`."
+ ) from e
+ except RepositoryNotFoundError as e:
+ logger.error(e)
+ raise EnvironmentError(
+ f"{path_or_repo} is not a local folder or a valid repository name on 'https://hf.co'."
+ ) from e
+ except RevisionNotFoundError as e:
+ logger.error(e)
+ raise EnvironmentError(
+ f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for this "
+ f"model name. Check the model page at 'https://huggingface.co/{path_or_repo}' for available revisions."
+ ) from e
+ except EntryNotFoundError:
+ return False # File does not exist
+ except requests.HTTPError:
+ # Any authentication/authorization error will be caught here => default to cache
+ return has_file_in_cache
+
+
+class PushToHubMixin:
+ """
+ A Mixin containing the functionality to push a model or tokenizer to the hub.
+ """
+
+ def _create_repo(
+ self,
+ repo_id: str,
+ private: Optional[bool] = None,
+ token: Optional[Union[bool, str]] = None,
+ repo_url: Optional[str] = None,
+ organization: Optional[str] = None,
+ ) -> str:
+ """
+ Create the repo if needed, cleans up repo_id with deprecated kwargs `repo_url` and `organization`, retrieves
+ the token.
+ """
+ if repo_url is not None:
+ warnings.warn(
+ "The `repo_url` argument is deprecated and will be removed in v5 of Transformers. Use `repo_id` "
+ "instead."
+ )
+ if repo_id is not None:
+ raise ValueError(
+ "`repo_id` and `repo_url` are both specified. Please set only the argument `repo_id`."
+ )
+ repo_id = repo_url.replace(f"{HUGGINGFACE_CO_RESOLVE_ENDPOINT}/", "")
+ if organization is not None:
+ warnings.warn(
+ "The `organization` argument is deprecated and will be removed in v5 of Transformers. Set your "
+ "organization directly in the `repo_id` passed instead (`repo_id={organization}/{model_id}`)."
+ )
+ if not repo_id.startswith(organization):
+ if "/" in repo_id:
+ repo_id = repo_id.split("/")[-1]
+ repo_id = f"{organization}/{repo_id}"
+
+ url = create_repo(repo_id=repo_id, token=token, private=private, exist_ok=True)
+ return url.repo_id
+
+ def _get_files_timestamps(self, working_dir: Union[str, os.PathLike]):
+ """
+ Returns the list of files with their last modification timestamp.
+ """
+ return {f: os.path.getmtime(os.path.join(working_dir, f)) for f in os.listdir(working_dir)}
+
+ def _upload_modified_files(
+ self,
+ working_dir: Union[str, os.PathLike],
+ repo_id: str,
+ files_timestamps: Dict[str, float],
+ commit_message: Optional[str] = None,
+ token: Optional[Union[bool, str]] = None,
+ create_pr: bool = False,
+ revision: str = None,
+ commit_description: str = None,
+ ):
+ """
+ Uploads all modified files in `working_dir` to `repo_id`, based on `files_timestamps`.
+ """
+ if commit_message is None:
+ if "Model" in self.__class__.__name__:
+ commit_message = "Upload model"
+ elif "Config" in self.__class__.__name__:
+ commit_message = "Upload config"
+ elif "Tokenizer" in self.__class__.__name__:
+ commit_message = "Upload tokenizer"
+ elif "FeatureExtractor" in self.__class__.__name__:
+ commit_message = "Upload feature extractor"
+ elif "Processor" in self.__class__.__name__:
+ commit_message = "Upload processor"
+ else:
+ commit_message = f"Upload {self.__class__.__name__}"
+ modified_files = [
+ f
+ for f in os.listdir(working_dir)
+ if f not in files_timestamps or os.path.getmtime(os.path.join(working_dir, f)) > files_timestamps[f]
+ ]
+
+ # filter for actual files + folders at the root level
+ modified_files = [
+ f
+ for f in modified_files
+ if os.path.isfile(os.path.join(working_dir, f)) or os.path.isdir(os.path.join(working_dir, f))
+ ]
+
+ operations = []
+ # upload standalone files
+ for file in modified_files:
+ if os.path.isdir(os.path.join(working_dir, file)):
+ # go over individual files of folder
+ for f in os.listdir(os.path.join(working_dir, file)):
+ operations.append(
+ CommitOperationAdd(
+ path_or_fileobj=os.path.join(working_dir, file, f), path_in_repo=os.path.join(file, f)
+ )
+ )
+ else:
+ operations.append(
+ CommitOperationAdd(path_or_fileobj=os.path.join(working_dir, file), path_in_repo=file)
+ )
+
+ if revision is not None and not revision.startswith("refs/pr"):
+ try:
+ create_branch(repo_id=repo_id, branch=revision, token=token, exist_ok=True)
+ except HfHubHTTPError as e:
+ if e.response.status_code == 403 and create_pr:
+ # If we are creating a PR on a repo we don't have access to, we can't create the branch.
+ # so let's assume the branch already exists. If it's not the case, an error will be raised when
+ # calling `create_commit` below.
+ pass
+ else:
+ raise
+
+ logger.info(f"Uploading the following files to {repo_id}: {','.join(modified_files)}")
+ return create_commit(
+ repo_id=repo_id,
+ operations=operations,
+ commit_message=commit_message,
+ commit_description=commit_description,
+ token=token,
+ create_pr=create_pr,
+ revision=revision,
+ )
+
+ def push_to_hub(
+ self,
+ repo_id: str,
+ use_temp_dir: Optional[bool] = None,
+ commit_message: Optional[str] = None,
+ private: Optional[bool] = None,
+ token: Optional[Union[bool, str]] = None,
+ max_shard_size: Optional[Union[int, str]] = "5GB",
+ create_pr: bool = False,
+ safe_serialization: bool = True,
+ revision: str = None,
+ commit_description: str = None,
+ tags: Optional[List[str]] = None,
+ **deprecated_kwargs,
+ ) -> str:
+ """
+ Upload the {object_files} to the 🤗 Model Hub.
+
+ Parameters:
+ repo_id (`str`):
+ The name of the repository you want to push your {object} to. It should contain your organization name
+ when pushing to a given organization.
+ use_temp_dir (`bool`, *optional*):
+ Whether or not to use a temporary directory to store the files saved before they are pushed to the Hub.
+ Will default to `True` if there is no directory named like `repo_id`, `False` otherwise.
+ commit_message (`str`, *optional*):
+ Message to commit while pushing. Will default to `"Upload {object}"`.
+ private (`bool`, *optional*):
+ Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
+ token (`bool` or `str`, *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`). Will default to `True` if `repo_url`
+ is not specified.
+ max_shard_size (`int` or `str`, *optional*, defaults to `"5GB"`):
+ Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard
+ will then be each of size lower than this size. If expressed as a string, needs to be digits followed
+ by a unit (like `"5MB"`). We default it to `"5GB"` so that users can easily load models on free-tier
+ Google Colab instances without any CPU OOM issues.
+ create_pr (`bool`, *optional*, defaults to `False`):
+ Whether or not to create a PR with the uploaded files or directly commit.
+ safe_serialization (`bool`, *optional*, defaults to `True`):
+ Whether or not to convert the model weights in safetensors format for safer serialization.
+ revision (`str`, *optional*):
+ Branch to push the uploaded files to.
+ commit_description (`str`, *optional*):
+ The description of the commit that will be created
+ tags (`List[str]`, *optional*):
+ List of tags to push on the Hub.
+
+ Examples:
+
+ ```python
+ from transformers import {object_class}
+
+ {object} = {object_class}.from_pretrained("google-bert/bert-base-cased")
+
+ # Push the {object} to your namespace with the name "my-finetuned-bert".
+ {object}.push_to_hub("my-finetuned-bert")
+
+ # Push the {object} to an organization with the name "my-finetuned-bert".
+ {object}.push_to_hub("huggingface/my-finetuned-bert")
+ ```
+ """
+ use_auth_token = deprecated_kwargs.pop("use_auth_token", None)
+ ignore_metadata_errors = deprecated_kwargs.pop("ignore_metadata_errors", False)
+ 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
+
+ repo_path_or_name = deprecated_kwargs.pop("repo_path_or_name", None)
+ if repo_path_or_name is not None:
+ # Should use `repo_id` instead of `repo_path_or_name`. When using `repo_path_or_name`, we try to infer
+ # repo_id from the folder path, if it exists.
+ warnings.warn(
+ "The `repo_path_or_name` argument is deprecated and will be removed in v5 of Transformers. Use "
+ "`repo_id` instead.",
+ FutureWarning,
+ )
+ if repo_id is not None:
+ raise ValueError(
+ "`repo_id` and `repo_path_or_name` are both specified. Please set only the argument `repo_id`."
+ )
+ if os.path.isdir(repo_path_or_name):
+ # repo_path: infer repo_id from the path
+ repo_id = repo_id.split(os.path.sep)[-1]
+ working_dir = repo_id
+ else:
+ # repo_name: use it as repo_id
+ repo_id = repo_path_or_name
+ working_dir = repo_id.split("/")[-1]
+ else:
+ # Repo_id is passed correctly: infer working_dir from it
+ working_dir = repo_id.split("/")[-1]
+
+ # Deprecation warning will be sent after for repo_url and organization
+ repo_url = deprecated_kwargs.pop("repo_url", None)
+ organization = deprecated_kwargs.pop("organization", None)
+
+ repo_id = self._create_repo(
+ repo_id, private=private, token=token, repo_url=repo_url, organization=organization
+ )
+
+ # Create a new empty model card and eventually tag it
+ model_card = create_and_tag_model_card(
+ repo_id, tags, token=token, ignore_metadata_errors=ignore_metadata_errors
+ )
+
+ if use_temp_dir is None:
+ use_temp_dir = not os.path.isdir(working_dir)
+
+ with working_or_temp_dir(working_dir=working_dir, use_temp_dir=use_temp_dir) as work_dir:
+ files_timestamps = self._get_files_timestamps(work_dir)
+
+ # Save all files.
+ self.save_pretrained(work_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)
+
+ # Update model card if needed:
+ model_card.save(os.path.join(work_dir, "README.md"))
+
+ return self._upload_modified_files(
+ work_dir,
+ repo_id,
+ files_timestamps,
+ commit_message=commit_message,
+ token=token,
+ create_pr=create_pr,
+ revision=revision,
+ commit_description=commit_description,
+ )
+
+
+def send_example_telemetry(example_name, *example_args, framework="pytorch"):
+ """
+ Sends telemetry that helps tracking the examples use.
+
+ Args:
+ example_name (`str`): The name of the example.
+ *example_args (dataclasses or `argparse.ArgumentParser`): The arguments to the script. This function will only
+ try to extract the model and dataset name from those. Nothing else is tracked.
+ framework (`str`, *optional*, defaults to `"pytorch"`): The framework for the example.
+ """
+ if is_offline_mode():
+ return
+
+ data = {"example": example_name, "framework": framework}
+ for args in example_args:
+ args_as_dict = {k: v for k, v in args.__dict__.items() if not k.startswith("_") and v is not None}
+ if "model_name_or_path" in args_as_dict:
+ model_name = args_as_dict["model_name_or_path"]
+ # Filter out local paths
+ if not os.path.isdir(model_name):
+ data["model_name"] = args_as_dict["model_name_or_path"]
+ if "dataset_name" in args_as_dict:
+ data["dataset_name"] = args_as_dict["dataset_name"]
+ elif "task_name" in args_as_dict:
+ # Extract script name from the example_name
+ script_name = example_name.replace("tf_", "").replace("flax_", "").replace("run_", "")
+ script_name = script_name.replace("_no_trainer", "")
+ data["dataset_name"] = f"{script_name}-{args_as_dict['task_name']}"
+
+ # Send telemetry in the background
+ send_telemetry(
+ topic="examples", library_name="transformers", library_version=__version__, user_agent=http_user_agent(data)
+ )
+
+
+def convert_file_size_to_int(size: Union[int, str]):
+ """
+ Converts a size expressed as a string with digits an unit (like `"5MB"`) to an integer (in bytes).
+
+ Args:
+ size (`int` or `str`): The size to convert. Will be directly returned if an `int`.
+
+ Example:
+ ```py
+ >>> convert_file_size_to_int("1MiB")
+ 1048576
+ ```
+ """
+ if isinstance(size, int):
+ return size
+ if size.upper().endswith("GIB"):
+ return int(size[:-3]) * (2**30)
+ if size.upper().endswith("MIB"):
+ return int(size[:-3]) * (2**20)
+ if size.upper().endswith("KIB"):
+ return int(size[:-3]) * (2**10)
+ if size.upper().endswith("GB"):
+ int_size = int(size[:-2]) * (10**9)
+ return int_size // 8 if size.endswith("b") else int_size
+ if size.upper().endswith("MB"):
+ int_size = int(size[:-2]) * (10**6)
+ return int_size // 8 if size.endswith("b") else int_size
+ if size.upper().endswith("KB"):
+ int_size = int(size[:-2]) * (10**3)
+ return int_size // 8 if size.endswith("b") else int_size
+ raise ValueError("`size` is not in a valid format. Use an integer followed by the unit, e.g., '5GB'.")
+
+
+def get_checkpoint_shard_files(
+ pretrained_model_name_or_path,
+ index_filename,
+ cache_dir=None,
+ force_download=False,
+ proxies=None,
+ resume_download=None,
+ local_files_only=False,
+ token=None,
+ user_agent=None,
+ revision=None,
+ subfolder="",
+ _commit_hash=None,
+ **deprecated_kwargs,
+):
+ """
+ For a given model:
+
+ - download and cache all the shards of a sharded checkpoint if `pretrained_model_name_or_path` is a model ID on the
+ Hub
+ - returns the list of paths to all the shards, as well as some metadata.
+
+ For the description of each arg, see [`PreTrainedModel.from_pretrained`]. `index_filename` is the full path to the
+ index (downloaded and cached if `pretrained_model_name_or_path` is a model ID on the Hub).
+ """
+ import json
+
+ use_auth_token = deprecated_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
+
+ if not os.path.isfile(index_filename):
+ raise ValueError(f"Can't find a checkpoint index ({index_filename}) in {pretrained_model_name_or_path}.")
+
+ with open(index_filename, "r") as f:
+ index = json.loads(f.read())
+
+ shard_filenames = sorted(set(index["weight_map"].values()))
+ sharded_metadata = index["metadata"]
+ sharded_metadata["all_checkpoint_keys"] = list(index["weight_map"].keys())
+ sharded_metadata["weight_map"] = index["weight_map"].copy()
+
+ # First, let's deal with local folder.
+ if os.path.isdir(pretrained_model_name_or_path):
+ shard_filenames = [os.path.join(pretrained_model_name_or_path, subfolder, f) for f in shard_filenames]
+ return shard_filenames, sharded_metadata
+
+ # At this stage pretrained_model_name_or_path is a model identifier on the Hub. Try to get everything from cache,
+ # or download the files
+ cached_filenames = cached_files(
+ pretrained_model_name_or_path,
+ shard_filenames,
+ cache_dir=cache_dir,
+ force_download=force_download,
+ proxies=proxies,
+ resume_download=resume_download,
+ local_files_only=local_files_only,
+ token=token,
+ user_agent=user_agent,
+ revision=revision,
+ subfolder=subfolder,
+ _commit_hash=_commit_hash,
+ )
+
+ return cached_filenames, sharded_metadata
+
+
+def create_and_tag_model_card(
+ repo_id: str,
+ tags: Optional[List[str]] = None,
+ token: Optional[str] = None,
+ ignore_metadata_errors: bool = False,
+):
+ """
+ Creates or loads an existing model card and tags it.
+
+ Args:
+ repo_id (`str`):
+ The repo_id where to look for the model card.
+ tags (`List[str]`, *optional*):
+ The list of tags to add in the model card
+ token (`str`, *optional*):
+ Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to the stored token.
+ ignore_metadata_errors (`str`):
+ If True, errors while parsing the metadata section will be ignored. Some information might be lost during
+ the process. Use it at your own risk.
+ """
+ try:
+ # Check if the model card is present on the remote repo
+ model_card = ModelCard.load(repo_id, token=token, ignore_metadata_errors=ignore_metadata_errors)
+ except EntryNotFoundError:
+ # Otherwise create a simple model card from template
+ model_description = "This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated."
+ card_data = ModelCardData(tags=[] if tags is None else tags, library_name="transformers")
+ model_card = ModelCard.from_template(card_data, model_description=model_description)
+
+ if tags is not None:
+ # Ensure model_card.data.tags is a list and not None
+ if model_card.data.tags is None:
+ model_card.data.tags = []
+ for model_tag in tags:
+ if model_tag not in model_card.data.tags:
+ model_card.data.tags.append(model_tag)
+
+ return model_card
+
+
+class PushInProgress:
+ """
+ Internal class to keep track of a push in progress (which might contain multiple `Future` jobs).
+ """
+
+ def __init__(self, jobs: Optional[futures.Future] = None) -> None:
+ self.jobs = [] if jobs is None else jobs
+
+ def is_done(self):
+ return all(job.done() for job in self.jobs)
+
+ def wait_until_done(self):
+ futures.wait(self.jobs)
+
+ def cancel(self) -> None:
+ self.jobs = [
+ job
+ for job in self.jobs
+ # Cancel the job if it wasn't started yet and remove cancelled/done jobs from the list
+ if not (job.cancel() or job.done())
+ ]
diff --git a/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/import_utils.py b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/import_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f114b925482758db285eec9b9a98ed7cdd6b5fd3
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/import_utils.py
@@ -0,0 +1,2399 @@
+# 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 utilities: Utilities related to imports and our lazy inits.
+"""
+
+import importlib.machinery
+import importlib.metadata
+import importlib.util
+import json
+import os
+import shutil
+import subprocess
+import sys
+import warnings
+from collections import OrderedDict
+from functools import lru_cache
+from itertools import chain
+from types import ModuleType
+from typing import Any, Dict, FrozenSet, Optional, Set, Tuple, Union
+
+from packaging import version
+
+from . import logging
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+# TODO: This doesn't work for all packages (`bs4`, `faiss`, etc.) Talk to Sylvain to see how to do with it better.
+def _is_package_available(pkg_name: str, return_version: bool = False) -> Union[Tuple[bool, str], bool]:
+ # Check if the package spec exists and grab its version to avoid importing a local directory
+ package_exists = importlib.util.find_spec(pkg_name) is not None
+ package_version = "N/A"
+ if package_exists:
+ try:
+ # Primary method to get the package version
+ package_version = importlib.metadata.version(pkg_name)
+ except importlib.metadata.PackageNotFoundError:
+ # Fallback method: Only for "torch" and versions containing "dev"
+ if pkg_name == "torch":
+ try:
+ package = importlib.import_module(pkg_name)
+ temp_version = getattr(package, "__version__", "N/A")
+ # Check if the version contains "dev"
+ if "dev" in temp_version:
+ package_version = temp_version
+ package_exists = True
+ else:
+ package_exists = False
+ except ImportError:
+ # If the package can't be imported, it's not available
+ package_exists = False
+ else:
+ # For packages other than "torch", don't attempt the fallback and set as not available
+ package_exists = False
+ logger.debug(f"Detected {pkg_name} version: {package_version}")
+ if return_version:
+ return package_exists, package_version
+ else:
+ return package_exists
+
+
+ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"}
+ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"})
+
+USE_TF = os.environ.get("USE_TF", "AUTO").upper()
+USE_TORCH = os.environ.get("USE_TORCH", "AUTO").upper()
+USE_JAX = os.environ.get("USE_FLAX", "AUTO").upper()
+
+# Try to run a native pytorch job in an environment with TorchXLA installed by setting this value to 0.
+USE_TORCH_XLA = os.environ.get("USE_TORCH_XLA", "1").upper()
+
+FORCE_TF_AVAILABLE = os.environ.get("FORCE_TF_AVAILABLE", "AUTO").upper()
+
+# `transformers` requires `torch>=1.11` but this variable is exposed publicly, and we can't simply remove it.
+# This is the version of torch required to run torch.fx features and torch.onnx with dictionary inputs.
+TORCH_FX_REQUIRED_VERSION = version.parse("1.10")
+
+ACCELERATE_MIN_VERSION = "0.26.0"
+SCHEDULEFREE_MIN_VERSION = "1.2.6"
+FSDP_MIN_VERSION = "1.12.0"
+GGUF_MIN_VERSION = "0.10.0"
+XLA_FSDPV2_MIN_VERSION = "2.2.0"
+HQQ_MIN_VERSION = "0.2.1"
+VPTQ_MIN_VERSION = "0.0.4"
+
+
+_accelerate_available, _accelerate_version = _is_package_available("accelerate", return_version=True)
+_apex_available = _is_package_available("apex")
+_apollo_torch_available = _is_package_available("apollo_torch")
+_aqlm_available = _is_package_available("aqlm")
+_vptq_available, _vptq_version = _is_package_available("vptq", return_version=True)
+_av_available = importlib.util.find_spec("av") is not None
+_decord_available = importlib.util.find_spec("decord") is not None
+_bitsandbytes_available = _is_package_available("bitsandbytes")
+_eetq_available = _is_package_available("eetq")
+_fbgemm_gpu_available = _is_package_available("fbgemm_gpu")
+_galore_torch_available = _is_package_available("galore_torch")
+_lomo_available = _is_package_available("lomo_optim")
+_grokadamw_available = _is_package_available("grokadamw")
+_schedulefree_available, _schedulefree_version = _is_package_available("schedulefree", return_version=True)
+# `importlib.metadata.version` doesn't work with `bs4` but `beautifulsoup4`. For `importlib.util.find_spec`, reversed.
+_bs4_available = importlib.util.find_spec("bs4") is not None
+_coloredlogs_available = _is_package_available("coloredlogs")
+# `importlib.metadata.util` doesn't work with `opencv-python-headless`.
+_cv2_available = importlib.util.find_spec("cv2") is not None
+_yt_dlp_available = importlib.util.find_spec("yt_dlp") is not None
+_datasets_available = _is_package_available("datasets")
+_detectron2_available = _is_package_available("detectron2")
+# We need to check both `faiss` and `faiss-cpu`.
+_faiss_available = importlib.util.find_spec("faiss") is not None
+try:
+ _faiss_version = importlib.metadata.version("faiss")
+ logger.debug(f"Successfully imported faiss version {_faiss_version}")
+except importlib.metadata.PackageNotFoundError:
+ try:
+ _faiss_version = importlib.metadata.version("faiss-cpu")
+ logger.debug(f"Successfully imported faiss version {_faiss_version}")
+ except importlib.metadata.PackageNotFoundError:
+ _faiss_available = False
+_ftfy_available = _is_package_available("ftfy")
+_g2p_en_available = _is_package_available("g2p_en")
+_hadamard_available = _is_package_available("fast_hadamard_transform")
+_ipex_available, _ipex_version = _is_package_available("intel_extension_for_pytorch", return_version=True)
+_jieba_available = _is_package_available("jieba")
+_jinja_available = _is_package_available("jinja2")
+_kenlm_available = _is_package_available("kenlm")
+_keras_nlp_available = _is_package_available("keras_nlp")
+_levenshtein_available = _is_package_available("Levenshtein")
+_librosa_available = _is_package_available("librosa")
+_natten_available = _is_package_available("natten")
+_nltk_available = _is_package_available("nltk")
+_onnx_available = _is_package_available("onnx")
+_openai_available = _is_package_available("openai")
+_optimum_available = _is_package_available("optimum")
+_auto_gptq_available = _is_package_available("auto_gptq")
+_gptqmodel_available = _is_package_available("gptqmodel")
+# `importlib.metadata.version` doesn't work with `awq`
+_auto_awq_available = importlib.util.find_spec("awq") is not None
+_is_optimum_quanto_available = False
+try:
+ importlib.metadata.version("optimum_quanto")
+ _is_optimum_quanto_available = True
+except importlib.metadata.PackageNotFoundError:
+ _is_optimum_quanto_available = False
+# For compressed_tensors, only check spec to allow compressed_tensors-nightly package
+_compressed_tensors_available = importlib.util.find_spec("compressed_tensors") is not None
+_pandas_available = _is_package_available("pandas")
+_peft_available = _is_package_available("peft")
+_phonemizer_available = _is_package_available("phonemizer")
+_uroman_available = _is_package_available("uroman")
+_psutil_available = _is_package_available("psutil")
+_py3nvml_available = _is_package_available("py3nvml")
+_pyctcdecode_available = _is_package_available("pyctcdecode")
+_pygments_available = _is_package_available("pygments")
+_pytesseract_available = _is_package_available("pytesseract")
+_pytest_available = _is_package_available("pytest")
+_pytorch_quantization_available = _is_package_available("pytorch_quantization")
+_rjieba_available = _is_package_available("rjieba")
+_sacremoses_available = _is_package_available("sacremoses")
+_safetensors_available = _is_package_available("safetensors")
+_scipy_available = _is_package_available("scipy")
+_sentencepiece_available = _is_package_available("sentencepiece")
+_is_seqio_available = _is_package_available("seqio")
+_is_gguf_available, _gguf_version = _is_package_available("gguf", return_version=True)
+_sklearn_available = importlib.util.find_spec("sklearn") is not None
+if _sklearn_available:
+ try:
+ importlib.metadata.version("scikit-learn")
+ except importlib.metadata.PackageNotFoundError:
+ _sklearn_available = False
+_smdistributed_available = importlib.util.find_spec("smdistributed") is not None
+_soundfile_available = _is_package_available("soundfile")
+_spacy_available = _is_package_available("spacy")
+_sudachipy_available, _sudachipy_version = _is_package_available("sudachipy", return_version=True)
+_tensorflow_probability_available = _is_package_available("tensorflow_probability")
+_tensorflow_text_available = _is_package_available("tensorflow_text")
+_tf2onnx_available = _is_package_available("tf2onnx")
+_timm_available = _is_package_available("timm")
+_tokenizers_available = _is_package_available("tokenizers")
+_torchaudio_available = _is_package_available("torchaudio")
+_torchao_available = _is_package_available("torchao")
+_torchdistx_available = _is_package_available("torchdistx")
+_torchvision_available, _torchvision_version = _is_package_available("torchvision", return_version=True)
+_mlx_available = _is_package_available("mlx")
+_num2words_available = _is_package_available("num2words")
+_hqq_available, _hqq_version = _is_package_available("hqq", return_version=True)
+_tiktoken_available = _is_package_available("tiktoken")
+_blobfile_available = _is_package_available("blobfile")
+_liger_kernel_available = _is_package_available("liger_kernel")
+_triton_available = _is_package_available("triton")
+_spqr_available = _is_package_available("spqr_quant")
+_rich_available = _is_package_available("rich")
+
+_torch_version = "N/A"
+_torch_available = False
+if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES:
+ _torch_available, _torch_version = _is_package_available("torch", return_version=True)
+else:
+ logger.info("Disabling PyTorch because USE_TF is set")
+ _torch_available = False
+
+
+_tf_version = "N/A"
+_tf_available = False
+if FORCE_TF_AVAILABLE in ENV_VARS_TRUE_VALUES:
+ _tf_available = True
+else:
+ if USE_TF in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TORCH not in ENV_VARS_TRUE_VALUES:
+ # Note: _is_package_available("tensorflow") fails for tensorflow-cpu. Please test any changes to the line below
+ # with tensorflow-cpu to make sure it still works!
+ _tf_available = importlib.util.find_spec("tensorflow") is not None
+ if _tf_available:
+ candidates = (
+ "tensorflow",
+ "tensorflow-cpu",
+ "tensorflow-gpu",
+ "tf-nightly",
+ "tf-nightly-cpu",
+ "tf-nightly-gpu",
+ "tf-nightly-rocm",
+ "intel-tensorflow",
+ "intel-tensorflow-avx512",
+ "tensorflow-rocm",
+ "tensorflow-macos",
+ "tensorflow-aarch64",
+ )
+ _tf_version = None
+ # For the metadata, we have to look for both tensorflow and tensorflow-cpu
+ for pkg in candidates:
+ try:
+ _tf_version = importlib.metadata.version(pkg)
+ break
+ except importlib.metadata.PackageNotFoundError:
+ pass
+ _tf_available = _tf_version is not None
+ if _tf_available:
+ if version.parse(_tf_version) < version.parse("2"):
+ logger.info(
+ f"TensorFlow found but with version {_tf_version}. Transformers requires version 2 minimum."
+ )
+ _tf_available = False
+ else:
+ logger.info("Disabling Tensorflow because USE_TORCH is set")
+
+
+_essentia_available = importlib.util.find_spec("essentia") is not None
+try:
+ _essentia_version = importlib.metadata.version("essentia")
+ logger.debug(f"Successfully imported essentia version {_essentia_version}")
+except importlib.metadata.PackageNotFoundError:
+ _essentia_version = False
+
+
+_pretty_midi_available = importlib.util.find_spec("pretty_midi") is not None
+try:
+ _pretty_midi_version = importlib.metadata.version("pretty_midi")
+ logger.debug(f"Successfully imported pretty_midi version {_pretty_midi_version}")
+except importlib.metadata.PackageNotFoundError:
+ _pretty_midi_available = False
+
+
+ccl_version = "N/A"
+_is_ccl_available = (
+ importlib.util.find_spec("torch_ccl") is not None
+ or importlib.util.find_spec("oneccl_bindings_for_pytorch") is not None
+)
+try:
+ ccl_version = importlib.metadata.version("oneccl_bind_pt")
+ logger.debug(f"Detected oneccl_bind_pt version {ccl_version}")
+except importlib.metadata.PackageNotFoundError:
+ _is_ccl_available = False
+
+
+_flax_available = False
+if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES:
+ _flax_available, _flax_version = _is_package_available("flax", return_version=True)
+ if _flax_available:
+ _jax_available, _jax_version = _is_package_available("jax", return_version=True)
+ if _jax_available:
+ logger.info(f"JAX version {_jax_version}, Flax version {_flax_version} available.")
+ else:
+ _flax_available = _jax_available = False
+ _jax_version = _flax_version = "N/A"
+
+
+_torch_fx_available = False
+if _torch_available:
+ torch_version = version.parse(_torch_version)
+ _torch_fx_available = (torch_version.major, torch_version.minor) >= (
+ TORCH_FX_REQUIRED_VERSION.major,
+ TORCH_FX_REQUIRED_VERSION.minor,
+ )
+
+
+_torch_xla_available = False
+if USE_TORCH_XLA in ENV_VARS_TRUE_VALUES:
+ _torch_xla_available, _torch_xla_version = _is_package_available("torch_xla", return_version=True)
+ if _torch_xla_available:
+ logger.info(f"Torch XLA version {_torch_xla_version} available.")
+
+
+def is_kenlm_available():
+ return _kenlm_available
+
+
+def is_cv2_available():
+ return _cv2_available
+
+
+def is_yt_dlp_available():
+ return _yt_dlp_available
+
+
+def is_torch_available():
+ return _torch_available
+
+
+def is_accelerate_available(min_version: str = ACCELERATE_MIN_VERSION):
+ return _accelerate_available and version.parse(_accelerate_version) >= version.parse(min_version)
+
+
+def is_torch_deterministic():
+ """
+ Check whether pytorch uses deterministic algorithms by looking if torch.set_deterministic_debug_mode() is set to 1 or 2"
+ """
+ import torch
+
+ if torch.get_deterministic_debug_mode() == 0:
+ return False
+ else:
+ return True
+
+
+def is_hadamard_available():
+ return _hadamard_available
+
+
+def is_hqq_available(min_version: str = HQQ_MIN_VERSION):
+ return _hqq_available and version.parse(_hqq_version) >= version.parse(min_version)
+
+
+def is_pygments_available():
+ return _pygments_available
+
+
+def get_torch_version():
+ return _torch_version
+
+
+def is_torch_sdpa_available():
+ if not is_torch_available():
+ return False
+ elif _torch_version == "N/A":
+ return False
+
+ # NOTE: We require torch>=2.1 (and not torch>=2.0) to use SDPA in Transformers for two reasons:
+ # - Allow the global use of the `scale` argument introduced in https://github.com/pytorch/pytorch/pull/95259
+ # - Memory-efficient attention supports arbitrary attention_mask: https://github.com/pytorch/pytorch/pull/104310
+ # NOTE: MLU is OK with non-contiguous inputs.
+ if is_torch_mlu_available():
+ return version.parse(_torch_version) >= version.parse("2.1.0")
+ # NOTE: NPU can use SDPA in Transformers with torch>=2.1.0.
+ if is_torch_npu_available():
+ return version.parse(_torch_version) >= version.parse("2.1.0")
+ # NOTE: We require torch>=2.1.1 to avoid a numerical issue in SDPA with non-contiguous inputs: https://github.com/pytorch/pytorch/issues/112577
+ return version.parse(_torch_version) >= version.parse("2.1.1")
+
+
+def is_torch_flex_attn_available():
+ if not is_torch_available():
+ return False
+ elif _torch_version == "N/A":
+ return False
+
+ # TODO check if some bugs cause push backs on the exact version
+ # NOTE: We require torch>=2.5.0 as it is the first release
+ return version.parse(_torch_version) >= version.parse("2.5.0")
+
+
+def is_torchvision_available():
+ return _torchvision_available
+
+
+def is_torchvision_v2_available():
+ if not is_torchvision_available():
+ return False
+
+ # NOTE: We require torchvision>=0.15 as v2 transforms are available from this version: https://pytorch.org/vision/stable/transforms.html#v1-or-v2-which-one-should-i-use
+ return version.parse(_torchvision_version) >= version.parse("0.15")
+
+
+def is_galore_torch_available():
+ return _galore_torch_available
+
+
+def is_apollo_torch_available():
+ return _apollo_torch_available
+
+
+def is_lomo_available():
+ return _lomo_available
+
+
+def is_grokadamw_available():
+ return _grokadamw_available
+
+
+def is_schedulefree_available(min_version: str = SCHEDULEFREE_MIN_VERSION):
+ return _schedulefree_available and version.parse(_schedulefree_version) >= version.parse(min_version)
+
+
+def is_pyctcdecode_available():
+ return _pyctcdecode_available
+
+
+def is_librosa_available():
+ return _librosa_available
+
+
+def is_essentia_available():
+ return _essentia_available
+
+
+def is_pretty_midi_available():
+ return _pretty_midi_available
+
+
+def is_torch_cuda_available():
+ if is_torch_available():
+ import torch
+
+ return torch.cuda.is_available()
+ else:
+ return False
+
+
+def is_mamba_ssm_available():
+ if is_torch_available():
+ import torch
+
+ if not torch.cuda.is_available():
+ return False
+ else:
+ return _is_package_available("mamba_ssm")
+ return False
+
+
+def is_mamba_2_ssm_available():
+ if is_torch_available():
+ import torch
+
+ if not torch.cuda.is_available():
+ return False
+ else:
+ if _is_package_available("mamba_ssm"):
+ import mamba_ssm
+
+ if version.parse(mamba_ssm.__version__) >= version.parse("2.0.4"):
+ return True
+ return False
+
+
+def is_causal_conv1d_available():
+ if is_torch_available():
+ import torch
+
+ if not torch.cuda.is_available():
+ return False
+ return _is_package_available("causal_conv1d")
+ return False
+
+
+def is_mambapy_available():
+ if is_torch_available():
+ return _is_package_available("mambapy")
+ return False
+
+
+def is_torch_mps_available(min_version: Optional[str] = None):
+ if is_torch_available():
+ import torch
+
+ if hasattr(torch.backends, "mps"):
+ backend_available = torch.backends.mps.is_available() and torch.backends.mps.is_built()
+ if min_version is not None:
+ flag = version.parse(_torch_version) >= version.parse(min_version)
+ backend_available = backend_available and flag
+ return backend_available
+ return False
+
+
+def is_torch_bf16_gpu_available():
+ if not is_torch_available():
+ return False
+
+ import torch
+
+ return torch.cuda.is_available() and torch.cuda.is_bf16_supported()
+
+
+def is_torch_bf16_cpu_available():
+ if not is_torch_available():
+ return False
+
+ import torch
+
+ try:
+ # multiple levels of AttributeError depending on the pytorch version so do them all in one check
+ _ = torch.cpu.amp.autocast
+ except AttributeError:
+ return False
+
+ return True
+
+
+def is_torch_bf16_available():
+ # the original bf16 check was for gpu only, but later a cpu/bf16 combo has emerged so this util
+ # has become ambiguous and therefore deprecated
+ warnings.warn(
+ "The util is_torch_bf16_available is deprecated, please use is_torch_bf16_gpu_available "
+ "or is_torch_bf16_cpu_available instead according to whether it's used with cpu or gpu",
+ FutureWarning,
+ )
+ return is_torch_bf16_gpu_available()
+
+
+@lru_cache()
+def is_torch_fp16_available_on_device(device):
+ if not is_torch_available():
+ return False
+
+ if is_torch_hpu_available():
+ if is_habana_gaudi1():
+ return False
+ else:
+ return True
+
+ import torch
+
+ try:
+ x = torch.zeros(2, 2, dtype=torch.float16).to(device)
+ _ = x @ x
+
+ # At this moment, let's be strict of the check: check if `LayerNorm` is also supported on device, because many
+ # models use this layer.
+ batch, sentence_length, embedding_dim = 3, 4, 5
+ embedding = torch.randn(batch, sentence_length, embedding_dim, dtype=torch.float16, device=device)
+ layer_norm = torch.nn.LayerNorm(embedding_dim, dtype=torch.float16, device=device)
+ _ = layer_norm(embedding)
+
+ except: # noqa: E722
+ # TODO: more precise exception matching, if possible.
+ # most backends should return `RuntimeError` however this is not guaranteed.
+ return False
+
+ return True
+
+
+@lru_cache()
+def is_torch_bf16_available_on_device(device):
+ if not is_torch_available():
+ return False
+
+ import torch
+
+ if device == "cuda":
+ return is_torch_bf16_gpu_available()
+
+ if device == "hpu":
+ return True
+
+ try:
+ x = torch.zeros(2, 2, dtype=torch.bfloat16).to(device)
+ _ = x @ x
+ except: # noqa: E722
+ # TODO: more precise exception matching, if possible.
+ # most backends should return `RuntimeError` however this is not guaranteed.
+ return False
+
+ return True
+
+
+def is_torch_tf32_available():
+ if not is_torch_available():
+ return False
+
+ import torch
+
+ if not torch.cuda.is_available() or torch.version.cuda is None:
+ return False
+ if torch.cuda.get_device_properties(torch.cuda.current_device()).major < 8:
+ return False
+ if int(torch.version.cuda.split(".")[0]) < 11:
+ return False
+ if version.parse(version.parse(torch.__version__).base_version) < version.parse("1.7"):
+ return False
+
+ return True
+
+
+def is_torch_fx_available():
+ return _torch_fx_available
+
+
+def is_peft_available():
+ return _peft_available
+
+
+def is_bs4_available():
+ return _bs4_available
+
+
+def is_tf_available():
+ return _tf_available
+
+
+def is_coloredlogs_available():
+ return _coloredlogs_available
+
+
+def is_tf2onnx_available():
+ return _tf2onnx_available
+
+
+def is_onnx_available():
+ return _onnx_available
+
+
+def is_openai_available():
+ return _openai_available
+
+
+def is_flax_available():
+ return _flax_available
+
+
+def is_flute_available():
+ try:
+ return importlib.util.find_spec("flute") is not None and importlib.metadata.version("flute-kernel") >= "0.4.1"
+ except importlib.metadata.PackageNotFoundError:
+ return False
+
+
+def is_ftfy_available():
+ return _ftfy_available
+
+
+def is_g2p_en_available():
+ return _g2p_en_available
+
+
+@lru_cache()
+def is_torch_tpu_available(check_device=True):
+ "Checks if `torch_xla` is installed and potentially if a TPU is in the environment"
+ warnings.warn(
+ "`is_torch_tpu_available` is deprecated and will be removed in 4.41.0. "
+ "Please use the `is_torch_xla_available` instead.",
+ FutureWarning,
+ )
+
+ if not _torch_available:
+ return False
+ if importlib.util.find_spec("torch_xla") is not None:
+ if check_device:
+ # We need to check if `xla_device` can be found, will raise a RuntimeError if not
+ try:
+ import torch_xla.core.xla_model as xm
+
+ _ = xm.xla_device()
+ return True
+ except RuntimeError:
+ return False
+ return True
+ return False
+
+
+@lru_cache
+def is_torch_xla_available(check_is_tpu=False, check_is_gpu=False):
+ """
+ Check if `torch_xla` is available. To train a native pytorch job in an environment with torch xla installed, set
+ the USE_TORCH_XLA to false.
+ """
+ assert not (check_is_tpu and check_is_gpu), "The check_is_tpu and check_is_gpu cannot both be true."
+
+ if not _torch_xla_available:
+ return False
+
+ import torch_xla
+
+ if check_is_gpu:
+ return torch_xla.runtime.device_type() in ["GPU", "CUDA"]
+ elif check_is_tpu:
+ return torch_xla.runtime.device_type() == "TPU"
+
+ return True
+
+
+@lru_cache()
+def is_torch_neuroncore_available(check_device=True):
+ if importlib.util.find_spec("torch_neuronx") is not None:
+ return is_torch_xla_available()
+ return False
+
+
+@lru_cache()
+def is_torch_npu_available(check_device=False):
+ "Checks if `torch_npu` is installed and potentially if a NPU is in the environment"
+ if not _torch_available or importlib.util.find_spec("torch_npu") is None:
+ return False
+
+ import torch
+ import torch_npu # noqa: F401
+
+ if check_device:
+ try:
+ # Will raise a RuntimeError if no NPU is found
+ _ = torch.npu.device_count()
+ return torch.npu.is_available()
+ except RuntimeError:
+ return False
+ return hasattr(torch, "npu") and torch.npu.is_available()
+
+
+@lru_cache()
+def is_torch_mlu_available(check_device=False):
+ """
+ Checks if `mlu` is available via an `cndev-based` check which won't trigger the drivers and leave mlu
+ uninitialized.
+ """
+ if not _torch_available or importlib.util.find_spec("torch_mlu") is None:
+ return False
+
+ import torch
+ import torch_mlu # noqa: F401
+
+ pytorch_cndev_based_mlu_check_previous_value = os.environ.get("PYTORCH_CNDEV_BASED_MLU_CHECK")
+ try:
+ os.environ["PYTORCH_CNDEV_BASED_MLU_CHECK"] = str(1)
+ available = torch.mlu.is_available()
+ finally:
+ if pytorch_cndev_based_mlu_check_previous_value:
+ os.environ["PYTORCH_CNDEV_BASED_MLU_CHECK"] = pytorch_cndev_based_mlu_check_previous_value
+ else:
+ os.environ.pop("PYTORCH_CNDEV_BASED_MLU_CHECK", None)
+
+ return available
+
+
+@lru_cache()
+def is_torch_musa_available(check_device=False):
+ "Checks if `torch_musa` is installed and potentially if a MUSA is in the environment"
+ if not _torch_available or importlib.util.find_spec("torch_musa") is None:
+ return False
+
+ import torch
+ import torch_musa # noqa: F401
+
+ torch_musa_min_version = "0.33.0"
+ if _accelerate_available and version.parse(_accelerate_version) < version.parse(torch_musa_min_version):
+ return False
+
+ if check_device:
+ try:
+ # Will raise a RuntimeError if no MUSA is found
+ _ = torch.musa.device_count()
+ return torch.musa.is_available()
+ except RuntimeError:
+ return False
+ return hasattr(torch, "musa") and torch.musa.is_available()
+
+
+@lru_cache
+def is_torch_hpu_available():
+ "Checks if `torch.hpu` is available and potentially if a HPU is in the environment"
+ if (
+ not _torch_available
+ or importlib.util.find_spec("habana_frameworks") is None
+ or importlib.util.find_spec("habana_frameworks.torch") is None
+ ):
+ return False
+
+ torch_hpu_min_version = "1.5.0"
+ if _accelerate_available and version.parse(_accelerate_version) < version.parse(torch_hpu_min_version):
+ return False
+
+ import torch
+
+ if not hasattr(torch, "hpu") or not torch.hpu.is_available():
+ return False
+
+ import habana_frameworks.torch.utils.experimental as htexp # noqa: F401
+
+ # IlyasMoutawwakil: We patch masked_fill_ for int64 tensors to avoid a bug on Gaudi1
+ # synNodeCreateWithId failed for node: masked_fill_fwd_i64 with synStatus 26 [Generic failure]
+ # This can be removed once Gaudi1 support is discontinued but for now we need it to keep using
+ # dl1.24xlarge Gaudi1 instances on AWS for testing.
+ # check if the device is Gaudi1 (vs Gaudi2, Gaudi3).
+ if htexp._get_device_type() == htexp.synDeviceType.synDeviceGaudi:
+ original_masked_fill_ = torch.Tensor.masked_fill_
+
+ def patched_masked_fill_(self, mask, value):
+ if self.dtype == torch.int64:
+ logger.warning(
+ "In-place tensor.masked_fill_(mask, value) is not supported for int64 tensors on Gaudi1. "
+ "This operation will be performed out-of-place using tensor[mask] = value."
+ )
+ self[mask] = value
+ else:
+ original_masked_fill_(self, mask, value)
+
+ torch.Tensor.masked_fill_ = patched_masked_fill_
+
+ return True
+
+
+@lru_cache
+def is_habana_gaudi1():
+ if not is_torch_hpu_available():
+ return False
+
+ import habana_frameworks.torch.utils.experimental as htexp # noqa: F401
+
+ # Check if the device is Gaudi1 (vs Gaudi2, Gaudi3)
+ return htexp._get_device_type() == htexp.synDeviceType.synDeviceGaudi
+
+
+def is_torchdynamo_available():
+ if not is_torch_available():
+ return False
+
+ return version.parse(_torch_version) >= version.parse("2.0.0")
+
+
+def is_torch_compile_available():
+ if not is_torch_available():
+ return False
+
+ import torch
+
+ # We don't do any version check here to support nighlies marked as 1.14. Ultimately needs to check version against
+ # 2.0 but let's do it later.
+ return hasattr(torch, "compile")
+
+
+def is_torchdynamo_compiling():
+ if not is_torch_available():
+ return False
+
+ # Importing torch._dynamo causes issues with PyTorch profiler (https://github.com/pytorch/pytorch/issues/130622)
+ # hence rather relying on `torch.compiler.is_compiling()` when possible (torch>=2.3)
+ try:
+ import torch
+
+ return torch.compiler.is_compiling()
+ except Exception:
+ try:
+ import torch._dynamo as dynamo # noqa: F401
+
+ return dynamo.is_compiling()
+ except Exception:
+ return False
+
+
+def is_torch_tensorrt_fx_available():
+ if importlib.util.find_spec("torch_tensorrt") is None:
+ return False
+ return importlib.util.find_spec("torch_tensorrt.fx") is not None
+
+
+def is_datasets_available():
+ return _datasets_available
+
+
+def is_detectron2_available():
+ return _detectron2_available
+
+
+def is_rjieba_available():
+ return _rjieba_available
+
+
+def is_psutil_available():
+ return _psutil_available
+
+
+def is_py3nvml_available():
+ return _py3nvml_available
+
+
+def is_sacremoses_available():
+ return _sacremoses_available
+
+
+def is_apex_available():
+ return _apex_available
+
+
+def is_aqlm_available():
+ return _aqlm_available
+
+
+def is_vptq_available(min_version: str = VPTQ_MIN_VERSION):
+ return _vptq_available and version.parse(_vptq_version) >= version.parse(min_version)
+
+
+def is_av_available():
+ return _av_available
+
+
+def is_decord_available():
+ return _decord_available
+
+
+def is_ninja_available():
+ r"""
+ Code comes from *torch.utils.cpp_extension.is_ninja_available()*. Returns `True` if the
+ [ninja](https://ninja-build.org/) build system is available on the system, `False` otherwise.
+ """
+ try:
+ subprocess.check_output("ninja --version".split())
+ except Exception:
+ return False
+ else:
+ return True
+
+
+def is_ipex_available(min_version: str = ""):
+ def get_major_and_minor_from_version(full_version):
+ return str(version.parse(full_version).major) + "." + str(version.parse(full_version).minor)
+
+ if not is_torch_available() or not _ipex_available:
+ return False
+
+ torch_major_and_minor = get_major_and_minor_from_version(_torch_version)
+ ipex_major_and_minor = get_major_and_minor_from_version(_ipex_version)
+ if torch_major_and_minor != ipex_major_and_minor:
+ logger.warning(
+ f"Intel Extension for PyTorch {ipex_major_and_minor} needs to work with PyTorch {ipex_major_and_minor}.*,"
+ f" but PyTorch {_torch_version} is found. Please switch to the matching version and run again."
+ )
+ return False
+ if min_version:
+ return version.parse(_ipex_version) >= version.parse(min_version)
+ return True
+
+
+@lru_cache
+def is_torch_xpu_available(check_device=False):
+ """
+ Checks if XPU acceleration is available either via native PyTorch (>=2.6),
+ `intel_extension_for_pytorch` or via stock PyTorch (>=2.4) and potentially
+ if a XPU is in the environment.
+ """
+ if not is_torch_available():
+ return False
+
+ torch_version = version.parse(_torch_version)
+ if torch_version.major < 2 or (torch_version.major == 2 and torch_version.minor < 6):
+ if is_ipex_available():
+ import intel_extension_for_pytorch # noqa: F401
+ elif torch_version.major < 2 or (torch_version.major == 2 and torch_version.minor < 4):
+ return False
+
+ import torch
+
+ if check_device:
+ try:
+ # Will raise a RuntimeError if no XPU is found
+ _ = torch.xpu.device_count()
+ return torch.xpu.is_available()
+ except RuntimeError:
+ return False
+ return hasattr(torch, "xpu") and torch.xpu.is_available()
+
+
+@lru_cache()
+def is_bitsandbytes_available():
+ if not is_torch_available() or not _bitsandbytes_available:
+ return False
+
+ import torch
+
+ # `bitsandbytes` versions older than 0.43.1 eagerly require CUDA at import time,
+ # so those versions of the library are practically only available when CUDA is too.
+ if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.43.1"):
+ return torch.cuda.is_available()
+
+ # Newer versions of `bitsandbytes` can be imported on systems without CUDA.
+ return True
+
+
+def is_bitsandbytes_multi_backend_available() -> bool:
+ if not is_bitsandbytes_available():
+ return False
+
+ import bitsandbytes as bnb
+
+ return "multi_backend" in getattr(bnb, "features", set())
+
+
+def is_flash_attn_2_available():
+ if not is_torch_available():
+ return False
+
+ if not _is_package_available("flash_attn"):
+ return False
+
+ # Let's add an extra check to see if cuda is available
+ import torch
+
+ if not (torch.cuda.is_available() or is_torch_mlu_available()):
+ return False
+
+ # Ascend does not support "flash_attn".
+ # If "flash_attn" is left in the env, is_flash_attn_2_available() should return False.
+ if is_torch_npu_available():
+ return False
+
+ if torch.version.cuda:
+ return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.1.0")
+ elif torch.version.hip:
+ # TODO: Bump the requirement to 2.1.0 once released in https://github.com/ROCmSoftwarePlatform/flash-attention
+ return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.0.4")
+ elif is_torch_mlu_available():
+ return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.3.3")
+ else:
+ return False
+
+
+@lru_cache()
+def is_flash_attn_greater_or_equal_2_10():
+ if not _is_package_available("flash_attn"):
+ return False
+
+ return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.1.0")
+
+
+@lru_cache()
+def is_flash_attn_greater_or_equal(library_version: str):
+ if not _is_package_available("flash_attn"):
+ return False
+
+ return version.parse(importlib.metadata.version("flash_attn")) >= version.parse(library_version)
+
+
+@lru_cache()
+def is_torch_greater_or_equal(library_version: str):
+ if not _is_package_available("torch"):
+ return False
+
+ return version.parse(importlib.metadata.version("torch")) >= version.parse(library_version)
+
+
+def is_torchdistx_available():
+ return _torchdistx_available
+
+
+def is_faiss_available():
+ return _faiss_available
+
+
+def is_scipy_available():
+ return _scipy_available
+
+
+def is_sklearn_available():
+ return _sklearn_available
+
+
+def is_sentencepiece_available():
+ return _sentencepiece_available
+
+
+def is_seqio_available():
+ return _is_seqio_available
+
+
+def is_gguf_available(min_version: str = GGUF_MIN_VERSION):
+ return _is_gguf_available and version.parse(_gguf_version) >= version.parse(min_version)
+
+
+def is_protobuf_available():
+ if importlib.util.find_spec("google") is None:
+ return False
+ return importlib.util.find_spec("google.protobuf") is not None
+
+
+def is_fsdp_available(min_version: str = FSDP_MIN_VERSION):
+ return is_torch_available() and version.parse(_torch_version) >= version.parse(min_version)
+
+
+def is_optimum_available():
+ return _optimum_available
+
+
+def is_auto_awq_available():
+ return _auto_awq_available
+
+
+def is_optimum_quanto_available():
+ # `importlib.metadata.version` doesn't work with `optimum.quanto`, need to put `optimum_quanto`
+ return _is_optimum_quanto_available
+
+
+def is_compressed_tensors_available():
+ return _compressed_tensors_available
+
+
+def is_auto_gptq_available():
+ return _auto_gptq_available
+
+
+def is_gptqmodel_available():
+ return _gptqmodel_available
+
+
+def is_eetq_available():
+ return _eetq_available
+
+
+def is_fbgemm_gpu_available():
+ return _fbgemm_gpu_available
+
+
+def is_levenshtein_available():
+ return _levenshtein_available
+
+
+def is_optimum_neuron_available():
+ return _optimum_available and _is_package_available("optimum.neuron")
+
+
+def is_safetensors_available():
+ return _safetensors_available
+
+
+def is_tokenizers_available():
+ return _tokenizers_available
+
+
+@lru_cache
+def is_vision_available():
+ _pil_available = importlib.util.find_spec("PIL") is not None
+ if _pil_available:
+ try:
+ package_version = importlib.metadata.version("Pillow")
+ except importlib.metadata.PackageNotFoundError:
+ try:
+ package_version = importlib.metadata.version("Pillow-SIMD")
+ except importlib.metadata.PackageNotFoundError:
+ return False
+ logger.debug(f"Detected PIL version {package_version}")
+ return _pil_available
+
+
+def is_pytesseract_available():
+ return _pytesseract_available
+
+
+def is_pytest_available():
+ return _pytest_available
+
+
+def is_spacy_available():
+ return _spacy_available
+
+
+def is_tensorflow_text_available():
+ return is_tf_available() and _tensorflow_text_available
+
+
+def is_keras_nlp_available():
+ return is_tensorflow_text_available() and _keras_nlp_available
+
+
+def is_in_notebook():
+ try:
+ # Test adapted from tqdm.autonotebook: https://github.com/tqdm/tqdm/blob/master/tqdm/autonotebook.py
+ get_ipython = sys.modules["IPython"].get_ipython
+ if "IPKernelApp" not in get_ipython().config:
+ raise ImportError("console")
+ # Removed the lines to include VSCode
+ if "DATABRICKS_RUNTIME_VERSION" in os.environ and os.environ["DATABRICKS_RUNTIME_VERSION"] < "11.0":
+ # Databricks Runtime 11.0 and above uses IPython kernel by default so it should be compatible with Jupyter notebook
+ # https://docs.microsoft.com/en-us/azure/databricks/notebooks/ipython-kernel
+ raise ImportError("databricks")
+
+ return importlib.util.find_spec("IPython") is not None
+ except (AttributeError, ImportError, KeyError):
+ return False
+
+
+def is_pytorch_quantization_available():
+ return _pytorch_quantization_available
+
+
+def is_tensorflow_probability_available():
+ return _tensorflow_probability_available
+
+
+def is_pandas_available():
+ return _pandas_available
+
+
+def is_sagemaker_dp_enabled():
+ # Get the sagemaker specific env variable.
+ sagemaker_params = os.getenv("SM_FRAMEWORK_PARAMS", "{}")
+ try:
+ # Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
+ sagemaker_params = json.loads(sagemaker_params)
+ if not sagemaker_params.get("sagemaker_distributed_dataparallel_enabled", False):
+ return False
+ except json.JSONDecodeError:
+ return False
+ # Lastly, check if the `smdistributed` module is present.
+ return _smdistributed_available
+
+
+def is_sagemaker_mp_enabled():
+ # Get the sagemaker specific mp parameters from smp_options variable.
+ smp_options = os.getenv("SM_HP_MP_PARAMETERS", "{}")
+ try:
+ # Parse it and check the field "partitions" is included, it is required for model parallel.
+ smp_options = json.loads(smp_options)
+ if "partitions" not in smp_options:
+ return False
+ except json.JSONDecodeError:
+ return False
+
+ # Get the sagemaker specific framework parameters from mpi_options variable.
+ mpi_options = os.getenv("SM_FRAMEWORK_PARAMS", "{}")
+ try:
+ # Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
+ mpi_options = json.loads(mpi_options)
+ if not mpi_options.get("sagemaker_mpi_enabled", False):
+ return False
+ except json.JSONDecodeError:
+ return False
+ # Lastly, check if the `smdistributed` module is present.
+ return _smdistributed_available
+
+
+def is_training_run_on_sagemaker():
+ return "SAGEMAKER_JOB_NAME" in os.environ
+
+
+def is_soundfile_available():
+ return _soundfile_available
+
+
+def is_timm_available():
+ return _timm_available
+
+
+def is_natten_available():
+ return _natten_available
+
+
+def is_nltk_available():
+ return _nltk_available
+
+
+def is_torchaudio_available():
+ return _torchaudio_available
+
+
+def is_torchao_available():
+ return _torchao_available
+
+
+def is_speech_available():
+ # For now this depends on torchaudio but the exact dependency might evolve in the future.
+ return _torchaudio_available
+
+
+def is_spqr_available():
+ return _spqr_available
+
+
+def is_phonemizer_available():
+ return _phonemizer_available
+
+
+def is_uroman_available():
+ return _uroman_available
+
+
+def torch_only_method(fn):
+ def wrapper(*args, **kwargs):
+ if not _torch_available:
+ raise ImportError(
+ "You need to install pytorch to use this method or class, "
+ "or activate it with environment variables USE_TORCH=1 and USE_TF=0."
+ )
+ else:
+ return fn(*args, **kwargs)
+
+ return wrapper
+
+
+def is_ccl_available():
+ return _is_ccl_available
+
+
+def is_sudachi_available():
+ return _sudachipy_available
+
+
+def get_sudachi_version():
+ return _sudachipy_version
+
+
+def is_sudachi_projection_available():
+ if not is_sudachi_available():
+ return False
+
+ # NOTE: We require sudachipy>=0.6.8 to use projection option in sudachi_kwargs for the constructor of BertJapaneseTokenizer.
+ # - `projection` option is not supported in sudachipy<0.6.8, see https://github.com/WorksApplications/sudachi.rs/issues/230
+ return version.parse(_sudachipy_version) >= version.parse("0.6.8")
+
+
+def is_jumanpp_available():
+ return (importlib.util.find_spec("rhoknp") is not None) and (shutil.which("jumanpp") is not None)
+
+
+def is_cython_available():
+ return importlib.util.find_spec("pyximport") is not None
+
+
+def is_jieba_available():
+ return _jieba_available
+
+
+def is_jinja_available():
+ return _jinja_available
+
+
+def is_mlx_available():
+ return _mlx_available
+
+
+def is_num2words_available():
+ return _num2words_available
+
+
+def is_tiktoken_available():
+ return _tiktoken_available and _blobfile_available
+
+
+def is_liger_kernel_available():
+ if not _liger_kernel_available:
+ return False
+
+ return version.parse(importlib.metadata.version("liger_kernel")) >= version.parse("0.3.0")
+
+
+def is_triton_available():
+ return _triton_available
+
+
+def is_rich_available():
+ return _rich_available
+
+
+# docstyle-ignore
+AV_IMPORT_ERROR = """
+{0} requires the PyAv library but it was not found in your environment. You can install it with:
+```
+pip install av
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+YT_DLP_IMPORT_ERROR = """
+{0} requires the YT-DLP library but it was not found in your environment. You can install it with:
+```
+pip install yt-dlp
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+DECORD_IMPORT_ERROR = """
+{0} requires the PyAv library but it was not found in your environment. You can install it with:
+```
+pip install decord
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+CV2_IMPORT_ERROR = """
+{0} requires the OpenCV library but it was not found in your environment. You can install it with:
+```
+pip install opencv-python
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+DATASETS_IMPORT_ERROR = """
+{0} requires the 🤗 Datasets library but it was not found in your environment. You can install it with:
+```
+pip install datasets
+```
+In a notebook or a colab, you can install it by executing a cell with
+```
+!pip install datasets
+```
+then restarting your kernel.
+
+Note that if you have a local folder named `datasets` or a local python file named `datasets.py` in your current
+working directory, python may try to import this instead of the 🤗 Datasets library. You should rename this folder or
+that python file if that's the case. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+TOKENIZERS_IMPORT_ERROR = """
+{0} requires the 🤗 Tokenizers library but it was not found in your environment. You can install it with:
+```
+pip install tokenizers
+```
+In a notebook or a colab, you can install it by executing a cell with
+```
+!pip install tokenizers
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+SENTENCEPIECE_IMPORT_ERROR = """
+{0} requires the SentencePiece library but it was not found in your environment. Checkout the instructions on the
+installation page of its repo: https://github.com/google/sentencepiece#installation and follow the ones
+that match your environment. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+PROTOBUF_IMPORT_ERROR = """
+{0} requires the protobuf library but it was not found in your environment. Checkout the instructions on the
+installation page of its repo: https://github.com/protocolbuffers/protobuf/tree/master/python#installation and follow the ones
+that match your environment. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+FAISS_IMPORT_ERROR = """
+{0} requires the faiss library but it was not found in your environment. Checkout the instructions on the
+installation page of its repo: https://github.com/facebookresearch/faiss/blob/master/INSTALL.md and follow the ones
+that match your environment. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+PYTORCH_IMPORT_ERROR = """
+{0} requires the PyTorch library but it was not found in your environment. Checkout the instructions on the
+installation page: https://pytorch.org/get-started/locally/ and follow the ones that match your environment.
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+TORCHVISION_IMPORT_ERROR = """
+{0} requires the Torchvision library but it was not found in your environment. Checkout the instructions on the
+installation page: https://pytorch.org/get-started/locally/ and follow the ones that match your environment.
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+PYTORCH_IMPORT_ERROR_WITH_TF = """
+{0} requires the PyTorch library but it was not found in your environment.
+However, we were able to find a TensorFlow installation. TensorFlow classes begin
+with "TF", but are otherwise identically named to our PyTorch classes. This
+means that the TF equivalent of the class you tried to import would be "TF{0}".
+If you want to use TensorFlow, please use TF classes instead!
+
+If you really do want to use PyTorch please go to
+https://pytorch.org/get-started/locally/ and follow the instructions that
+match your environment.
+"""
+
+# docstyle-ignore
+TF_IMPORT_ERROR_WITH_PYTORCH = """
+{0} requires the TensorFlow library but it was not found in your environment.
+However, we were able to find a PyTorch installation. PyTorch classes do not begin
+with "TF", but are otherwise identically named to our TF classes.
+If you want to use PyTorch, please use those classes instead!
+
+If you really do want to use TensorFlow, please follow the instructions on the
+installation page https://www.tensorflow.org/install that match your environment.
+"""
+
+# docstyle-ignore
+BS4_IMPORT_ERROR = """
+{0} requires the Beautiful Soup library but it was not found in your environment. You can install it with pip:
+`pip install beautifulsoup4`. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+SKLEARN_IMPORT_ERROR = """
+{0} requires the scikit-learn library but it was not found in your environment. You can install it with:
+```
+pip install -U scikit-learn
+```
+In a notebook or a colab, you can install it by executing a cell with
+```
+!pip install -U scikit-learn
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+TENSORFLOW_IMPORT_ERROR = """
+{0} requires the TensorFlow library but it was not found in your environment. Checkout the instructions on the
+installation page: https://www.tensorflow.org/install and follow the ones that match your environment.
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+DETECTRON2_IMPORT_ERROR = """
+{0} requires the detectron2 library but it was not found in your environment. Checkout the instructions on the
+installation page: https://github.com/facebookresearch/detectron2/blob/master/INSTALL.md and follow the ones
+that match your environment. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+FLAX_IMPORT_ERROR = """
+{0} requires the FLAX library but it was not found in your environment. Checkout the instructions on the
+installation page: https://github.com/google/flax and follow the ones that match your environment.
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+FTFY_IMPORT_ERROR = """
+{0} requires the ftfy library but it was not found in your environment. Checkout the instructions on the
+installation section: https://github.com/rspeer/python-ftfy/tree/master#installing and follow the ones
+that match your environment. Please note that you may need to restart your runtime after installation.
+"""
+
+LEVENSHTEIN_IMPORT_ERROR = """
+{0} requires the python-Levenshtein library but it was not found in your environment. You can install it with pip: `pip
+install python-Levenshtein`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+G2P_EN_IMPORT_ERROR = """
+{0} requires the g2p-en library but it was not found in your environment. You can install it with pip:
+`pip install g2p-en`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+PYTORCH_QUANTIZATION_IMPORT_ERROR = """
+{0} requires the pytorch-quantization library but it was not found in your environment. You can install it with pip:
+`pip install pytorch-quantization --extra-index-url https://pypi.ngc.nvidia.com`
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+TENSORFLOW_PROBABILITY_IMPORT_ERROR = """
+{0} requires the tensorflow_probability library but it was not found in your environment. You can install it with pip as
+explained here: https://github.com/tensorflow/probability. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+TENSORFLOW_TEXT_IMPORT_ERROR = """
+{0} requires the tensorflow_text library but it was not found in your environment. You can install it with pip as
+explained here: https://www.tensorflow.org/text/guide/tf_text_intro.
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+TORCHAUDIO_IMPORT_ERROR = """
+{0} requires the torchaudio library but it was not found in your environment. Please install it and restart your
+runtime.
+"""
+
+# docstyle-ignore
+PANDAS_IMPORT_ERROR = """
+{0} requires the pandas library but it was not found in your environment. You can install it with pip as
+explained here: https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html.
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+PHONEMIZER_IMPORT_ERROR = """
+{0} requires the phonemizer library but it was not found in your environment. You can install it with pip:
+`pip install phonemizer`. Please note that you may need to restart your runtime after installation.
+"""
+# docstyle-ignore
+UROMAN_IMPORT_ERROR = """
+{0} requires the uroman library but it was not found in your environment. You can install it with pip:
+`pip install uroman`. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+SACREMOSES_IMPORT_ERROR = """
+{0} requires the sacremoses library but it was not found in your environment. You can install it with pip:
+`pip install sacremoses`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+SCIPY_IMPORT_ERROR = """
+{0} requires the scipy library but it was not found in your environment. You can install it with pip:
+`pip install scipy`. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+SPEECH_IMPORT_ERROR = """
+{0} requires the torchaudio library but it was not found in your environment. You can install it with pip:
+`pip install torchaudio`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+TIMM_IMPORT_ERROR = """
+{0} requires the timm library but it was not found in your environment. You can install it with pip:
+`pip install timm`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+NATTEN_IMPORT_ERROR = """
+{0} requires the natten library but it was not found in your environment. You can install it by referring to:
+shi-labs.com/natten . You can also install it with pip (may take longer to build):
+`pip install natten`. Please note that you may need to restart your runtime after installation.
+"""
+
+NUMEXPR_IMPORT_ERROR = """
+{0} requires the numexpr library but it was not found in your environment. You can install it by referring to:
+https://numexpr.readthedocs.io/en/latest/index.html.
+"""
+
+
+# docstyle-ignore
+NLTK_IMPORT_ERROR = """
+{0} requires the NLTK library but it was not found in your environment. You can install it by referring to:
+https://www.nltk.org/install.html. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+VISION_IMPORT_ERROR = """
+{0} requires the PIL library but it was not found in your environment. You can install it with pip:
+`pip install pillow`. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+PYTESSERACT_IMPORT_ERROR = """
+{0} requires the PyTesseract library but it was not found in your environment. You can install it with pip:
+`pip install pytesseract`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+PYCTCDECODE_IMPORT_ERROR = """
+{0} requires the pyctcdecode library but it was not found in your environment. You can install it with pip:
+`pip install pyctcdecode`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+ACCELERATE_IMPORT_ERROR = """
+{0} requires the accelerate library >= {ACCELERATE_MIN_VERSION} it was not found in your environment.
+You can install or update it with pip: `pip install --upgrade accelerate`. Please note that you may need to restart your
+runtime after installation.
+"""
+
+# docstyle-ignore
+CCL_IMPORT_ERROR = """
+{0} requires the torch ccl library but it was not found in your environment. You can install it with pip:
+`pip install oneccl_bind_pt -f https://developer.intel.com/ipex-whl-stable`
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+ESSENTIA_IMPORT_ERROR = """
+{0} requires essentia library. But that was not found in your environment. You can install them with pip:
+`pip install essentia==2.1b6.dev1034`
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+LIBROSA_IMPORT_ERROR = """
+{0} requires thes librosa library. But that was not found in your environment. You can install them with pip:
+`pip install librosa`
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+PRETTY_MIDI_IMPORT_ERROR = """
+{0} requires thes pretty_midi library. But that was not found in your environment. You can install them with pip:
+`pip install pretty_midi`
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+CYTHON_IMPORT_ERROR = """
+{0} requires the Cython library but it was not found in your environment. You can install it with pip: `pip install
+Cython`. Please note that you may need to restart your runtime after installation.
+"""
+
+JIEBA_IMPORT_ERROR = """
+{0} requires the jieba library but it was not found in your environment. You can install it with pip: `pip install
+jieba`. Please note that you may need to restart your runtime after installation.
+"""
+
+PEFT_IMPORT_ERROR = """
+{0} requires the peft library but it was not found in your environment. You can install it with pip: `pip install
+peft`. Please note that you may need to restart your runtime after installation.
+"""
+
+JINJA_IMPORT_ERROR = """
+{0} requires the jinja library but it was not found in your environment. You can install it with pip: `pip install
+jinja2`. Please note that you may need to restart your runtime after installation.
+"""
+
+RICH_IMPORT_ERROR = """
+{0} requires the rich library but it was not found in your environment. You can install it with pip: `pip install
+rich`. Please note that you may need to restart your runtime after installation.
+"""
+
+BACKENDS_MAPPING = OrderedDict(
+ [
+ ("av", (is_av_available, AV_IMPORT_ERROR)),
+ ("bs4", (is_bs4_available, BS4_IMPORT_ERROR)),
+ ("cv2", (is_cv2_available, CV2_IMPORT_ERROR)),
+ ("datasets", (is_datasets_available, DATASETS_IMPORT_ERROR)),
+ ("decord", (is_decord_available, DECORD_IMPORT_ERROR)),
+ ("detectron2", (is_detectron2_available, DETECTRON2_IMPORT_ERROR)),
+ ("essentia", (is_essentia_available, ESSENTIA_IMPORT_ERROR)),
+ ("faiss", (is_faiss_available, FAISS_IMPORT_ERROR)),
+ ("flax", (is_flax_available, FLAX_IMPORT_ERROR)),
+ ("ftfy", (is_ftfy_available, FTFY_IMPORT_ERROR)),
+ ("g2p_en", (is_g2p_en_available, G2P_EN_IMPORT_ERROR)),
+ ("pandas", (is_pandas_available, PANDAS_IMPORT_ERROR)),
+ ("phonemizer", (is_phonemizer_available, PHONEMIZER_IMPORT_ERROR)),
+ ("uroman", (is_uroman_available, UROMAN_IMPORT_ERROR)),
+ ("pretty_midi", (is_pretty_midi_available, PRETTY_MIDI_IMPORT_ERROR)),
+ ("levenshtein", (is_levenshtein_available, LEVENSHTEIN_IMPORT_ERROR)),
+ ("librosa", (is_librosa_available, LIBROSA_IMPORT_ERROR)),
+ ("protobuf", (is_protobuf_available, PROTOBUF_IMPORT_ERROR)),
+ ("pyctcdecode", (is_pyctcdecode_available, PYCTCDECODE_IMPORT_ERROR)),
+ ("pytesseract", (is_pytesseract_available, PYTESSERACT_IMPORT_ERROR)),
+ ("sacremoses", (is_sacremoses_available, SACREMOSES_IMPORT_ERROR)),
+ ("pytorch_quantization", (is_pytorch_quantization_available, PYTORCH_QUANTIZATION_IMPORT_ERROR)),
+ ("sentencepiece", (is_sentencepiece_available, SENTENCEPIECE_IMPORT_ERROR)),
+ ("sklearn", (is_sklearn_available, SKLEARN_IMPORT_ERROR)),
+ ("speech", (is_speech_available, SPEECH_IMPORT_ERROR)),
+ ("tensorflow_probability", (is_tensorflow_probability_available, TENSORFLOW_PROBABILITY_IMPORT_ERROR)),
+ ("tf", (is_tf_available, TENSORFLOW_IMPORT_ERROR)),
+ ("tensorflow_text", (is_tensorflow_text_available, TENSORFLOW_TEXT_IMPORT_ERROR)),
+ ("timm", (is_timm_available, TIMM_IMPORT_ERROR)),
+ ("torchaudio", (is_torchaudio_available, TORCHAUDIO_IMPORT_ERROR)),
+ ("natten", (is_natten_available, NATTEN_IMPORT_ERROR)),
+ ("nltk", (is_nltk_available, NLTK_IMPORT_ERROR)),
+ ("tokenizers", (is_tokenizers_available, TOKENIZERS_IMPORT_ERROR)),
+ ("torch", (is_torch_available, PYTORCH_IMPORT_ERROR)),
+ ("torchvision", (is_torchvision_available, TORCHVISION_IMPORT_ERROR)),
+ ("vision", (is_vision_available, VISION_IMPORT_ERROR)),
+ ("scipy", (is_scipy_available, SCIPY_IMPORT_ERROR)),
+ ("accelerate", (is_accelerate_available, ACCELERATE_IMPORT_ERROR)),
+ ("oneccl_bind_pt", (is_ccl_available, CCL_IMPORT_ERROR)),
+ ("cython", (is_cython_available, CYTHON_IMPORT_ERROR)),
+ ("jieba", (is_jieba_available, JIEBA_IMPORT_ERROR)),
+ ("peft", (is_peft_available, PEFT_IMPORT_ERROR)),
+ ("jinja", (is_jinja_available, JINJA_IMPORT_ERROR)),
+ ("yt_dlp", (is_yt_dlp_available, YT_DLP_IMPORT_ERROR)),
+ ("rich", (is_rich_available, RICH_IMPORT_ERROR)),
+ ]
+)
+
+
+def requires_backends(obj, backends):
+ if not isinstance(backends, (list, tuple)):
+ backends = [backends]
+
+ name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
+
+ # Raise an error for users who might not realize that classes without "TF" are torch-only
+ if "torch" in backends and "tf" not in backends and not is_torch_available() and is_tf_available():
+ raise ImportError(PYTORCH_IMPORT_ERROR_WITH_TF.format(name))
+
+ # Raise the inverse error for PyTorch users trying to load TF classes
+ if "tf" in backends and "torch" not in backends and is_torch_available() and not is_tf_available():
+ raise ImportError(TF_IMPORT_ERROR_WITH_PYTORCH.format(name))
+
+ checks = (BACKENDS_MAPPING[backend] for backend in backends)
+ failed = [msg.format(name) for available, msg in checks if not available()]
+ if failed:
+ raise ImportError("".join(failed))
+
+
+class DummyObject(type):
+ """
+ Metaclass for the dummy objects. Any class inheriting from it will return the ImportError generated by
+ `requires_backend` each time a user tries to access any method of that class.
+ """
+
+ def __getattribute__(cls, key):
+ if key.startswith("_") and key != "_from_config":
+ return super().__getattribute__(key)
+ requires_backends(cls, cls._backends)
+
+
+def is_torch_fx_proxy(x):
+ if is_torch_fx_available():
+ import torch.fx
+
+ return isinstance(x, torch.fx.Proxy)
+ return False
+
+
+BACKENDS_T = FrozenSet[str]
+IMPORT_STRUCTURE_T = Dict[BACKENDS_T, Dict[str, Set[str]]]
+
+
+class _LazyModule(ModuleType):
+ """
+ Module class that surfaces all objects but only performs associated imports when the objects are requested.
+ """
+
+ # Very heavily inspired by optuna.integration._IntegrationModule
+ # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py
+ def __init__(
+ self,
+ name: str,
+ module_file: str,
+ import_structure: IMPORT_STRUCTURE_T,
+ module_spec: importlib.machinery.ModuleSpec = None,
+ extra_objects: Dict[str, object] = None,
+ ):
+ super().__init__(name)
+
+ self._object_missing_backend = {}
+ if any(isinstance(key, frozenset) for key in import_structure.keys()):
+ self._modules = set()
+ self._class_to_module = {}
+ self.__all__ = []
+
+ _import_structure = {}
+
+ for backends, module in import_structure.items():
+ missing_backends = []
+ for backend in backends:
+ if backend not in BACKENDS_MAPPING:
+ raise ValueError(
+ f"Error: the following backend: '{backend}' was specified around object {module} but isn't specified in the backends mapping."
+ )
+ callable, error = BACKENDS_MAPPING[backend]
+ if not callable():
+ missing_backends.append(backend)
+ self._modules = self._modules.union(set(module.keys()))
+
+ for key, values in module.items():
+ if len(missing_backends):
+ self._object_missing_backend[key] = missing_backends
+
+ for value in values:
+ self._class_to_module[value] = key
+ if len(missing_backends):
+ self._object_missing_backend[value] = missing_backends
+ _import_structure.setdefault(key, []).extend(values)
+
+ # Needed for autocompletion in an IDE
+ self.__all__.extend(list(module.keys()) + list(chain(*module.values())))
+
+ self.__file__ = module_file
+ self.__spec__ = module_spec
+ self.__path__ = [os.path.dirname(module_file)]
+ self._objects = {} if extra_objects is None else extra_objects
+ self._name = name
+ self._import_structure = _import_structure
+
+ # This can be removed once every exportable object has a `export()` export.
+ else:
+ self._modules = set(import_structure.keys())
+ self._class_to_module = {}
+ for key, values in import_structure.items():
+ for value in values:
+ self._class_to_module[value] = key
+ # Needed for autocompletion in an IDE
+ self.__all__ = list(import_structure.keys()) + list(chain(*import_structure.values()))
+ self.__file__ = module_file
+ self.__spec__ = module_spec
+ self.__path__ = [os.path.dirname(module_file)]
+ self._objects = {} if extra_objects is None else extra_objects
+ self._name = name
+ self._import_structure = import_structure
+
+ # Needed for autocompletion in an IDE
+ def __dir__(self):
+ result = super().__dir__()
+ # The elements of self.__all__ that are submodules may or may not be in the dir already, depending on whether
+ # they have been accessed or not. So we only add the elements of self.__all__ that are not already in the dir.
+ for attr in self.__all__:
+ if attr not in result:
+ result.append(attr)
+ return result
+
+ def __getattr__(self, name: str) -> Any:
+ if name in self._objects:
+ return self._objects[name]
+ if name in self._object_missing_backend.keys():
+ missing_backends = self._object_missing_backend[name]
+
+ class Placeholder(metaclass=DummyObject):
+ _backends = missing_backends
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, missing_backends)
+
+ Placeholder.__name__ = name
+ Placeholder.__module__ = self.__spec__
+
+ value = Placeholder
+ elif name in self._class_to_module.keys():
+ module = self._get_module(self._class_to_module[name])
+ value = getattr(module, name)
+ elif name in self._modules:
+ value = self._get_module(name)
+ else:
+ raise AttributeError(f"module {self.__name__} has no attribute {name}")
+
+ setattr(self, name, value)
+ return value
+
+ def _get_module(self, module_name: str):
+ try:
+ return importlib.import_module("." + module_name, self.__name__)
+ except Exception as e:
+ raise RuntimeError(
+ f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its"
+ f" traceback):\n{e}"
+ ) from e
+
+ def __reduce__(self):
+ return (self.__class__, (self._name, self.__file__, self._import_structure))
+
+
+class OptionalDependencyNotAvailable(BaseException):
+ """Internally used error class for signalling an optional dependency was not found."""
+
+
+def direct_transformers_import(path: str, file="__init__.py") -> ModuleType:
+ """Imports transformers directly
+
+ Args:
+ path (`str`): The path to the source file
+ file (`str`, *optional*): The file to join with the path. Defaults to "__init__.py".
+
+ Returns:
+ `ModuleType`: The resulting imported module
+ """
+ name = "transformers"
+ location = os.path.join(path, file)
+ spec = importlib.util.spec_from_file_location(name, location, submodule_search_locations=[path])
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ module = sys.modules[name]
+ return module
+
+
+def export(*, backends=()):
+ """
+ This decorator enables two things:
+ - Attaching a `__backends` tuple to an object to see what are the necessary backends for it
+ to execute correctly without instantiating it
+ - The '@export' string is used to dynamically import objects
+ """
+ for backend in backends:
+ if backend not in BACKENDS_MAPPING:
+ raise ValueError(f"Backend should be defined in the BACKENDS_MAPPING. Offending backend: {backend}")
+
+ if not isinstance(backends, tuple):
+ raise ValueError("Backends should be a tuple.")
+
+ def inner_fn(fun):
+ fun.__backends = backends
+ return fun
+
+ return inner_fn
+
+
+BASE_FILE_REQUIREMENTS = {
+ lambda e: "modeling_tf_" in e: ("tf",),
+ lambda e: "modeling_flax_" in e: ("flax",),
+ lambda e: "modeling_" in e: ("torch",),
+ lambda e: e.startswith("tokenization_") and e.endswith("_fast"): ("tokenizers",),
+}
+
+
+def fetch__all__(file_content):
+ """
+ Returns the content of the __all__ variable in the file content.
+ Returns None if not defined, otherwise returns a list of strings.
+ """
+
+ if "__all__" not in file_content:
+ return []
+
+ start_index = None
+ lines = file_content.splitlines()
+ for index, line in enumerate(lines):
+ if line.startswith("__all__"):
+ start_index = index
+
+ # There is no line starting with `__all__`
+ if start_index is None:
+ return []
+
+ lines = lines[start_index:]
+
+ if not lines[0].startswith("__all__"):
+ raise ValueError(
+ "fetch__all__ accepts a list of lines, with the first line being the __all__ variable declaration"
+ )
+
+ # __all__ is defined on a single line
+ if lines[0].endswith("]"):
+ return [obj.strip("\"' ") for obj in lines[0].split("=")[1].strip(" []").split(",")]
+
+ # __all__ is defined on multiple lines
+ else:
+ _all = []
+ for __all__line_index in range(1, len(lines)):
+ if lines[__all__line_index].strip() == "]":
+ return _all
+ else:
+ _all.append(lines[__all__line_index].strip("\"', "))
+
+ return _all
+
+
+@lru_cache()
+def create_import_structure_from_path(module_path):
+ """
+ This method takes the path to a file/a folder and returns the import structure.
+ If a file is given, it will return the import structure of the parent folder.
+
+ Import structures are designed to be digestible by `_LazyModule` objects. They are
+ created from the __all__ definitions in each files as well as the `@export` decorators
+ above methods and objects.
+
+ The import structure allows explicit display of the required backends for a given object.
+ These backends are specified in two ways:
+
+ 1. Through their `@export`, if they are exported with that decorator. This `@export` decorator
+ accepts a `backend` tuple kwarg mentioning which backends are required to run this object.
+
+ 2. If an object is defined in a file with "default" backends, it will have, at a minimum, this
+ backend specified. The default backends are defined according to the filename:
+
+ - If a file is named like `modeling_*.py`, it will have a `torch` backend
+ - If a file is named like `modeling_tf_*.py`, it will have a `tf` backend
+ - If a file is named like `modeling_flax_*.py`, it will have a `flax` backend
+ - If a file is named like `tokenization_*_fast.py`, it will have a `tokenizers` backend
+
+ Backends serve the purpose of displaying a clear error message to the user in case the backends are not installed.
+ Should an object be imported without its required backends being in the environment, any attempt to use the
+ object will raise an error mentioning which backend(s) should be added to the environment in order to use
+ that object.
+
+ Here's an example of an input import structure at the src.transformers.models level:
+
+ {
+ 'albert': {
+ frozenset(): {
+ 'configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'}
+ },
+ frozenset({'tokenizers'}): {
+ 'tokenization_albert_fast': {'AlbertTokenizerFast'}
+ },
+ },
+ 'align': {
+ frozenset(): {
+ 'configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
+ 'processing_align': {'AlignProcessor'}
+ },
+ },
+ 'altclip': {
+ frozenset(): {
+ 'configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
+ 'processing_altclip': {'AltCLIPProcessor'},
+ }
+ }
+ }
+ """
+ import_structure = {}
+ if os.path.isdir(module_path):
+ directory = module_path
+ adjacent_modules = []
+
+ for f in os.listdir(module_path):
+ if f != "__pycache__" and os.path.isdir(os.path.join(module_path, f)):
+ import_structure[f] = create_import_structure_from_path(os.path.join(module_path, f))
+
+ elif not os.path.isdir(os.path.join(directory, f)):
+ adjacent_modules.append(f)
+
+ else:
+ directory = os.path.dirname(module_path)
+ adjacent_modules = [f for f in os.listdir(directory) if not os.path.isdir(os.path.join(directory, f))]
+
+ # We're only taking a look at files different from __init__.py
+ # We could theoretically export things directly from the __init__.py
+ # files, but this is not supported at this time.
+ if "__init__.py" in adjacent_modules:
+ adjacent_modules.remove("__init__.py")
+
+ # Modular files should not be imported
+ def find_substring(substring, list_):
+ return any(substring in x for x in list_)
+
+ if find_substring("modular_", adjacent_modules) and find_substring("modeling_", adjacent_modules):
+ adjacent_modules = [module for module in adjacent_modules if "modular_" not in module]
+
+ module_requirements = {}
+ for module_name in adjacent_modules:
+ # Only modules ending in `.py` are accepted here.
+ if not module_name.endswith(".py"):
+ continue
+
+ with open(os.path.join(directory, module_name), encoding="utf-8") as f:
+ file_content = f.read()
+
+ # Remove the .py suffix
+ module_name = module_name[:-3]
+
+ previous_line = ""
+ previous_index = 0
+
+ # Some files have some requirements by default.
+ # For example, any file named `modeling_tf_xxx.py`
+ # should have TensorFlow as a required backend.
+ base_requirements = ()
+ for string_check, requirements in BASE_FILE_REQUIREMENTS.items():
+ if string_check(module_name):
+ base_requirements = requirements
+ break
+
+ # Objects that have a `@export` assigned to them will get exported
+ # with the backends specified in the decorator as well as the file backends.
+ exported_objects = set()
+ if "@export" in file_content:
+ lines = file_content.split("\n")
+ for index, line in enumerate(lines):
+ # This allows exporting items with other decorators. We'll take a look
+ # at the line that follows at the same indentation level.
+ if line.startswith((" ", "\t", "@", ")")) and not line.startswith("@export"):
+ continue
+
+ # Skipping line enables putting whatever we want between the
+ # export() call and the actual class/method definition.
+ # This is what enables having # Copied from statements, docs, etc.
+ skip_line = False
+
+ if "@export" in previous_line:
+ skip_line = False
+
+ # Backends are defined on the same line as export
+ if "backends" in previous_line:
+ backends_string = previous_line.split("backends=")[1].split("(")[1].split(")")[0]
+ backends = tuple(sorted([b.strip("'\",") for b in backends_string.split(", ") if b]))
+
+ # Backends are defined in the lines following export, for example such as:
+ # @export(
+ # backends=(
+ # "sentencepiece",
+ # "torch",
+ # "tf",
+ # )
+ # )
+ #
+ # or
+ #
+ # @export(
+ # backends=(
+ # "sentencepiece", "tf"
+ # )
+ # )
+ elif "backends" in lines[previous_index + 1]:
+ backends = []
+ for backend_line in lines[previous_index:index]:
+ if "backends" in backend_line:
+ backend_line = backend_line.split("=")[1]
+ if '"' in backend_line or "'" in backend_line:
+ if ", " in backend_line:
+ backends.extend(backend.strip("()\"', ") for backend in backend_line.split(", "))
+ else:
+ backends.append(backend_line.strip("()\"', "))
+
+ # If the line is only a ')', then we reached the end of the backends and we break.
+ if backend_line.strip() == ")":
+ break
+ backends = tuple(backends)
+
+ # No backends are registered for export
+ else:
+ backends = ()
+
+ backends = frozenset(backends + base_requirements)
+ if backends not in module_requirements:
+ module_requirements[backends] = {}
+ if module_name not in module_requirements[backends]:
+ module_requirements[backends][module_name] = set()
+
+ if not line.startswith("class") and not line.startswith("def"):
+ skip_line = True
+ else:
+ start_index = 6 if line.startswith("class") else 4
+ object_name = line[start_index:].split("(")[0].strip(":")
+ module_requirements[backends][module_name].add(object_name)
+ exported_objects.add(object_name)
+
+ if not skip_line:
+ previous_line = line
+ previous_index = index
+
+ # All objects that are in __all__ should be exported by default.
+ # These objects are exported with the file backends.
+ if "__all__" in file_content:
+ for _all_object in fetch__all__(file_content):
+ if _all_object not in exported_objects:
+ backends = frozenset(base_requirements)
+ if backends not in module_requirements:
+ module_requirements[backends] = {}
+ if module_name not in module_requirements[backends]:
+ module_requirements[backends][module_name] = set()
+
+ module_requirements[backends][module_name].add(_all_object)
+
+ import_structure = {**module_requirements, **import_structure}
+ return import_structure
+
+
+def spread_import_structure(nested_import_structure):
+ """
+ This method takes as input an unordered import structure and brings the required backends at the top-level,
+ aggregating modules and objects under their required backends.
+
+ Here's an example of an input import structure at the src.transformers.models level:
+
+ {
+ 'albert': {
+ frozenset(): {
+ 'configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'}
+ },
+ frozenset({'tokenizers'}): {
+ 'tokenization_albert_fast': {'AlbertTokenizerFast'}
+ },
+ },
+ 'align': {
+ frozenset(): {
+ 'configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
+ 'processing_align': {'AlignProcessor'}
+ },
+ },
+ 'altclip': {
+ frozenset(): {
+ 'configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
+ 'processing_altclip': {'AltCLIPProcessor'},
+ }
+ }
+ }
+
+ Here's an example of an output import structure at the src.transformers.models level:
+
+ {
+ frozenset({'tokenizers'}): {
+ 'albert.tokenization_albert_fast': {'AlbertTokenizerFast'}
+ },
+ frozenset(): {
+ 'albert.configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'},
+ 'align.processing_align': {'AlignProcessor'},
+ 'align.configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
+ 'altclip.configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
+ 'altclip.processing_altclip': {'AltCLIPProcessor'}
+ }
+ }
+
+ """
+
+ def propagate_frozenset(unordered_import_structure):
+ tuple_first_import_structure = {}
+ for _key, _value in unordered_import_structure.items():
+ if not isinstance(_value, dict):
+ tuple_first_import_structure[_key] = _value
+
+ elif any(isinstance(v, frozenset) for v in _value.keys()):
+ # Here we want to switch around key and v
+ for k, v in _value.items():
+ if isinstance(k, frozenset):
+ if k not in tuple_first_import_structure:
+ tuple_first_import_structure[k] = {}
+ tuple_first_import_structure[k][_key] = v
+
+ else:
+ tuple_first_import_structure[_key] = propagate_frozenset(_value)
+
+ return tuple_first_import_structure
+
+ def flatten_dict(_dict, previous_key=None):
+ items = []
+ for _key, _value in _dict.items():
+ _key = f"{previous_key}.{_key}" if previous_key is not None else _key
+ if isinstance(_value, dict):
+ items.extend(flatten_dict(_value, _key).items())
+ else:
+ items.append((_key, _value))
+ return dict(items)
+
+ # The tuples contain the necessary backends. We want these first, so we propagate them up the
+ # import structure.
+ ordered_import_structure = nested_import_structure
+
+ # 6 is a number that gives us sufficient depth to go through all files and foreseeable folder depths
+ # while not taking too long to parse.
+ for i in range(6):
+ ordered_import_structure = propagate_frozenset(ordered_import_structure)
+
+ # We then flatten the dict so that it references a module path.
+ flattened_import_structure = {}
+ for key, value in ordered_import_structure.copy().items():
+ if isinstance(key, str):
+ del ordered_import_structure[key]
+ else:
+ flattened_import_structure[key] = flatten_dict(value)
+
+ return flattened_import_structure
+
+
+def define_import_structure(module_path: str) -> IMPORT_STRUCTURE_T:
+ """
+ This method takes a module_path as input and creates an import structure digestible by a _LazyModule.
+
+ Here's an example of an output import structure at the src.transformers.models level:
+
+ {
+ frozenset({'tokenizers'}): {
+ 'albert.tokenization_albert_fast': {'AlbertTokenizerFast'}
+ },
+ frozenset(): {
+ 'albert.configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'},
+ 'align.processing_align': {'AlignProcessor'},
+ 'align.configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
+ 'altclip.configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
+ 'altclip.processing_altclip': {'AltCLIPProcessor'}
+ }
+ }
+
+ The import structure is a dict defined with frozensets as keys, and dicts of strings to sets of objects.
+ """
+ import_structure = create_import_structure_from_path(module_path)
+ return spread_import_structure(import_structure)
+
+
+def clear_import_cache():
+ """
+ Clear cached Transformers modules to allow reloading modified code.
+
+ This is useful when actively developing/modifying Transformers code.
+ """
+ # Get all transformers modules
+ transformers_modules = [mod_name for mod_name in sys.modules if mod_name.startswith("transformers.")]
+
+ # Remove them from sys.modules
+ for mod_name in transformers_modules:
+ module = sys.modules[mod_name]
+ # Clear _LazyModule caches if applicable
+ if isinstance(module, _LazyModule):
+ module._objects = {} # Clear cached objects
+ del sys.modules[mod_name]
+
+ # Force reload main transformers module
+ if "transformers" in sys.modules:
+ main_module = sys.modules["transformers"]
+ if isinstance(main_module, _LazyModule):
+ main_module._objects = {} # Clear cached objects
+ importlib.reload(main_module)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/logging.py b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..67f70b96eddcb29fb4c1978c5132622e94c5ffea
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/logging.py
@@ -0,0 +1,411 @@
+# coding=utf-8
+# Copyright 2020 Optuna, Hugging Face
+#
+# 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.
+"""Logging utilities."""
+
+import functools
+import logging
+import os
+import sys
+import threading
+from logging import (
+ CRITICAL, # NOQA
+ DEBUG, # NOQA
+ ERROR, # NOQA
+ FATAL, # NOQA
+ INFO, # NOQA
+ NOTSET, # NOQA
+ WARN, # NOQA
+ WARNING, # NOQA
+)
+from logging import captureWarnings as _captureWarnings
+from typing import Optional
+
+import huggingface_hub.utils as hf_hub_utils
+from tqdm import auto as tqdm_lib
+
+
+_lock = threading.Lock()
+_default_handler: Optional[logging.Handler] = None
+
+log_levels = {
+ "detail": logging.DEBUG, # will also print filename and line number
+ "debug": logging.DEBUG,
+ "info": logging.INFO,
+ "warning": logging.WARNING,
+ "error": logging.ERROR,
+ "critical": logging.CRITICAL,
+}
+
+_default_log_level = logging.WARNING
+
+_tqdm_active = not hf_hub_utils.are_progress_bars_disabled()
+
+
+def _get_default_logging_level():
+ """
+ If TRANSFORMERS_VERBOSITY env var is set to one of the valid choices return that as the new default level. If it is
+ not - fall back to `_default_log_level`
+ """
+ env_level_str = os.getenv("TRANSFORMERS_VERBOSITY", None)
+ if env_level_str:
+ if env_level_str in log_levels:
+ return log_levels[env_level_str]
+ else:
+ logging.getLogger().warning(
+ f"Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, "
+ f"has to be one of: { ', '.join(log_levels.keys()) }"
+ )
+ return _default_log_level
+
+
+def _get_library_name() -> str:
+ return __name__.split(".")[0]
+
+
+def _get_library_root_logger() -> logging.Logger:
+ return logging.getLogger(_get_library_name())
+
+
+def _configure_library_root_logger() -> None:
+ global _default_handler
+
+ with _lock:
+ if _default_handler:
+ # This library has already configured the library root logger.
+ return
+ _default_handler = logging.StreamHandler() # Set sys.stderr as stream.
+ # set defaults based on https://github.com/pyinstaller/pyinstaller/issues/7334#issuecomment-1357447176
+ if sys.stderr is None:
+ sys.stderr = open(os.devnull, "w")
+
+ _default_handler.flush = sys.stderr.flush
+
+ # Apply our default configuration to the library root logger.
+ library_root_logger = _get_library_root_logger()
+ library_root_logger.addHandler(_default_handler)
+ library_root_logger.setLevel(_get_default_logging_level())
+ # if logging level is debug, we add pathname and lineno to formatter for easy debugging
+ if os.getenv("TRANSFORMERS_VERBOSITY", None) == "detail":
+ formatter = logging.Formatter("[%(levelname)s|%(pathname)s:%(lineno)s] %(asctime)s >> %(message)s")
+ _default_handler.setFormatter(formatter)
+
+ is_ci = os.getenv("CI") is not None and os.getenv("CI").upper() in {"1", "ON", "YES", "TRUE"}
+ library_root_logger.propagate = True if is_ci else False
+
+
+def _reset_library_root_logger() -> None:
+ global _default_handler
+
+ with _lock:
+ if not _default_handler:
+ return
+
+ library_root_logger = _get_library_root_logger()
+ library_root_logger.removeHandler(_default_handler)
+ library_root_logger.setLevel(logging.NOTSET)
+ _default_handler = None
+
+
+def get_log_levels_dict():
+ return log_levels
+
+
+def captureWarnings(capture):
+ """
+ Calls the `captureWarnings` method from the logging library to enable management of the warnings emitted by the
+ `warnings` library.
+
+ Read more about this method here:
+ https://docs.python.org/3/library/logging.html#integration-with-the-warnings-module
+
+ All warnings will be logged through the `py.warnings` logger.
+
+ Careful: this method also adds a handler to this logger if it does not already have one, and updates the logging
+ level of that logger to the library's root logger.
+ """
+ logger = get_logger("py.warnings")
+
+ if not logger.handlers:
+ logger.addHandler(_default_handler)
+
+ logger.setLevel(_get_library_root_logger().level)
+
+ _captureWarnings(capture)
+
+
+def get_logger(name: Optional[str] = None) -> logging.Logger:
+ """
+ Return a logger with the specified name.
+
+ This function is not supposed to be directly accessed unless you are writing a custom transformers module.
+ """
+
+ if name is None:
+ name = _get_library_name()
+
+ _configure_library_root_logger()
+ return logging.getLogger(name)
+
+
+def get_verbosity() -> int:
+ """
+ Return the current level for the 🤗 Transformers's root logger as an int.
+
+ Returns:
+ `int`: The logging level.
+
+
+
+ 🤗 Transformers has following logging levels:
+
+ - 50: `transformers.logging.CRITICAL` or `transformers.logging.FATAL`
+ - 40: `transformers.logging.ERROR`
+ - 30: `transformers.logging.WARNING` or `transformers.logging.WARN`
+ - 20: `transformers.logging.INFO`
+ - 10: `transformers.logging.DEBUG`
+
+ """
+
+ _configure_library_root_logger()
+ return _get_library_root_logger().getEffectiveLevel()
+
+
+def set_verbosity(verbosity: int) -> None:
+ """
+ Set the verbosity level for the 🤗 Transformers's root logger.
+
+ Args:
+ verbosity (`int`):
+ Logging level, e.g., one of:
+
+ - `transformers.logging.CRITICAL` or `transformers.logging.FATAL`
+ - `transformers.logging.ERROR`
+ - `transformers.logging.WARNING` or `transformers.logging.WARN`
+ - `transformers.logging.INFO`
+ - `transformers.logging.DEBUG`
+ """
+
+ _configure_library_root_logger()
+ _get_library_root_logger().setLevel(verbosity)
+
+
+def set_verbosity_info():
+ """Set the verbosity to the `INFO` level."""
+ return set_verbosity(INFO)
+
+
+def set_verbosity_warning():
+ """Set the verbosity to the `WARNING` level."""
+ return set_verbosity(WARNING)
+
+
+def set_verbosity_debug():
+ """Set the verbosity to the `DEBUG` level."""
+ return set_verbosity(DEBUG)
+
+
+def set_verbosity_error():
+ """Set the verbosity to the `ERROR` level."""
+ return set_verbosity(ERROR)
+
+
+def disable_default_handler() -> None:
+ """Disable the default handler of the HuggingFace Transformers's root logger."""
+
+ _configure_library_root_logger()
+
+ assert _default_handler is not None
+ _get_library_root_logger().removeHandler(_default_handler)
+
+
+def enable_default_handler() -> None:
+ """Enable the default handler of the HuggingFace Transformers's root logger."""
+
+ _configure_library_root_logger()
+
+ assert _default_handler is not None
+ _get_library_root_logger().addHandler(_default_handler)
+
+
+def add_handler(handler: logging.Handler) -> None:
+ """adds a handler to the HuggingFace Transformers's root logger."""
+
+ _configure_library_root_logger()
+
+ assert handler is not None
+ _get_library_root_logger().addHandler(handler)
+
+
+def remove_handler(handler: logging.Handler) -> None:
+ """removes given handler from the HuggingFace Transformers's root logger."""
+
+ _configure_library_root_logger()
+
+ assert handler is not None and handler not in _get_library_root_logger().handlers
+ _get_library_root_logger().removeHandler(handler)
+
+
+def disable_propagation() -> None:
+ """
+ Disable propagation of the library log outputs. Note that log propagation is disabled by default.
+ """
+
+ _configure_library_root_logger()
+ _get_library_root_logger().propagate = False
+
+
+def enable_propagation() -> None:
+ """
+ Enable propagation of the library log outputs. Please disable the HuggingFace Transformers's default handler to
+ prevent double logging if the root logger has been configured.
+ """
+
+ _configure_library_root_logger()
+ _get_library_root_logger().propagate = True
+
+
+def enable_explicit_format() -> None:
+ """
+ Enable explicit formatting for every HuggingFace Transformers's logger. The explicit formatter is as follows:
+ ```
+ [LEVELNAME|FILENAME|LINE NUMBER] TIME >> MESSAGE
+ ```
+ All handlers currently bound to the root logger are affected by this method.
+ """
+ handlers = _get_library_root_logger().handlers
+
+ for handler in handlers:
+ formatter = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s")
+ handler.setFormatter(formatter)
+
+
+def reset_format() -> None:
+ """
+ Resets the formatting for HuggingFace Transformers's loggers.
+
+ All handlers currently bound to the root logger are affected by this method.
+ """
+ handlers = _get_library_root_logger().handlers
+
+ for handler in handlers:
+ handler.setFormatter(None)
+
+
+def warning_advice(self, *args, **kwargs):
+ """
+ This method is identical to `logger.warning()`, but if env var TRANSFORMERS_NO_ADVISORY_WARNINGS=1 is set, this
+ warning will not be printed
+ """
+ no_advisory_warnings = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS", False)
+ if no_advisory_warnings:
+ return
+ self.warning(*args, **kwargs)
+
+
+logging.Logger.warning_advice = warning_advice
+
+
+@functools.lru_cache(None)
+def warning_once(self, *args, **kwargs):
+ """
+ This method is identical to `logger.warning()`, but will emit the warning with the same message only once
+
+ Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the cache.
+ The assumption here is that all warning messages are unique across the code. If they aren't then need to switch to
+ another type of cache that includes the caller frame information in the hashing function.
+ """
+ self.warning(*args, **kwargs)
+
+
+logging.Logger.warning_once = warning_once
+
+
+@functools.lru_cache(None)
+def info_once(self, *args, **kwargs):
+ """
+ This method is identical to `logger.info()`, but will emit the info with the same message only once
+
+ Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the cache.
+ The assumption here is that all warning messages are unique across the code. If they aren't then need to switch to
+ another type of cache that includes the caller frame information in the hashing function.
+ """
+ self.info(*args, **kwargs)
+
+
+logging.Logger.info_once = info_once
+
+
+class EmptyTqdm:
+ """Dummy tqdm which doesn't do anything."""
+
+ def __init__(self, *args, **kwargs): # pylint: disable=unused-argument
+ self._iterator = args[0] if args else None
+
+ def __iter__(self):
+ return iter(self._iterator)
+
+ def __getattr__(self, _):
+ """Return empty function."""
+
+ def empty_fn(*args, **kwargs): # pylint: disable=unused-argument
+ return
+
+ return empty_fn
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, type_, value, traceback):
+ return
+
+
+class _tqdm_cls:
+ def __call__(self, *args, **kwargs):
+ if _tqdm_active:
+ return tqdm_lib.tqdm(*args, **kwargs)
+ else:
+ return EmptyTqdm(*args, **kwargs)
+
+ def set_lock(self, *args, **kwargs):
+ self._lock = None
+ if _tqdm_active:
+ return tqdm_lib.tqdm.set_lock(*args, **kwargs)
+
+ def get_lock(self):
+ if _tqdm_active:
+ return tqdm_lib.tqdm.get_lock()
+
+
+tqdm = _tqdm_cls()
+
+
+def is_progress_bar_enabled() -> bool:
+ """Return a boolean indicating whether tqdm progress bars are enabled."""
+ global _tqdm_active
+ return bool(_tqdm_active)
+
+
+def enable_progress_bar():
+ """Enable tqdm progress bar."""
+ global _tqdm_active
+ _tqdm_active = True
+ hf_hub_utils.enable_progress_bars()
+
+
+def disable_progress_bar():
+ """Disable tqdm progress bar."""
+ global _tqdm_active
+ _tqdm_active = False
+ hf_hub_utils.disable_progress_bars()
diff --git a/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/model_parallel_utils.py b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/model_parallel_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ec79a5e23cbc976e2cb26934abe94e7bbe890d7
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/model_parallel_utils.py
@@ -0,0 +1,56 @@
+# coding=utf-8
+# 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 math import ceil
+
+
+def assert_device_map(device_map, num_blocks):
+ blocks = list(range(0, num_blocks))
+
+ device_map_blocks = [item for sublist in list(device_map.values()) for item in sublist]
+
+ # Duplicate check
+ duplicate_blocks = []
+ for i in device_map_blocks:
+ if device_map_blocks.count(i) > 1 and i not in duplicate_blocks:
+ duplicate_blocks.append(i)
+ # Missing blocks
+ missing_blocks = [i for i in blocks if i not in device_map_blocks]
+ extra_blocks = [i for i in device_map_blocks if i not in blocks]
+
+ if len(duplicate_blocks) != 0:
+ raise ValueError(
+ "Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device."
+ " These attention blocks were specified more than once: " + str(duplicate_blocks)
+ )
+ if len(missing_blocks) != 0:
+ raise ValueError(
+ "There are attention blocks for this model that are not specified in the device_map. Add these attention "
+ "blocks to a device on the device_map: " + str(missing_blocks)
+ )
+ if len(extra_blocks) != 0:
+ raise ValueError(
+ "The device_map contains more attention blocks than this model has. Remove these from the device_map:"
+ + str(extra_blocks)
+ )
+
+
+def get_device_map(n_layers, devices):
+ """Returns a dictionary of layers distributed evenly across all devices."""
+ layers = list(range(n_layers))
+ n_blocks = int(ceil(n_layers / len(devices)))
+ layers_list = [layers[i : i + n_blocks] for i in range(0, n_layers, n_blocks)]
+
+ return dict(zip(devices, layers_list))
diff --git a/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/notebook.py b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/notebook.py
new file mode 100644
index 0000000000000000000000000000000000000000..eff8a28459e7edeb47844d7dac240e723b6031eb
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/notebook.py
@@ -0,0 +1,384 @@
+# coding=utf-8
+# Copyright 2020 Hugging Face
+#
+# 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 re
+import time
+from typing import Optional
+
+import IPython.display as disp
+
+from ..trainer_callback import TrainerCallback
+from ..trainer_utils import IntervalStrategy, has_length
+
+
+def format_time(t):
+ "Format `t` (in seconds) to (h):mm:ss"
+ t = int(t)
+ h, m, s = t // 3600, (t // 60) % 60, t % 60
+ return f"{h}:{m:02d}:{s:02d}" if h != 0 else f"{m:02d}:{s:02d}"
+
+
+def html_progress_bar(value, total, prefix, label, width=300):
+ # docstyle-ignore
+ return f"""
+
+ """
+
+
+def text_to_html_table(items):
+ "Put the texts in `items` in an HTML table."
+ html_code = """\n"""
+ html_code += """ \n \n"""
+ for i in items[0]:
+ html_code += f" | {i} | \n"
+ html_code += "
\n \n \n"
+ for line in items[1:]:
+ html_code += " \n"
+ for elt in line:
+ elt = f"{elt:.6f}" if isinstance(elt, float) else str(elt)
+ html_code += f" | {elt} | \n"
+ html_code += "
\n"
+ html_code += " \n
"
+ return html_code
+
+
+class NotebookProgressBar:
+ """
+ A progress par for display in a notebook.
+
+ Class attributes (overridden by derived classes)
+
+ - **warmup** (`int`) -- The number of iterations to do at the beginning while ignoring `update_every`.
+ - **update_every** (`float`) -- Since calling the time takes some time, we only do it every presumed
+ `update_every` seconds. The progress bar uses the average time passed up until now to guess the next value
+ for which it will call the update.
+
+ Args:
+ total (`int`):
+ The total number of iterations to reach.
+ prefix (`str`, *optional*):
+ A prefix to add before the progress bar.
+ leave (`bool`, *optional*, defaults to `True`):
+ Whether or not to leave the progress bar once it's completed. You can always call the
+ [`~utils.notebook.NotebookProgressBar.close`] method to make the bar disappear.
+ parent ([`~notebook.NotebookTrainingTracker`], *optional*):
+ A parent object (like [`~utils.notebook.NotebookTrainingTracker`]) that spawns progress bars and handle
+ their display. If set, the object passed must have a `display()` method.
+ width (`int`, *optional*, defaults to 300):
+ The width (in pixels) that the bar will take.
+
+ Example:
+
+ ```python
+ import time
+
+ pbar = NotebookProgressBar(100)
+ for val in range(100):
+ pbar.update(val)
+ time.sleep(0.07)
+ pbar.update(100)
+ ```"""
+
+ warmup = 5
+ update_every = 0.2
+
+ def __init__(
+ self,
+ total: int,
+ prefix: Optional[str] = None,
+ leave: bool = True,
+ parent: Optional["NotebookTrainingTracker"] = None,
+ width: int = 300,
+ ):
+ self.total = total
+ self.prefix = "" if prefix is None else prefix
+ self.leave = leave
+ self.parent = parent
+ self.width = width
+ self.last_value = None
+ self.comment = None
+ self.output = None
+ self.value = None
+ self.label = None
+ if "VSCODE_PID" in os.environ:
+ self.update_every = 0.5 # Adjusted for smooth updated as html rending is slow on VS Code
+ # This is the only adjustment required to optimize training html rending
+
+ def update(self, value: int, force_update: bool = False, comment: str = None):
+ """
+ The main method to update the progress bar to `value`.
+
+ Args:
+ value (`int`):
+ The value to use. Must be between 0 and `total`.
+ force_update (`bool`, *optional*, defaults to `False`):
+ Whether or not to force and update of the internal state and display (by default, the bar will wait for
+ `value` to reach the value it predicted corresponds to a time of more than the `update_every` attribute
+ since the last update to avoid adding boilerplate).
+ comment (`str`, *optional*):
+ A comment to add on the left of the progress bar.
+ """
+ self.value = value
+ if comment is not None:
+ self.comment = comment
+ if self.last_value is None:
+ self.start_time = self.last_time = time.time()
+ self.start_value = self.last_value = value
+ self.elapsed_time = self.predicted_remaining = None
+ self.first_calls = self.warmup
+ self.wait_for = 1
+ self.update_bar(value)
+ elif value <= self.last_value and not force_update:
+ return
+ elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for, self.total):
+ if self.first_calls > 0:
+ self.first_calls -= 1
+ current_time = time.time()
+ self.elapsed_time = current_time - self.start_time
+ # We could have value = self.start_value if the update is called twixe with the same start value.
+ if value > self.start_value:
+ self.average_time_per_item = self.elapsed_time / (value - self.start_value)
+ else:
+ self.average_time_per_item = None
+ if value >= self.total:
+ value = self.total
+ self.predicted_remaining = None
+ if not self.leave:
+ self.close()
+ elif self.average_time_per_item is not None:
+ self.predicted_remaining = self.average_time_per_item * (self.total - value)
+ self.update_bar(value)
+ self.last_value = value
+ self.last_time = current_time
+ if (self.average_time_per_item is None) or (self.average_time_per_item == 0):
+ self.wait_for = 1
+ else:
+ self.wait_for = max(int(self.update_every / self.average_time_per_item), 1)
+
+ def update_bar(self, value, comment=None):
+ spaced_value = " " * (len(str(self.total)) - len(str(value))) + str(value)
+ if self.elapsed_time is None:
+ self.label = f"[{spaced_value}/{self.total} : < :"
+ elif self.predicted_remaining is None:
+ self.label = f"[{spaced_value}/{self.total} {format_time(self.elapsed_time)}"
+ else:
+ self.label = (
+ f"[{spaced_value}/{self.total} {format_time(self.elapsed_time)} <"
+ f" {format_time(self.predicted_remaining)}"
+ )
+ if self.average_time_per_item == 0:
+ self.label += ", +inf it/s"
+ else:
+ self.label += f", {1/self.average_time_per_item:.2f} it/s"
+
+ self.label += "]" if self.comment is None or len(self.comment) == 0 else f", {self.comment}]"
+ self.display()
+
+ def display(self):
+ self.html_code = html_progress_bar(self.value, self.total, self.prefix, self.label, self.width)
+ if self.parent is not None:
+ # If this is a child bar, the parent will take care of the display.
+ self.parent.display()
+ return
+ if self.output is None:
+ self.output = disp.display(disp.HTML(self.html_code), display_id=True)
+ else:
+ self.output.update(disp.HTML(self.html_code))
+
+ def close(self):
+ "Closes the progress bar."
+ if self.parent is None and self.output is not None:
+ self.output.update(disp.HTML(""))
+
+
+class NotebookTrainingTracker(NotebookProgressBar):
+ """
+ An object tracking the updates of an ongoing training with progress bars and a nice table reporting metrics.
+
+ Args:
+ num_steps (`int`): The number of steps during training. column_names (`List[str]`, *optional*):
+ The list of column names for the metrics table (will be inferred from the first call to
+ [`~utils.notebook.NotebookTrainingTracker.write_line`] if not set).
+ """
+
+ def __init__(self, num_steps, column_names=None):
+ super().__init__(num_steps)
+ self.inner_table = None if column_names is None else [column_names]
+ self.child_bar = None
+
+ def display(self):
+ self.html_code = html_progress_bar(self.value, self.total, self.prefix, self.label, self.width)
+ if self.inner_table is not None:
+ self.html_code += text_to_html_table(self.inner_table)
+ if self.child_bar is not None:
+ self.html_code += self.child_bar.html_code
+ if self.output is None:
+ self.output = disp.display(disp.HTML(self.html_code), display_id=True)
+ else:
+ self.output.update(disp.HTML(self.html_code))
+
+ def write_line(self, values):
+ """
+ Write the values in the inner table.
+
+ Args:
+ values (`Dict[str, float]`): The values to display.
+ """
+ if self.inner_table is None:
+ self.inner_table = [list(values.keys()), list(values.values())]
+ else:
+ columns = self.inner_table[0]
+ for key in values.keys():
+ if key not in columns:
+ columns.append(key)
+ self.inner_table[0] = columns
+ if len(self.inner_table) > 1:
+ last_values = self.inner_table[-1]
+ first_column = self.inner_table[0][0]
+ if last_values[0] != values[first_column]:
+ # write new line
+ self.inner_table.append([values[c] if c in values else "No Log" for c in columns])
+ else:
+ # update last line
+ new_values = values
+ for c in columns:
+ if c not in new_values.keys():
+ new_values[c] = last_values[columns.index(c)]
+ self.inner_table[-1] = [new_values[c] for c in columns]
+ else:
+ self.inner_table.append([values[c] for c in columns])
+
+ def add_child(self, total, prefix=None, width=300):
+ """
+ Add a child progress bar displayed under the table of metrics. The child progress bar is returned (so it can be
+ easily updated).
+
+ Args:
+ total (`int`): The number of iterations for the child progress bar.
+ prefix (`str`, *optional*): A prefix to write on the left of the progress bar.
+ width (`int`, *optional*, defaults to 300): The width (in pixels) of the progress bar.
+ """
+ self.child_bar = NotebookProgressBar(total, prefix=prefix, parent=self, width=width)
+ return self.child_bar
+
+ def remove_child(self):
+ """
+ Closes the child progress bar.
+ """
+ self.child_bar = None
+ self.display()
+
+
+class NotebookProgressCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that displays the progress of training or evaluation, optimized for Jupyter Notebooks or
+ Google colab.
+ """
+
+ def __init__(self):
+ self.training_tracker = None
+ self.prediction_bar = None
+ self._force_next_update = False
+
+ def on_train_begin(self, args, state, control, **kwargs):
+ self.first_column = "Epoch" if args.eval_strategy == IntervalStrategy.EPOCH else "Step"
+ self.training_loss = 0
+ self.last_log = 0
+ column_names = [self.first_column] + ["Training Loss"]
+ if args.eval_strategy != IntervalStrategy.NO:
+ column_names.append("Validation Loss")
+ self.training_tracker = NotebookTrainingTracker(state.max_steps, column_names)
+
+ def on_step_end(self, args, state, control, **kwargs):
+ epoch = int(state.epoch) if int(state.epoch) == state.epoch else f"{state.epoch:.2f}"
+ self.training_tracker.update(
+ state.global_step + 1,
+ comment=f"Epoch {epoch}/{state.num_train_epochs}",
+ force_update=self._force_next_update,
+ )
+ self._force_next_update = False
+
+ def on_prediction_step(self, args, state, control, eval_dataloader=None, **kwargs):
+ if not has_length(eval_dataloader):
+ return
+ if self.prediction_bar is None:
+ if self.training_tracker is not None:
+ self.prediction_bar = self.training_tracker.add_child(len(eval_dataloader))
+ else:
+ self.prediction_bar = NotebookProgressBar(len(eval_dataloader))
+ self.prediction_bar.update(1)
+ else:
+ self.prediction_bar.update(self.prediction_bar.value + 1)
+
+ def on_predict(self, args, state, control, **kwargs):
+ if self.prediction_bar is not None:
+ self.prediction_bar.close()
+ self.prediction_bar = None
+
+ def on_log(self, args, state, control, logs=None, **kwargs):
+ # Only for when there is no evaluation
+ if args.eval_strategy == IntervalStrategy.NO and "loss" in logs:
+ values = {"Training Loss": logs["loss"]}
+ # First column is necessarily Step sine we're not in epoch eval strategy
+ values["Step"] = state.global_step
+ self.training_tracker.write_line(values)
+
+ def on_evaluate(self, args, state, control, metrics=None, **kwargs):
+ if self.training_tracker is not None:
+ values = {"Training Loss": "No log", "Validation Loss": "No log"}
+ for log in reversed(state.log_history):
+ if "loss" in log:
+ values["Training Loss"] = log["loss"]
+ break
+
+ if self.first_column == "Epoch":
+ values["Epoch"] = int(state.epoch)
+ else:
+ values["Step"] = state.global_step
+ metric_key_prefix = "eval"
+ for k in metrics:
+ if k.endswith("_loss"):
+ metric_key_prefix = re.sub(r"\_loss$", "", k)
+ _ = metrics.pop("total_flos", None)
+ _ = metrics.pop("epoch", None)
+ _ = metrics.pop(f"{metric_key_prefix}_runtime", None)
+ _ = metrics.pop(f"{metric_key_prefix}_samples_per_second", None)
+ _ = metrics.pop(f"{metric_key_prefix}_steps_per_second", None)
+ _ = metrics.pop(f"{metric_key_prefix}_jit_compilation_time", None)
+ for k, v in metrics.items():
+ splits = k.split("_")
+ name = " ".join([part.capitalize() for part in splits[1:]])
+ if name == "Loss":
+ # Single dataset
+ name = "Validation Loss"
+ values[name] = v
+ self.training_tracker.write_line(values)
+ self.training_tracker.remove_child()
+ self.prediction_bar = None
+ # Evaluation takes a long time so we should force the next update.
+ self._force_next_update = True
+
+ def on_train_end(self, args, state, control, **kwargs):
+ self.training_tracker.update(
+ state.global_step,
+ comment=f"Epoch {int(state.epoch)}/{state.num_train_epochs}",
+ force_update=True,
+ )
+ self.training_tracker = None
diff --git a/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/peft_utils.py b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/peft_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..7efa80e92347e2351ec75486ecea5c9f9fde6371
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/peft_utils.py
@@ -0,0 +1,125 @@
+# Copyright 2023 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 importlib
+import os
+from typing import Dict, Optional, Union
+
+from packaging import version
+
+from .hub import cached_file
+from .import_utils import is_peft_available
+
+
+ADAPTER_CONFIG_NAME = "adapter_config.json"
+ADAPTER_WEIGHTS_NAME = "adapter_model.bin"
+ADAPTER_SAFE_WEIGHTS_NAME = "adapter_model.safetensors"
+
+
+def find_adapter_config_file(
+ model_id: str,
+ 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,
+ subfolder: str = "",
+ _commit_hash: Optional[str] = None,
+) -> Optional[str]:
+ r"""
+ Simply checks if the model stored on the Hub or locally is an adapter model or not, return the path of the adapter
+ config file if it is, None otherwise.
+
+ Args:
+ model_id (`str`):
+ The identifier of the model to look for, can be either a local path or an id to the repository on the Hub.
+ 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.
+
+
+
+ To test a pull request you made on the Hub, you can pass `revision="refs/pr/".
+
+
+
+ local_files_only (`bool`, *optional*, defaults to `False`):
+ If `True`, will only try to load the tokenizer configuration from local files.
+ subfolder (`str`, *optional*, defaults to `""`):
+ In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
+ specify the folder name here.
+ """
+ adapter_cached_filename = None
+ if model_id is None:
+ return None
+ elif os.path.isdir(model_id):
+ list_remote_files = os.listdir(model_id)
+ if ADAPTER_CONFIG_NAME in list_remote_files:
+ adapter_cached_filename = os.path.join(model_id, ADAPTER_CONFIG_NAME)
+ else:
+ adapter_cached_filename = cached_file(
+ model_id,
+ ADAPTER_CONFIG_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,
+ subfolder=subfolder,
+ _commit_hash=_commit_hash,
+ _raise_exceptions_for_gated_repo=False,
+ _raise_exceptions_for_missing_entries=False,
+ _raise_exceptions_for_connection_errors=False,
+ )
+
+ return adapter_cached_filename
+
+
+def check_peft_version(min_version: str) -> None:
+ r"""
+ Checks if the version of PEFT is compatible.
+
+ Args:
+ version (`str`):
+ The version of PEFT to check against.
+ """
+ if not is_peft_available():
+ raise ValueError("PEFT is not installed. Please install it with `pip install peft`")
+
+ is_peft_version_compatible = version.parse(importlib.metadata.version("peft")) >= version.parse(min_version)
+
+ if not is_peft_version_compatible:
+ raise ValueError(
+ f"The version of PEFT you are using is not compatible, please use a version that is greater"
+ f" than {min_version}"
+ )
diff --git a/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/quantization_config.py b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/quantization_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..0988d8ac1474714bc03ad3e127bdb13e90c92e53
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/quantization_config.py
@@ -0,0 +1,1714 @@
+#!/usr/bin/env python
+# coding=utf-8
+
+# Copyright 2023 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 copy
+import dataclasses
+import importlib.metadata
+import json
+import os
+from dataclasses import dataclass
+from enum import Enum
+from inspect import Parameter, signature
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+from packaging import version
+
+from ..utils import (
+ is_auto_awq_available,
+ is_compressed_tensors_available,
+ is_gptqmodel_available,
+ is_hqq_available,
+ is_torch_available,
+ is_torchao_available,
+ logging,
+)
+from .import_utils import is_auto_gptq_available
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+class QuantizationMethod(str, Enum):
+ BITS_AND_BYTES = "bitsandbytes"
+ GPTQ = "gptq"
+ AWQ = "awq"
+ AQLM = "aqlm"
+ VPTQ = "vptq"
+ QUANTO = "quanto"
+ EETQ = "eetq"
+ HIGGS = "higgs"
+ HQQ = "hqq"
+ COMPRESSED_TENSORS = "compressed-tensors"
+ FBGEMM_FP8 = "fbgemm_fp8"
+ TORCHAO = "torchao"
+ BITNET = "bitnet"
+ SPQR = "spqr"
+ FP8 = "fp8"
+
+
+class AWQLinearVersion(str, Enum):
+ GEMM = "gemm"
+ GEMV = "gemv"
+ EXLLAMA = "exllama"
+ IPEX = "ipex"
+
+ @staticmethod
+ def from_str(version: str):
+ version = version.lower()
+ if version == "gemm":
+ return AWQLinearVersion.GEMM
+ elif version == "gemv":
+ return AWQLinearVersion.GEMV
+ elif version == "exllama":
+ return AWQLinearVersion.EXLLAMA
+ elif version == "ipex":
+ return AWQLinearVersion.IPEX
+ else:
+ raise ValueError(f"Unknown AWQLinearVersion {version}")
+
+
+class AwqBackendPackingMethod(str, Enum):
+ AUTOAWQ = "autoawq"
+ LLMAWQ = "llm-awq"
+
+
+@dataclass
+class QuantizationConfigMixin:
+ """
+ Mixin class for quantization config
+ """
+
+ quant_method: QuantizationMethod
+
+ @classmethod
+ def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs):
+ """
+ Instantiates a [`QuantizationConfigMixin`] from a Python dictionary of parameters.
+
+ Args:
+ config_dict (`Dict[str, Any]`):
+ Dictionary that will be used to instantiate the configuration object.
+ return_unused_kwargs (`bool`,*optional*, defaults to `False`):
+ Whether or not to return a list of unused keyword arguments. Used for `from_pretrained` method in
+ `PreTrainedModel`.
+ kwargs (`Dict[str, Any]`):
+ Additional parameters from which to initialize the configuration object.
+
+ Returns:
+ [`QuantizationConfigMixin`]: The configuration object instantiated from those parameters.
+ """
+ config = cls(**config_dict)
+
+ to_remove = []
+ for key, value in kwargs.items():
+ if hasattr(config, key):
+ setattr(config, key, value)
+ to_remove.append(key)
+ for key in to_remove:
+ kwargs.pop(key, None)
+
+ if return_unused_kwargs:
+ return config, kwargs
+ else:
+ return config
+
+ def to_json_file(self, json_file_path: Union[str, os.PathLike]):
+ """
+ Save this instance to a JSON file.
+
+ Args:
+ json_file_path (`str` or `os.PathLike`):
+ Path to the JSON file in which this configuration instance's parameters will be saved.
+ use_diff (`bool`, *optional*, defaults to `True`):
+ If set to `True`, only the difference between the config instance and the default
+ `QuantizationConfig()` is serialized to JSON file.
+ """
+ with open(json_file_path, "w", encoding="utf-8") as writer:
+ config_dict = self.to_dict()
+ json_string = json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
+
+ writer.write(json_string)
+
+ def to_dict(self) -> Dict[str, Any]:
+ """
+ Serializes this instance to a Python dictionary. Returns:
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
+ """
+ return copy.deepcopy(self.__dict__)
+
+ def __iter__(self):
+ """allows `dict(obj)` for situations where obj may be a dict or QuantizationConfigMixin"""
+ for attr, value in copy.deepcopy(self.__dict__).items():
+ yield attr, value
+
+ def __repr__(self):
+ return f"{self.__class__.__name__} {self.to_json_string()}"
+
+ def to_json_string(self, use_diff: bool = True) -> str:
+ """
+ Serializes this instance to a JSON string.
+
+ Args:
+ use_diff (`bool`, *optional*, defaults to `True`):
+ If set to `True`, only the difference between the config instance and the default `PretrainedConfig()`
+ is serialized to JSON string.
+
+ Returns:
+ `str`: String containing all the attributes that make up this configuration instance in JSON format.
+ """
+ if use_diff is True:
+ config_dict = self.to_diff_dict()
+ else:
+ config_dict = self.to_dict()
+ return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
+
+ def update(self, **kwargs):
+ """
+ Updates attributes of this class instance with attributes from `kwargs` if they match existing attributes,
+ returning all the unused kwargs.
+
+ Args:
+ kwargs (`Dict[str, Any]`):
+ Dictionary of attributes to tentatively update this class.
+
+ Returns:
+ `Dict[str, Any]`: Dictionary containing all the key-value pairs that were not used to update the instance.
+ """
+ to_remove = []
+ for key, value in kwargs.items():
+ if hasattr(self, key):
+ setattr(self, key, value)
+ to_remove.append(key)
+
+ # Remove all the attributes that were updated, without modifying the input dict
+ unused_kwargs = {key: value for key, value in kwargs.items() if key not in to_remove}
+ return unused_kwargs
+
+
+@dataclass
+class HqqConfig(QuantizationConfigMixin):
+ """
+ This is wrapper around hqq's BaseQuantizeConfig.
+
+ Args:
+ nbits (`int`, *optional*, defaults to 4):
+ Number of bits. Supported values are (8, 4, 3, 2, 1).
+ group_size (`int`, *optional*, defaults to 64):
+ Group-size value. Supported values are any value that is divisble by weight.shape[axis]).
+ view_as_float (`bool`, *optional*, defaults to `False`):
+ View the quantized weight as float (used in distributed training) if set to `True`.
+ axis (`Optional[int]`, *optional*):
+ Axis along which grouping is performed. Supported values are 0 or 1.
+ dynamic_config (dict, *optional*):
+ Parameters for dynamic configuration. The key is the name tag of the layer and the value is a quantization config.
+ If set, each layer specified by its id will use its dedicated quantization configuration.
+ skip_modules (`List[str]`, *optional*, defaults to `['lm_head']`):
+ List of `nn.Linear` layers to skip.
+ kwargs (`Dict[str, Any]`, *optional*):
+ Additional parameters from which to initialize the configuration object.
+ """
+
+ def __init__(
+ self,
+ nbits: int = 4,
+ group_size: int = 64,
+ view_as_float: bool = False,
+ axis: Optional[int] = None,
+ dynamic_config: Optional[dict] = None,
+ skip_modules: List[str] = ["lm_head"],
+ **kwargs,
+ ):
+ if is_hqq_available():
+ from hqq.core.quantize import BaseQuantizeConfig as HQQBaseQuantizeConfig
+ else:
+ raise ImportError(
+ "A valid HQQ version (>=0.2.1) is not available. Please follow the instructions to install it: `https://github.com/mobiusml/hqq/`."
+ )
+
+ for deprecated_key in ["quant_zero", "quant_scale", "offload_meta"]:
+ if deprecated_key in kwargs:
+ logger.info(
+ deprecated_key + " is deprecated. This parameter will be ignored in quantization settings."
+ )
+
+ if axis is None:
+ axis = 1
+ logger.info("Setting axis=1 as faster backends such as TorchAO or BitBlas are only compatible with it.")
+
+ if axis not in [0, 1]:
+ raise ValueError("Invalid axis value. Only 0 and 1 are allowed.")
+
+ if dynamic_config is not None:
+ self.quant_config = {}
+ for key in dynamic_config:
+ self.quant_config[key] = HQQBaseQuantizeConfig(**dynamic_config[key])
+ else:
+ self.quant_config = HQQBaseQuantizeConfig(
+ **{
+ "nbits": nbits,
+ "group_size": group_size,
+ "view_as_float": view_as_float,
+ "axis": axis,
+ }
+ )
+
+ self.quant_method = QuantizationMethod.HQQ
+ self.skip_modules = skip_modules
+
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
+ """
+ pass
+
+ @classmethod
+ def from_dict(cls, config: Dict[str, Any]):
+ """
+ Override from_dict, used in AutoQuantizationConfig.from_dict in quantizers/auto.py
+ """
+ instance = cls()
+ instance.quant_config = config["quant_config"]
+ instance.skip_modules = config["skip_modules"]
+ return instance
+
+ def to_dict(self) -> Dict[str, Any]:
+ """
+ Serializes this instance to a Python dictionary. Returns:
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
+ """
+ return {
+ "quant_config": self.quant_config,
+ "quant_method": self.quant_method,
+ "skip_modules": self.skip_modules,
+ }
+
+ def __repr__(self):
+ config_dict = self.to_dict()
+ return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n"
+
+ def to_diff_dict(self) -> Dict[str, Any]:
+ """
+ Removes all attributes from config which correspond to the default config attributes for better readability and
+ serializes to a Python dictionary.
+ Returns:
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
+ """
+ config_dict = self.to_dict()
+
+ # get the default config dict
+ default_config_dict = HqqConfig().to_dict()
+
+ serializable_config_dict = {}
+
+ # only serialize values that differ from the default config
+ for key, value in config_dict.items():
+ if value != default_config_dict[key]:
+ serializable_config_dict[key] = value
+
+ return serializable_config_dict
+
+
+@dataclass
+class BitsAndBytesConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded using `bitsandbytes`.
+
+ This replaces `load_in_8bit` or `load_in_4bit`therefore both options are mutually exclusive.
+
+ Currently only supports `LLM.int8()`, `FP4`, and `NF4` quantization. If more methods are added to `bitsandbytes`,
+ then more arguments will be added to this class.
+
+ Args:
+ load_in_8bit (`bool`, *optional*, defaults to `False`):
+ This flag is used to enable 8-bit quantization with LLM.int8().
+ load_in_4bit (`bool`, *optional*, defaults to `False`):
+ This flag is used to enable 4-bit quantization by replacing the Linear layers with FP4/NF4 layers from
+ `bitsandbytes`.
+ llm_int8_threshold (`float`, *optional*, defaults to 6.0):
+ This corresponds to the outlier threshold for outlier detection as described in `LLM.int8() : 8-bit Matrix
+ Multiplication for Transformers at Scale` paper: https://arxiv.org/abs/2208.07339 Any hidden states value
+ that is above this threshold will be considered an outlier and the operation on those values will be done
+ in fp16. Values are usually normally distributed, that is, most values are in the range [-3.5, 3.5], but
+ there are some exceptional systematic outliers that are very differently distributed for large models.
+ These outliers are often in the interval [-60, -6] or [6, 60]. Int8 quantization works well for values of
+ magnitude ~5, but beyond that, there is a significant performance penalty. A good default threshold is 6,
+ but a lower threshold might be needed for more unstable models (small models, fine-tuning).
+ llm_int8_skip_modules (`List[str]`, *optional*):
+ An explicit list of the modules that we do not want to convert in 8-bit. This is useful for models such as
+ Jukebox that has several heads in different places and not necessarily at the last position. For example
+ for `CausalLM` models, the last `lm_head` is kept in its original `dtype`.
+ llm_int8_enable_fp32_cpu_offload (`bool`, *optional*, defaults to `False`):
+ This flag is used for advanced use cases and users that are aware of this feature. If you want to split
+ your model in different parts and run some parts in int8 on GPU and some parts in fp32 on CPU, you can use
+ this flag. This is useful for offloading large models such as `google/flan-t5-xxl`. Note that the int8
+ operations will not be run on CPU.
+ llm_int8_has_fp16_weight (`bool`, *optional*, defaults to `False`):
+ This flag runs LLM.int8() with 16-bit main weights. This is useful for fine-tuning as the weights do not
+ have to be converted back and forth for the backward pass.
+ bnb_4bit_compute_dtype (`torch.dtype` or str, *optional*, defaults to `torch.float32`):
+ This sets the computational type which might be different than the input type. For example, inputs might be
+ fp32, but computation can be set to bf16 for speedups.
+ bnb_4bit_quant_type (`str`, *optional*, defaults to `"fp4"`):
+ This sets the quantization data type in the bnb.nn.Linear4Bit layers. Options are FP4 and NF4 data types
+ which are specified by `fp4` or `nf4`.
+ bnb_4bit_use_double_quant (`bool`, *optional*, defaults to `False`):
+ This flag is used for nested quantization where the quantization constants from the first quantization are
+ quantized again.
+ bnb_4bit_quant_storage (`torch.dtype` or str, *optional*, defaults to `torch.uint8`):
+ This sets the storage type to pack the quanitzed 4-bit prarams.
+ kwargs (`Dict[str, Any]`, *optional*):
+ Additional parameters from which to initialize the configuration object.
+ """
+
+ def __init__(
+ self,
+ load_in_8bit=False,
+ load_in_4bit=False,
+ llm_int8_threshold=6.0,
+ llm_int8_skip_modules=None,
+ llm_int8_enable_fp32_cpu_offload=False,
+ llm_int8_has_fp16_weight=False,
+ bnb_4bit_compute_dtype=None,
+ bnb_4bit_quant_type="fp4",
+ bnb_4bit_use_double_quant=False,
+ bnb_4bit_quant_storage=None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.BITS_AND_BYTES
+
+ if load_in_4bit and load_in_8bit:
+ raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
+
+ self._load_in_8bit = load_in_8bit
+ self._load_in_4bit = load_in_4bit
+ self.llm_int8_threshold = llm_int8_threshold
+ self.llm_int8_skip_modules = llm_int8_skip_modules
+ self.llm_int8_enable_fp32_cpu_offload = llm_int8_enable_fp32_cpu_offload
+ self.llm_int8_has_fp16_weight = llm_int8_has_fp16_weight
+ self.bnb_4bit_quant_type = bnb_4bit_quant_type
+ self.bnb_4bit_use_double_quant = bnb_4bit_use_double_quant
+
+ if bnb_4bit_compute_dtype is None:
+ self.bnb_4bit_compute_dtype = torch.float32
+ elif isinstance(bnb_4bit_compute_dtype, str):
+ self.bnb_4bit_compute_dtype = getattr(torch, bnb_4bit_compute_dtype)
+ elif isinstance(bnb_4bit_compute_dtype, torch.dtype):
+ self.bnb_4bit_compute_dtype = bnb_4bit_compute_dtype
+ else:
+ raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype")
+
+ if bnb_4bit_quant_storage is None:
+ self.bnb_4bit_quant_storage = torch.uint8
+ elif isinstance(bnb_4bit_quant_storage, str):
+ if bnb_4bit_quant_storage not in ["float16", "float32", "int8", "uint8", "float64", "bfloat16"]:
+ raise ValueError(
+ "`bnb_4bit_quant_storage` must be a valid string (one of 'float16', 'float32', 'int8', 'uint8', 'float64', 'bfloat16') "
+ )
+ self.bnb_4bit_quant_storage = getattr(torch, bnb_4bit_quant_storage)
+ elif isinstance(bnb_4bit_quant_storage, torch.dtype):
+ self.bnb_4bit_quant_storage = bnb_4bit_quant_storage
+ else:
+ raise ValueError("bnb_4bit_quant_storage must be a string or a torch.dtype")
+
+ if kwargs:
+ logger.info(f"Unused kwargs: {list(kwargs.keys())}. These kwargs are not used in {self.__class__}.")
+
+ self.post_init()
+
+ @property
+ def load_in_4bit(self):
+ return self._load_in_4bit
+
+ @load_in_4bit.setter
+ def load_in_4bit(self, value: bool):
+ if not isinstance(value, bool):
+ raise TypeError("load_in_4bit must be a boolean")
+
+ if self.load_in_8bit and value:
+ raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
+ self._load_in_4bit = value
+
+ @property
+ def load_in_8bit(self):
+ return self._load_in_8bit
+
+ @load_in_8bit.setter
+ def load_in_8bit(self, value: bool):
+ if not isinstance(value, bool):
+ raise TypeError("load_in_8bit must be a boolean")
+
+ if self.load_in_4bit and value:
+ raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
+ self._load_in_8bit = value
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
+ """
+ if not isinstance(self.load_in_4bit, bool):
+ raise TypeError("load_in_4bit must be a boolean")
+
+ if not isinstance(self.load_in_8bit, bool):
+ raise TypeError("load_in_8bit must be a boolean")
+
+ if not isinstance(self.llm_int8_threshold, float):
+ raise TypeError("llm_int8_threshold must be a float")
+
+ if self.llm_int8_skip_modules is not None and not isinstance(self.llm_int8_skip_modules, list):
+ raise TypeError("llm_int8_skip_modules must be a list of strings")
+ if not isinstance(self.llm_int8_enable_fp32_cpu_offload, bool):
+ raise TypeError("llm_int8_enable_fp32_cpu_offload must be a boolean")
+
+ if not isinstance(self.llm_int8_has_fp16_weight, bool):
+ raise TypeError("llm_int8_has_fp16_weight must be a boolean")
+
+ if self.bnb_4bit_compute_dtype is not None and not isinstance(self.bnb_4bit_compute_dtype, torch.dtype):
+ raise TypeError("bnb_4bit_compute_dtype must be torch.dtype")
+
+ if not isinstance(self.bnb_4bit_quant_type, str):
+ raise TypeError("bnb_4bit_quant_type must be a string")
+
+ if not isinstance(self.bnb_4bit_use_double_quant, bool):
+ raise TypeError("bnb_4bit_use_double_quant must be a boolean")
+
+ if self.load_in_4bit and not version.parse(importlib.metadata.version("bitsandbytes")) >= version.parse(
+ "0.39.0"
+ ):
+ raise ValueError(
+ "4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version"
+ )
+
+ def is_quantizable(self):
+ r"""
+ Returns `True` if the model is quantizable, `False` otherwise.
+ """
+ return self.load_in_8bit or self.load_in_4bit
+
+ def quantization_method(self):
+ r"""
+ This method returns the quantization method used for the model. If the model is not quantizable, it returns
+ `None`.
+ """
+ if self.load_in_8bit:
+ return "llm_int8"
+ elif self.load_in_4bit and self.bnb_4bit_quant_type == "fp4":
+ return "fp4"
+ elif self.load_in_4bit and self.bnb_4bit_quant_type == "nf4":
+ return "nf4"
+ else:
+ return None
+
+ def to_dict(self) -> Dict[str, Any]:
+ """
+ Serializes this instance to a Python dictionary. Returns:
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
+ """
+ output = copy.deepcopy(self.__dict__)
+ output["bnb_4bit_compute_dtype"] = str(output["bnb_4bit_compute_dtype"]).split(".")[1]
+ output["bnb_4bit_quant_storage"] = str(output["bnb_4bit_quant_storage"]).split(".")[1]
+ output["load_in_4bit"] = self.load_in_4bit
+ output["load_in_8bit"] = self.load_in_8bit
+
+ return output
+
+ def __repr__(self):
+ config_dict = self.to_dict()
+ return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n"
+
+ def to_diff_dict(self) -> Dict[str, Any]:
+ """
+ Removes all attributes from config which correspond to the default config attributes for better readability and
+ serializes to a Python dictionary.
+
+ Returns:
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
+ """
+ config_dict = self.to_dict()
+
+ # get the default config dict
+ default_config_dict = BitsAndBytesConfig().to_dict()
+
+ serializable_config_dict = {}
+
+ # only serialize values that differ from the default config
+ for key, value in config_dict.items():
+ if value != default_config_dict[key]:
+ serializable_config_dict[key] = value
+
+ return serializable_config_dict
+
+
+class ExllamaVersion(int, Enum):
+ ONE = 1
+ TWO = 2
+
+
+@dataclass
+class GPTQConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded using `optimum` api for gptq quantization relying on auto_gptq backend.
+
+ Args:
+ bits (`int`):
+ The number of bits to quantize to, supported numbers are (2, 3, 4, 8).
+ tokenizer (`str` or `PreTrainedTokenizerBase`, *optional*):
+ The tokenizer used to process the dataset. You can pass either:
+ - A custom tokenizer object.
+ - A string, the *model id* of a predefined tokenizer hosted inside a model repo on huggingface.co.
+ - A path to a *directory* containing vocabulary files required by the tokenizer, for instance saved
+ using the [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
+ dataset (`Union[List[str]]`, *optional*):
+ The dataset used for quantization. You can provide your own dataset in a list of string or just use the
+ original datasets used in GPTQ paper ['wikitext2','c4','c4-new']
+ group_size (`int`, *optional*, defaults to 128):
+ The group size to use for quantization. Recommended value is 128 and -1 uses per-column quantization.
+ damp_percent (`float`, *optional*, defaults to 0.1):
+ The percent of the average Hessian diagonal to use for dampening. Recommended value is 0.1.
+ desc_act (`bool`, *optional*, defaults to `False`):
+ Whether to quantize columns in order of decreasing activation size. Setting it to False can significantly
+ speed up inference but the perplexity may become slightly worse. Also known as act-order.
+ sym (`bool`, *optional*, defaults to `True`):
+ Whether to use symetric quantization.
+ true_sequential (`bool`, *optional*, defaults to `True`):
+ Whether to perform sequential quantization even within a single Transformer block. Instead of quantizing
+ the entire block at once, we perform layer-wise quantization. As a result, each layer undergoes
+ quantization using inputs that have passed through the previously quantized layers.
+ checkpoint_format (`str`, *optional*, defaults to `"gptq"`):
+ GPTQ weight format. `gptq`(v1) is supported by both gptqmodel and auto-gptq. `gptq_v2` is gptqmodel only.
+ meta (`Dict[str, any]`, *optional*):
+ Properties, such as tooling:version, that do not directly contributes to quantization or quant inference are stored in meta.
+ i.e. `meta.quantizer`: ["optimum:_version_", "gptqmodel:_version_"]
+ backend (`str`, *optional*):
+ Controls which gptq kernel to be used. Valid values for gptqmodel are `auto`, `auto_trainable` and more. For auto-gptq, only
+ valid value is None and `auto_trainable`. Ref gptqmodel backends: https://github.com/ModelCloud/GPTQModel/blob/main/gptqmodel/utils/backend.py
+ use_cuda_fp16 (`bool`, *optional*, defaults to `False`):
+ Whether or not to use optimized cuda kernel for fp16 model. Need to have model in fp16. Auto-gptq only.
+ model_seqlen (`int`, *optional*):
+ The maximum sequence length that the model can take.
+ block_name_to_quantize (`str`, *optional*):
+ The transformers block name to quantize. If None, we will infer the block name using common patterns (e.g. model.layers)
+ module_name_preceding_first_block (`List[str]`, *optional*):
+ The layers that are preceding the first Transformer block.
+ batch_size (`int`, *optional*, defaults to 1):
+ The batch size used when processing the dataset
+ pad_token_id (`int`, *optional*):
+ The pad token id. Needed to prepare the dataset when `batch_size` > 1.
+ use_exllama (`bool`, *optional*):
+ Whether to use exllama backend. Defaults to `True` if unset. Only works with `bits` = 4.
+ max_input_length (`int`, *optional*):
+ The maximum input length. This is needed to initialize a buffer that depends on the maximum expected input
+ length. It is specific to the exllama backend with act-order.
+ exllama_config (`Dict[str, Any]`, *optional*):
+ The exllama config. You can specify the version of the exllama kernel through the `version` key. Defaults
+ to `{"version": 1}` if unset.
+ cache_block_outputs (`bool`, *optional*, defaults to `True`):
+ Whether to cache block outputs to reuse as inputs for the succeeding block.
+ modules_in_block_to_quantize (`List[List[str]]`, *optional*):
+ List of list of module names to quantize in the specified block. This argument is useful to exclude certain linear modules from being quantized.
+ The block to quantize can be specified by setting `block_name_to_quantize`. We will quantize each list sequentially. If not set, we will quantize all linear layers.
+ Example: `modules_in_block_to_quantize =[["self_attn.k_proj", "self_attn.v_proj", "self_attn.q_proj"], ["self_attn.o_proj"]]`.
+ In this example, we will first quantize the q,k,v layers simultaneously since they are independent.
+ Then, we will quantize `self_attn.o_proj` layer with the q,k,v layers quantized. This way, we will get
+ better results since it reflects the real input `self_attn.o_proj` will get when the model is quantized.
+ """
+
+ def __init__(
+ self,
+ bits: int,
+ tokenizer: Any = None,
+ dataset: Optional[Union[List[str], str]] = None,
+ group_size: int = 128,
+ damp_percent: float = 0.1,
+ desc_act: bool = False,
+ sym: bool = True,
+ true_sequential: bool = True,
+ checkpoint_format: str = "gptq",
+ meta: Optional[Dict[str, any]] = None,
+ backend: Optional[str] = None,
+ use_cuda_fp16: bool = False,
+ model_seqlen: Optional[int] = None,
+ block_name_to_quantize: Optional[str] = None,
+ module_name_preceding_first_block: Optional[List[str]] = None,
+ batch_size: int = 1,
+ pad_token_id: Optional[int] = None,
+ use_exllama: Optional[bool] = None,
+ max_input_length: Optional[int] = None,
+ exllama_config: Optional[Dict[str, Any]] = None,
+ cache_block_outputs: bool = True,
+ modules_in_block_to_quantize: Optional[List[List[str]]] = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.GPTQ
+ self.bits = bits
+ self.tokenizer = tokenizer
+ self.dataset = dataset
+ self.group_size = group_size
+ self.damp_percent = damp_percent
+ self.desc_act = desc_act
+ self.sym = sym
+ self.true_sequential = true_sequential
+ self.checkpoint_format = checkpoint_format.lower()
+ self.meta = meta
+ self.backend = backend.lower() if isinstance(backend, str) else backend
+ self.use_cuda_fp16 = use_cuda_fp16
+ self.model_seqlen = model_seqlen
+ self.block_name_to_quantize = block_name_to_quantize
+ self.module_name_preceding_first_block = module_name_preceding_first_block
+ self.batch_size = batch_size
+ self.pad_token_id = pad_token_id
+ self.use_exllama = use_exllama
+ self.max_input_length = max_input_length
+ self.exllama_config = exllama_config
+ self.disable_exllama = kwargs.pop("disable_exllama", None)
+ self.cache_block_outputs = cache_block_outputs
+ self.modules_in_block_to_quantize = modules_in_block_to_quantize
+ self.post_init()
+
+ def get_loading_attributes(self):
+ attibutes_dict = copy.deepcopy(self.__dict__)
+ loading_attibutes = [
+ "disable_exllama",
+ "use_exllama",
+ "exllama_config",
+ "use_cuda_fp16",
+ "max_input_length",
+ "backend",
+ ]
+ loading_attibutes_dict = {i: j for i, j in attibutes_dict.items() if i in loading_attibutes}
+ return loading_attibutes_dict
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ if self.bits not in [2, 3, 4, 8]:
+ raise ValueError(f"Only support quantization to [2,3,4,8] bits but found {self.bits}")
+ if self.group_size != -1 and self.group_size <= 0:
+ raise ValueError("group_size must be greater than 0 or equal to -1")
+ if not (0 < self.damp_percent < 1):
+ raise ValueError("damp_percent must between 0 and 1.")
+ if self.dataset is not None:
+ if isinstance(self.dataset, str):
+ if self.dataset in ["ptb", "ptb-new"]:
+ raise ValueError(
+ f"""{self.dataset} dataset was deprecated. You can only choose between
+ ['wikitext2','c4','c4-new']"""
+ )
+ if self.dataset not in ["wikitext2", "c4", "c4-new"]:
+ raise ValueError(
+ f"""You have entered a string value for dataset. You can only choose between
+ ['wikitext2','c4','c4-new'], but we found {self.dataset}"""
+ )
+ elif not isinstance(self.dataset, list):
+ raise ValueError(
+ f"""dataset needs to be either a list of string or a value in
+ ['wikitext2','c4','c4-new'], but we found {self.dataset}"""
+ )
+
+ # make sure backend is back/forward compatible with both gptqmodel (full) and auto-gptq (partial)
+ if is_gptqmodel_available():
+ # convert auto-gptq control into gptqmodel backend
+ if self.backend is None:
+ self.backend = "auto_trainable" if self.use_exllama is not None and not self.use_exllama else "auto"
+ else:
+ # convert gptqmodel backend `auto_trainable` into auto-gptq control
+ if self.backend == "auto_trainable":
+ self.use_exllama = False
+
+ # auto-gptq specific kernel control logic
+ if self.disable_exllama is None and self.use_exllama is None:
+ # New default behaviour
+ self.use_exllama = True
+ elif self.disable_exllama is not None and self.use_exllama is None:
+ # Follow pattern of old config
+ logger.warning(
+ "Using `disable_exllama` is deprecated and will be removed in version 4.37. Use `use_exllama` instead and specify the version with `exllama_config`."
+ "The value of `use_exllama` will be overwritten by `disable_exllama` passed in `GPTQConfig` or stored in your config file."
+ )
+ self.use_exllama = not self.disable_exllama
+ self.disable_exllama = None
+ elif self.disable_exllama is not None and self.use_exllama is not None:
+ # Only happens if user explicitly passes in both arguments
+ raise ValueError("Cannot specify both `disable_exllama` and `use_exllama`. Please use just `use_exllama`")
+
+ if self.exllama_config is None:
+ self.exllama_config = {"version": ExllamaVersion.ONE}
+ else:
+ if "version" not in self.exllama_config:
+ raise ValueError("`exllama_config` needs to have a `version` key.")
+ elif self.exllama_config["version"] not in [ExllamaVersion.ONE, ExllamaVersion.TWO]:
+ exllama_version = self.exllama_config["version"]
+ raise ValueError(
+ f"Only supported versions are in [ExllamaVersion.ONE, ExllamaVersion.TWO] - not recognized version {exllama_version}"
+ )
+
+ if self.bits == 4 and self.use_exllama:
+ if self.exllama_config["version"] == ExllamaVersion.ONE:
+ logger.info(
+ "You have activated exllama backend. Note that you can get better inference "
+ "speed using exllamav2 kernel by setting `exllama_config`."
+ )
+ elif self.exllama_config["version"] == ExllamaVersion.TWO:
+ if is_auto_gptq_available():
+ optimum_version = version.parse(importlib.metadata.version("optimum"))
+ autogptq_version = version.parse(importlib.metadata.version("auto_gptq"))
+ if optimum_version <= version.parse("1.13.2") or autogptq_version <= version.parse("0.4.2"):
+ raise ValueError(
+ f"You need optimum > 1.13.2 and auto-gptq > 0.4.2 . Make sure to have that version installed - detected version : optimum {optimum_version} and autogptq {autogptq_version}"
+ )
+ if self.modules_in_block_to_quantize is not None:
+ optimum_version = version.parse(importlib.metadata.version("optimum"))
+ if optimum_version < version.parse("1.15.0"):
+ raise ValueError(
+ "You current version of `optimum` does not support `modules_in_block_to_quantize` quantization argument, please upgrade `optimum` package to a version superior than 1.15.0 ."
+ )
+
+ def to_dict(self):
+ config_dict = super().to_dict()
+ config_dict.pop("disable_exllama", None)
+ return config_dict
+
+ def to_dict_optimum(self):
+ """
+ Get compatible dict for optimum gptq config
+ """
+ quant_dict = self.to_dict()
+ # make it compatible with optimum config
+ quant_dict["disable_exllama"] = not self.use_exllama
+ return quant_dict
+
+ @classmethod
+ def from_dict_optimum(cls, config_dict):
+ """
+ Get compatible class with optimum gptq config dict
+ """
+
+ if "disable_exllama" in config_dict:
+ config_dict["use_exllama"] = not config_dict["disable_exllama"]
+ # switch to None to not trigger the warning
+ config_dict["disable_exllama"] = None
+
+ config = cls(**config_dict)
+ return config
+
+
+@dataclass
+class AwqConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded using `auto-awq` library awq quantization relying on auto_awq backend.
+
+ Args:
+ bits (`int`, *optional*, defaults to 4):
+ The number of bits to quantize to.
+ group_size (`int`, *optional*, defaults to 128):
+ The group size to use for quantization. Recommended value is 128 and -1 uses per-column quantization.
+ zero_point (`bool`, *optional*, defaults to `True`):
+ Whether to use zero point quantization.
+ version (`AWQLinearVersion`, *optional*, defaults to `AWQLinearVersion.GEMM`):
+ The version of the quantization algorithm to use. GEMM is better for big batch_size (e.g. >= 8) otherwise,
+ GEMV is better (e.g. < 8 ). GEMM models are compatible with Exllama kernels.
+ backend (`AwqBackendPackingMethod`, *optional*, defaults to `AwqBackendPackingMethod.AUTOAWQ`):
+ The quantization backend. Some models might be quantized using `llm-awq` backend. This is useful for users
+ that quantize their own models using `llm-awq` library.
+ do_fuse (`bool`, *optional*, defaults to `False`):
+ Whether to fuse attention and mlp layers together for faster inference
+ fuse_max_seq_len (`int`, *optional*):
+ The Maximum sequence length to generate when using fusing.
+ modules_to_fuse (`dict`, *optional*, default to `None`):
+ Overwrite the natively supported fusing scheme with the one specified by the users.
+ modules_to_not_convert (`list`, *optional*, default to `None`):
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have
+ some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers).
+ Note you cannot quantize directly with transformers, please refer to `AutoAWQ` documentation for quantizing HF models.
+ exllama_config (`Dict[str, Any]`, *optional*):
+ You can specify the version of the exllama kernel through the `version` key, the maximum sequence
+ length through the `max_input_len` key, and the maximum batch size through the `max_batch_size` key.
+ Defaults to `{"version": 2, "max_input_len": 2048, "max_batch_size": 8}` if unset.
+ """
+
+ def __init__(
+ self,
+ bits: int = 4,
+ group_size: int = 128,
+ zero_point: bool = True,
+ version: AWQLinearVersion = AWQLinearVersion.GEMM,
+ backend: AwqBackendPackingMethod = AwqBackendPackingMethod.AUTOAWQ,
+ do_fuse: Optional[bool] = None,
+ fuse_max_seq_len: Optional[int] = None,
+ modules_to_fuse: Optional[dict] = None,
+ modules_to_not_convert: Optional[List] = None,
+ exllama_config: Optional[Dict[str, int]] = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.AWQ
+
+ self.bits = bits
+ self.group_size = group_size
+ self.zero_point = zero_point
+ self.version = version
+ self.backend = backend
+ self.fuse_max_seq_len = fuse_max_seq_len
+ self.modules_to_not_convert = modules_to_not_convert
+ self.exllama_config = exllama_config
+
+ self.modules_to_fuse = modules_to_fuse
+ if do_fuse is None:
+ self.do_fuse = modules_to_fuse is not None and len(modules_to_fuse) > 0
+ else:
+ self.do_fuse = do_fuse
+ self.fuse_max_seq_len = fuse_max_seq_len
+
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ if self.backend not in [AwqBackendPackingMethod.AUTOAWQ, AwqBackendPackingMethod.LLMAWQ]:
+ raise ValueError(
+ f"Only supported quantization backends in {AwqBackendPackingMethod.AUTOAWQ} and {AwqBackendPackingMethod.LLMAWQ} - not recognized backend {self.backend}"
+ )
+
+ self.version = AWQLinearVersion.from_str(self.version)
+ if self.version not in [
+ AWQLinearVersion.GEMM,
+ AWQLinearVersion.GEMV,
+ AWQLinearVersion.EXLLAMA,
+ AWQLinearVersion.IPEX,
+ ]:
+ raise ValueError(
+ f"Only supported versions are in [AWQLinearVersion.GEMM, AWQLinearVersion.GEMV, AWQLinearVersion.EXLLAMA, AWQLinearVersion.IPEX] - not recognized version {self.version}"
+ )
+
+ if self.backend == AwqBackendPackingMethod.LLMAWQ:
+ compute_capability = torch.cuda.get_device_capability()
+ major, minor = compute_capability
+ if major < 8:
+ raise ValueError("LLM-AWQ backend is only supported on GPUs with compute capability >= 8.0")
+
+ if self.do_fuse and self.fuse_max_seq_len is None:
+ raise ValueError(
+ "You cannot enable fused modules without specifying a `fuse_max_seq_len`, make sure to pass a valid `fuse_max_seq_len` for your usecase"
+ )
+
+ if self.do_fuse:
+ awq_version_supports_fusing = False
+ MIN_AWQ_VERSION = "0.1.7"
+ if is_auto_awq_available():
+ awq_version_supports_fusing = version.parse(importlib.metadata.version("autoawq")) >= version.parse(
+ MIN_AWQ_VERSION
+ )
+
+ if not awq_version_supports_fusing:
+ raise ValueError(
+ f"You current version of `autoawq` does not support module fusing, please upgrade `autoawq` package to at least {MIN_AWQ_VERSION}."
+ )
+
+ if self.modules_to_not_convert is not None:
+ awq_version_supports_non_conversion = False
+ MIN_AWQ_VERSION = "0.1.8"
+ if is_auto_awq_available():
+ awq_version_supports_non_conversion = version.parse(
+ importlib.metadata.version("autoawq")
+ ) >= version.parse(MIN_AWQ_VERSION)
+
+ if not awq_version_supports_non_conversion:
+ raise ValueError(
+ f"You current version of `autoawq` does not support module quantization skipping, please upgrade `autoawq` package to at least {MIN_AWQ_VERSION}."
+ )
+
+ if self.do_fuse and self.modules_to_fuse is not None:
+ required_keys = [
+ "hidden_size",
+ "num_attention_heads",
+ "num_key_value_heads",
+ "mlp",
+ "attention",
+ "layernorm",
+ "use_alibi",
+ ]
+ if not all(key in self.modules_to_fuse for key in required_keys):
+ raise ValueError(
+ f"Required fields are missing in the fusing mapping, required fields are {required_keys}"
+ )
+
+ if self.version == AWQLinearVersion.EXLLAMA:
+ awq_version_supports_exllama = False
+ MIN_AWQ_VERSION = "0.2.0"
+ if is_auto_awq_available():
+ awq_version_supports_exllama = version.parse(importlib.metadata.version("autoawq")) >= version.parse(
+ MIN_AWQ_VERSION
+ )
+
+ if not awq_version_supports_exllama:
+ raise ValueError(
+ f"You current version of `autoawq` does not support exllama backend, "
+ f"please upgrade `autoawq` package to at least {MIN_AWQ_VERSION}."
+ )
+
+ if self.exllama_config is None:
+ self.exllama_config = {"version": ExllamaVersion.TWO, "max_input_len": 2048, "max_batch_size": 8}
+ else:
+ if "version" not in self.exllama_config:
+ raise ValueError("`exllama_config` needs to have a `version` key.")
+ elif self.exllama_config["version"] not in [ExllamaVersion.ONE, ExllamaVersion.TWO]:
+ exllama_version = self.exllama_config["version"]
+ raise ValueError(
+ f"Only supported versions are in [ExllamaVersion.ONE, ExllamaVersion.TWO] - not recognized version {exllama_version}"
+ )
+
+ def get_loading_attributes(self):
+ attibutes_dict = copy.deepcopy(self.__dict__)
+ loading_attibutes = ["version", "do_fuse", "modules_to_fuse", "fuse_max_seq_len", "exllama_config"]
+ loading_attibutes_dict = {i: j for i, j in attibutes_dict.items() if i in loading_attibutes}
+ return loading_attibutes_dict
+
+
+@dataclass
+class AqlmConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about `aqlm` parameters.
+
+ Args:
+ in_group_size (`int`, *optional*, defaults to 8):
+ The group size along the input dimension.
+ out_group_size (`int`, *optional*, defaults to 1):
+ The group size along the output dimension. It's recommended to always use 1.
+ num_codebooks (`int`, *optional*, defaults to 1):
+ Number of codebooks for the Additive Quantization procedure.
+ nbits_per_codebook (`int`, *optional*, defaults to 16):
+ Number of bits encoding a single codebook vector. Codebooks size is 2**nbits_per_codebook.
+ linear_weights_not_to_quantize (`Optional[List[str]]`, *optional*):
+ List of full paths of `nn.Linear` weight parameters that shall not be quantized.
+ kwargs (`Dict[str, Any]`, *optional*):
+ Additional parameters from which to initialize the configuration object.
+ """
+
+ def __init__(
+ self,
+ in_group_size: int = 8,
+ out_group_size: int = 1,
+ num_codebooks: int = 1,
+ nbits_per_codebook: int = 16,
+ linear_weights_not_to_quantize: Optional[List[str]] = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.AQLM
+ self.in_group_size = in_group_size
+ self.out_group_size = out_group_size
+ self.num_codebooks = num_codebooks
+ self.nbits_per_codebook = nbits_per_codebook
+ self.linear_weights_not_to_quantize = linear_weights_not_to_quantize
+
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
+ """
+ if not isinstance(self.in_group_size, int):
+ raise TypeError("in_group_size must be a float")
+ if not isinstance(self.out_group_size, int):
+ raise TypeError("out_group_size must be a float")
+ if not isinstance(self.num_codebooks, int):
+ raise TypeError("num_codebooks must be a float")
+ if not isinstance(self.nbits_per_codebook, int):
+ raise TypeError("nbits_per_codebook must be a float")
+
+ if self.linear_weights_not_to_quantize is not None and not isinstance(
+ self.linear_weights_not_to_quantize, list
+ ):
+ raise ValueError("linear_weights_not_to_quantize must be a list of strings")
+
+ if self.linear_weights_not_to_quantize is None:
+ self.linear_weights_not_to_quantize = []
+
+
+@dataclass
+class VptqLayerConfig(QuantizationConfigMixin):
+ """
+ This is used to explain vptq config params for each layer
+ Args:
+ enable_norm (`bool`, *optional*, defaults to `True`): to control if we have scale/bias for fp-weight
+ enable_perm (`bool`, *optional*, defaults to `True`): to perm input_channel or not
+ group_num (`int`, *optional*, defaults to `1`): how many single groups for vector-quantization
+ group_size (`int`, *optional*, defaults to `-1`): depends on out-features
+ indices_as_float (`bool`, *optional*, defaults to `False`): for Finetuning
+ is_indice_packed (`bool`, *optional*, defaults to `True`): should always be True
+ num_centroids (`list`, *optional*, defaults to `[-1, -1]`): centriod numbers of clusters
+ num_res_centroids (`list`, *optional*, defaults to `[-1, -1]`): ditto for residual
+ outlier_size (`int`, *optional*, defaults to `1`): outliers
+ vector_lens (`list`, *optional*, defaults to `[-1, -1]`): centroid vector length in quantization
+ """
+
+ def __init__(
+ self,
+ enable_norm: bool = True,
+ enable_perm: bool = True,
+ group_num: int = 1,
+ group_size: int = -1,
+ in_features: int = -1,
+ indices_as_float: bool = False,
+ is_indice_packed: bool = True,
+ num_centroids: tuple = [-1, -1],
+ num_res_centroids: tuple = [-1, -1],
+ out_features: int = -1,
+ outlier_size: int = 0,
+ vector_lens: tuple = [-1, -1],
+ **kwargs,
+ ):
+ self.enable_norm = enable_norm
+ self.enable_perm = enable_perm
+ self.group_num = group_num
+ self.group_size = group_size
+ self.in_features = in_features
+ self.indices_as_float = indices_as_float
+ self.is_indice_packed = is_indice_packed
+ self.num_centroids = num_centroids
+ self.num_res_centroids = num_res_centroids
+ self.out_features = out_features
+ self.outlier_size = outlier_size
+ self.vector_lens = vector_lens
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ if self.is_indice_packed is False:
+ raise ValueError("is_indice_packed should always be True")
+
+
+@dataclass
+class VptqConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about `vptq` parameters.
+
+ Args:
+ enable_proxy_error (`bool`, *optional*, defaults to `False`): calculate proxy error for each layer
+ config_for_layers (`Dict`, *optional*, defaults to `{}`): quantization params for each layer
+ shared_layer_config (`Dict`, *optional*, defaults to `{}`): shared quantization params among layers
+ modules_to_not_convert (`list`, *optional*, default to `None`):
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have
+ some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers).
+ kwargs (`Dict[str, Any]`, *optional*):
+ Additional parameters from which to initialize the configuration object.
+ """
+
+ def __init__(
+ self,
+ enable_proxy_error: bool = False,
+ config_for_layers: Dict[str, Any] = {},
+ shared_layer_config: Dict[str, Any] = {},
+ modules_to_not_convert: Optional[List] = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.VPTQ
+ self.enable_proxy_error = enable_proxy_error
+ self.config_for_layers: Dict[str, Any] = config_for_layers
+ self.shared_layer_config: Dict[str, Any] = shared_layer_config
+ self.modules_to_not_convert = modules_to_not_convert
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ for layer_name, layer_param in self.config_for_layers.items():
+ VptqLayerConfig(**layer_param)
+ if self.enable_proxy_error is True:
+ raise ValueError("enable_proxy_error should always be False until we support training")
+
+
+@dataclass
+class QuantoConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded using `quanto`.
+
+ Args:
+ weights (`str`, *optional*, defaults to `"int8"`):
+ The target dtype for the weights after quantization. Supported values are ("float8","int8","int4","int2")
+ activations (`str`, *optional*):
+ The target dtype for the activations after quantization. Supported values are (None,"int8","float8")
+ modules_to_not_convert (`list`, *optional*, default to `None`):
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have
+ some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers).
+ """
+
+ def __init__(
+ self,
+ weights="int8",
+ activations=None,
+ modules_to_not_convert: Optional[List] = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.QUANTO
+ self.weights = weights
+ self.activations = activations
+ self.modules_to_not_convert = modules_to_not_convert
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ accepted_weights = ["float8", "int8", "int4", "int2"]
+ accepted_activations = [None, "int8", "float8"]
+ if self.weights not in accepted_weights:
+ raise ValueError(f"Only support weights in {accepted_weights} but found {self.weights}")
+ if self.activations not in accepted_activations:
+ raise ValueError(f"Only support weights in {accepted_activations} but found {self.activations}")
+
+
+@dataclass
+class EetqConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded using `eetq`.
+
+ Args:
+ weights (`str`, *optional*, defaults to `"int8"`):
+ The target dtype for the weights. Supported value is only "int8"
+ modules_to_not_convert (`list`, *optional*, default to `None`):
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have
+ some modules left in their original precision.
+ """
+
+ def __init__(
+ self,
+ weights: str = "int8",
+ modules_to_not_convert: Optional[List] = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.EETQ
+ self.weights = weights
+ self.modules_to_not_convert = modules_to_not_convert
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ accepted_weights = ["int8"]
+ if self.weights not in accepted_weights:
+ raise ValueError(f"Only support weights in {accepted_weights} but found {self.weights}")
+
+
+class CompressedTensorsConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class that handles compressed-tensors quantization config options.
+ It is a wrapper around `compressed_tensors.QuantizationConfig`
+ Args:
+ config_groups (`typing.Dict[str, typing.Union[ForwardRef('QuantizationScheme'), typing.List[str]]]`, *optional*):
+ dictionary mapping group name to a quantization scheme definition
+ format (`str`, *optional*, defaults to `"dense"`):
+ format the model is represented as. Set `run_compressed` True to execute model as the
+ compressed format if not `dense`
+ quantization_status (`QuantizationStatus`, *optional*, defaults to `"initialized"`):
+ status of model in the quantization lifecycle, ie 'initialized', 'calibration', 'frozen'
+ kv_cache_scheme (`typing.Union[QuantizationArgs, NoneType]`, *optional*):
+ specifies quantization of the kv cache. If None, kv cache is not quantized.
+ global_compression_ratio (`typing.Union[float, NoneType]`, *optional*):
+ 0-1 float percentage of model compression
+ ignore (`typing.Union[typing.List[str], NoneType]`, *optional*):
+ layer names or types to not quantize, supports regex prefixed by 're:'
+ sparsity_config (`typing.Dict[str, typing.Any]`, *optional*):
+ configuration for sparsity compression
+ quant_method (`str`, *optional*, defaults to `"compressed-tensors"`):
+ do not override, should be compressed-tensors
+ run_compressed (`bool`, *optional*, defaults to `True`): alter submodules (usually linear) in order to
+ emulate compressed model execution if True, otherwise use default submodule
+ """
+
+ def __init__(
+ self,
+ config_groups: Dict[str, Union["QuantizationScheme", List[str]]] = None, # noqa: F821
+ format: str = "dense",
+ quantization_status: "QuantizationStatus" = "initialized", # noqa: F821
+ kv_cache_scheme: Optional["QuantizationArgs"] = None, # noqa: F821
+ global_compression_ratio: Optional[float] = None,
+ ignore: Optional[List[str]] = None,
+ sparsity_config: Dict[str, Any] = None,
+ quant_method: str = "compressed-tensors",
+ run_compressed: bool = True,
+ **kwargs,
+ ):
+ if is_compressed_tensors_available():
+ from compressed_tensors.config import SparsityCompressionConfig
+ from compressed_tensors.quantization import QuantizationConfig
+ else:
+ raise ImportError(
+ "compressed_tensors is not installed and is required for compressed-tensors quantization. Please install it with `pip install compressed-tensors`."
+ )
+ self.quantization_config = None
+ self.sparsity_config = None
+
+ self.run_compressed = run_compressed
+
+ # parse from dict to load nested QuantizationScheme objects
+ if config_groups or kv_cache_scheme:
+ self.quantization_config = QuantizationConfig.parse_obj(
+ {
+ "config_groups": config_groups,
+ "quant_method": quant_method,
+ "format": format,
+ "quantization_status": quantization_status,
+ "kv_cache_scheme": kv_cache_scheme,
+ "global_compression_ratio": global_compression_ratio,
+ "ignore": ignore,
+ "run_compressed": run_compressed,
+ **kwargs,
+ }
+ )
+
+ if sparsity_config:
+ self.sparsity_config = SparsityCompressionConfig.load_from_registry(
+ sparsity_config.get("format"), **sparsity_config
+ )
+
+ super().__init__(quant_method=QuantizationMethod.COMPRESSED_TENSORS)
+
+ @classmethod
+ def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs):
+ """
+ Instantiates a [`CompressedTensorsConfig`] from a Python dictionary of parameters.
+ Optionally unwraps any args from the nested quantization_config
+
+ Args:
+ config_dict (`Dict[str, Any]`):
+ Dictionary that will be used to instantiate the configuration object.
+ return_unused_kwargs (`bool`,*optional*, defaults to `False`):
+ Whether or not to return a list of unused keyword arguments. Used for `from_pretrained` method in
+ `PreTrainedModel`.
+ kwargs (`Dict[str, Any]`):
+ Additional parameters from which to initialize the configuration object.
+
+ Returns:
+ [`QuantizationConfigMixin`]: The configuration object instantiated from those parameters.
+
+ """
+
+ if "quantization_config" in config_dict:
+ config_dict = dict(
+ sparsity_config=config_dict.get("sparsity_config"),
+ **config_dict["quantization_config"],
+ )
+
+ return super().from_dict(config_dict, return_unused_kwargs=return_unused_kwargs, **kwargs)
+
+ def to_dict(self) -> Dict[str, Any]:
+ """
+ Quantization config to be added to config.json
+
+ Serializes this instance to a Python dictionary. Returns:
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
+ """
+ quantization_config = {}
+ if self.quantization_config is not None:
+ quantization_config = self.quantization_config.dict()
+ else:
+ quantization_config["quant_method"] = QuantizationMethod.COMPRESSED_TENSORS
+
+ if self.sparsity_config is not None:
+ quantization_config["sparsity_config"] = self.sparsity_config.dict()
+ else:
+ quantization_config["sparsity_config"] = {}
+
+ return quantization_config
+
+ def to_diff_dict(self) -> Dict[str, Any]:
+ """
+ Removes all attributes from config which correspond to the default config attributes for better readability and
+ serializes to a Python dictionary.
+ Returns:
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
+ """
+ config_dict = self.to_dict()
+
+ # get the default config dict
+ default_config_dict = CompressedTensorsConfig().to_dict()
+
+ serializable_config_dict = {}
+
+ # only serialize values that differ from the default config
+ for key, value in config_dict.items():
+ if value != default_config_dict[key]:
+ serializable_config_dict[key] = value
+
+ return serializable_config_dict
+
+ def get_loading_attributes(self):
+ return {"run_compressed": self.run_compressed}
+
+
+@dataclass
+class FbgemmFp8Config(QuantizationConfigMixin):
+ """
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded using fbgemm fp8 quantization.
+
+ Args:
+ activation_scale_ub (`float`, *optional*, defaults to 1200.0):
+ The activation scale upper bound. This is used when quantizing the input activation.
+ modules_to_not_convert (`list`, *optional*, default to `None`):
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have
+ some modules left in their original precision.
+ """
+
+ def __init__(
+ self,
+ activation_scale_ub: float = 1200.0,
+ modules_to_not_convert: Optional[List] = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.FBGEMM_FP8
+ self.activation_scale_ub = activation_scale_ub
+ self.modules_to_not_convert = modules_to_not_convert
+
+ def get_loading_attributes(self):
+ attibutes_dict = copy.deepcopy(self.__dict__)
+ loading_attibutes = ["activation_scale_ub"]
+ loading_attibutes_dict = {i: j for i, j in attibutes_dict.items() if i in loading_attibutes}
+ return loading_attibutes_dict
+
+
+@dataclass
+class HiggsConfig(QuantizationConfigMixin):
+ """
+ HiggsConfig is a configuration class for quantization using the HIGGS method.
+
+ Args:
+ bits (int, *optional*, defaults to 4):
+ Number of bits to use for quantization. Can be 2, 3 or 4. Default is 4.
+ p (int, *optional*, defaults to 2):
+ Quantization grid dimension. 1 and 2 are supported. 2 is always better in practice. Default is 2.
+ modules_to_not_convert (`list`, *optional*, default to ["lm_head"]):
+ List of linear layers that should not be quantized.
+ hadamard_size (int, *optional*, defaults to 512):
+ Hadamard size for the HIGGS method. Default is 512. Input dimension of matrices is padded to this value. Decreasing this below 512 will reduce the quality of the quantization.
+ group_size (int, *optional*, defaults to 256):
+ Group size for the HIGGS method. Can be 64, 128 or 256. Decreasing it barely affects the performance. Default is 256. Must be a divisor of hadamard_size.
+ tune_metadata ('dict', *optional*, defaults to {}):
+ Module-wise metadata (gemm block shapes, GPU metadata, etc.) for saving the kernel tuning results. Default is an empty dictionary. Is set automatically during tuning.
+ """
+
+ def __init__(
+ self,
+ bits: int = 4,
+ p: int = 2,
+ modules_to_not_convert: Optional[List[str]] = None,
+ hadamard_size: int = 512,
+ group_size: int = 256,
+ tune_metadata: Optional[Dict[str, Any]] = None,
+ **kwargs,
+ ):
+ if tune_metadata is None:
+ tune_metadata = {}
+ self.quant_method = QuantizationMethod.HIGGS
+ self.bits = bits
+ self.p = p
+ self.modules_to_not_convert = modules_to_not_convert
+ self.hadamard_size = hadamard_size
+ self.group_size = group_size
+ self.tune_metadata = tune_metadata
+
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
+ """
+ if self.bits not in [2, 3, 4]:
+ raise ValueError("bits must be 2, 3, or 4")
+ if self.p not in [1, 2]:
+ raise ValueError("p must be 1 or 2. 2 is always better in practice")
+ if self.group_size not in [64, 128, 256]:
+ raise ValueError("group_size must be 64, 128, or 256")
+ if self.hadamard_size % self.group_size != 0:
+ raise ValueError("hadamard_size must be divisible by group_size")
+
+
+@dataclass
+class TorchAoConfig(QuantizationConfigMixin):
+ """This is a config class for torchao quantization/sparsity techniques.
+
+ Args:
+ quant_type (`str`):
+ The type of quantization we want to use, currently supporting: `int4_weight_only`, `int8_weight_only`, `int8_dynamic_activation_int8_weight` and `autoquant`.
+ modules_to_not_convert (`list`, *optional*, default to `None`):
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have
+ some modules left in their original precision.
+ kwargs (`Dict[str, Any]`, *optional*):
+ The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments
+ `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in
+ https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques
+
+ Example:
+
+ ```python
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
+
+ # specific quantization method
+ quantization_config = TorchAoConfig("int4_weight_only", group_size=32)
+ # int4_weight_only quant is only working with *torch.bfloat16* dtype right now
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cuda", torch_dtype=torch.bfloat16, quantization_config=quantization_config)
+
+ # autoquant
+ # `autoquant` is a convenient way for users to search for the best quantization for each layer
+ # `min_sqnr` is an option to control the accuracy of the model, higher value means the model is more
+ # accurate, we can start with 30 and adjust it to larger or smaller (e.g. 40, 20)
+ # defaults to None, which means we'll try to get the best performing quantized model without
+ # considering accuracy
+ quantization_config = TorchAoConfig("autoquant", min_sqnr=30)
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cuda", torch_dtype=torch.bfloat16, quantization_config=quantization_config)
+ # run through example inputs, quantization methods will be selected based on the shape of example input
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
+ input_text = "What are we having for dinner?"
+ input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
+ MAX_NEW_TOKENS = 1000
+ model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation="static")
+ # manually ran finalize_autoquant if needed
+ if hasattr(quantized_model, "finalize_autoquant"):
+ print("finalizing autoquant")
+ quantized_model.finalize_autoquant()
+ ```
+ """
+
+ def __init__(self, quant_type: str, modules_to_not_convert: Optional[List] = None, **kwargs):
+ self.quant_method = QuantizationMethod.TORCHAO
+ self.quant_type = quant_type
+ self.modules_to_not_convert = modules_to_not_convert
+ # when we load from serailized config, "quant_type_kwargs" will be the key
+ if "quant_type_kwargs" in kwargs:
+ self.quant_type_kwargs = kwargs["quant_type_kwargs"]
+ else:
+ self.quant_type_kwargs = kwargs
+
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
+ """
+ if is_torchao_available():
+ if not version.parse(importlib.metadata.version("torchao")) >= version.parse("0.7.0"):
+ raise ValueError("Requires torchao 0.7.0 version and above")
+ else:
+ raise ValueError(
+ "TorchAoConfig requires torchao to be installed, please install with `pip install torchao`"
+ )
+
+ _STR_TO_METHOD = self._get_torchao_quant_type_to_method()
+ if self.quant_type not in _STR_TO_METHOD.keys():
+ raise ValueError(
+ f"Requested quantization type: {self.quant_type} is not supported yet, please add support in TorchAoConfig and TorchAoHfQuantizer."
+ )
+
+ method = _STR_TO_METHOD[self.quant_type]
+ sig = signature(method)
+ all_kwargs = [
+ param.name
+ for param in sig.parameters.values()
+ if param.kind in [Parameter.KEYWORD_ONLY, Parameter.POSITIONAL_OR_KEYWORD]
+ ]
+ for k in self.quant_type_kwargs:
+ if k not in all_kwargs:
+ raise ValueError(
+ f"Unexpected keyword arg: {k} for API: {method}, accepted keyword args are: {all_kwargs}"
+ )
+
+ def _get_torchao_quant_type_to_method(self):
+ if is_torchao_available():
+ from torchao.quantization import (
+ autoquant,
+ int4_weight_only,
+ int8_dynamic_activation_int8_weight,
+ int8_weight_only,
+ )
+
+ return {
+ "int4_weight_only": int4_weight_only,
+ "int8_weight_only": int8_weight_only,
+ "int8_dynamic_activation_int8_weight": int8_dynamic_activation_int8_weight,
+ "autoquant": autoquant,
+ }
+ else:
+ raise ValueError(
+ "TorchAoConfig requires torchao to be installed, please install with `pip install torchao`"
+ )
+
+ def get_apply_tensor_subclass(self):
+ _STR_TO_METHOD = self._get_torchao_quant_type_to_method()
+ quant_type_kwargs = self.quant_type_kwargs.copy()
+ if (
+ not torch.cuda.is_available()
+ and is_torchao_available()
+ and self.quant_type == "int4_weight_only"
+ and version.parse(importlib.metadata.version("torchao")) >= version.parse("0.8.0")
+ ):
+ from torchao.dtypes import Int4CPULayout
+
+ quant_type_kwargs["layout"] = Int4CPULayout()
+ return _STR_TO_METHOD[self.quant_type](**quant_type_kwargs)
+
+ def __repr__(self):
+ config_dict = self.to_dict()
+ return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n"
+
+ def to_dict(self) -> Dict[str, Any]:
+ """
+ Serializes this instance to a Python dictionary, converting any `torchao.dtypes.Layout`
+ dataclasses to simple dicts.
+
+ Returns:
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
+ """
+ d = super().to_dict()
+ if "quant_type_kwargs" in d and "layout" in d["quant_type_kwargs"]:
+ layout = d["quant_type_kwargs"]["layout"]
+ layout = dataclasses.asdict(layout)
+ d["quant_type_kwargs"]["layout"] = layout
+ return d
+
+
+@dataclass
+class BitNetConfig(QuantizationConfigMixin):
+ def __init__(
+ self,
+ modules_to_not_convert: Optional[List] = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.BITNET
+ self.modules_to_not_convert = modules_to_not_convert
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ pass
+
+
+@dataclass
+class SpQRConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about `spqr` parameters. Refer to the original publication for more details.
+
+ Args:
+ bits (`int`, *optional*, defaults to 3):
+ Specifies the bit count for the weights and first order zero-points and scales.
+ Currently only bits = 3 is supported.
+ beta1 (`int`, *optional*, defaults to 16):
+ SpQR tile width. Currently only beta1 = 16 is supported.
+ beta2 (`int`, *optional*, defaults to 16):
+ SpQR tile height. Currently only beta2 = 16 is supported.
+ shapes (`Optional`, *optional*):
+ A dictionary holding the shape of each object. We need this because it's impossible
+ to deduce the exact size of the parameters just from bits, beta1, beta2.
+ modules_to_not_convert (`Optional[List[str]]`, *optional*):
+ Optionally, provides a list of full paths of `nn.Linear` weight parameters that shall not be quantized.
+ Defaults to None.
+ kwargs (`Dict[str, Any]`, *optional*):
+ Additional parameters from which to initialize the configuration object.
+ """
+
+ def __init__(
+ self,
+ bits: int = 3,
+ beta1: int = 16,
+ beta2: int = 16,
+ shapes: Optional[Dict[str, int]] = None,
+ modules_to_not_convert: Optional[List[str]] = None,
+ **kwargs,
+ ):
+ if shapes is None:
+ shapes = {}
+ self.shapes = shapes
+ self.quant_method = QuantizationMethod.SPQR
+ self.bits = bits
+ self.beta1 = beta1
+ self.beta2 = beta2
+ self.modules_to_not_convert = modules_to_not_convert
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
+ """
+ if not isinstance(self.bits, int):
+ raise TypeError("bits must be an int")
+ if not isinstance(self.beta1, int):
+ raise TypeError("beta1 must be an int")
+ if not isinstance(self.beta2, int):
+ raise TypeError("beta2 must be an int")
+
+ if self.bits != 3:
+ raise ValueError("SpQR currently only supports bits = 3")
+ if self.beta1 != 16:
+ raise ValueError("SpQR currently only supports beta1 = 16")
+ if self.beta2 != 16:
+ raise ValueError("SpQR currently only supports beta2 = 16")
+ if not isinstance(self.shapes, dict):
+ raise TypeError("shapes must be a dict")
+
+
+@dataclass
+class FineGrainedFP8Config(QuantizationConfigMixin):
+ """
+ FineGrainedFP8Config is a configuration class for fine-grained FP8 quantization used mainly for deepseek models.
+
+ Args:
+ activation_scheme (`str`, *optional*, defaults to `"dynamic"`):
+ The scheme used for activation, the defaults and only support scheme for now is "dynamic".
+ weight_block_size (`typing.Tuple[int, int]`, *optional*, defaults to `(128, 128)`):
+ The size of the weight blocks for quantization, default is (128, 128).
+ modules_to_not_convert (`list`, *optional*):
+ A list of module names that should not be converted during quantization.
+ """
+
+ def __init__(
+ self,
+ activation_scheme: str = "dynamic",
+ weight_block_size: Tuple[int, int] = (128, 128),
+ modules_to_not_convert: Optional[List] = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.FP8
+ self.modules_to_not_convert = modules_to_not_convert
+ self.activation_scheme = activation_scheme
+ self.weight_block_size = weight_block_size
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ self.activation_scheme = self.activation_scheme.lower()
+ if self.activation_scheme not in ["dynamic"]:
+ raise ValueError(f"Activation scheme {self.activation_scheme} not supported")
+ if len(self.weight_block_size) != 2:
+ raise ValueError("weight_block_size must be a tuple of two integers")
+ if self.weight_block_size[0] <= 0 or self.weight_block_size[1] <= 0:
+ raise ValueError("weight_block_size must be a tuple of two positive integers")
diff --git a/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/sentencepiece_model_pb2.py b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/sentencepiece_model_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4b2992a6308c9f98f68486998d57d00bbdc1e34
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/sentencepiece_model_pb2.py
@@ -0,0 +1,1511 @@
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: sentencepiece_model.proto
+
+# 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.
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import message as _message
+from google.protobuf import reflection as _reflection
+from google.protobuf import symbol_database as _symbol_database
+
+
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+DESCRIPTOR = _descriptor.FileDescriptor(
+ name="sentencepiece_model.proto",
+ package="sentencepiece",
+ syntax="proto2",
+ serialized_options=b"H\003",
+ create_key=_descriptor._internal_create_key,
+ serialized_pb=(
+ b'\n\x19sentencepiece_model.proto\x12\rsentencepiece"\xa1\n\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01'
+ b" \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02"
+ b" \x01(\t\x12\x41\n\nmodel_type\x18\x03"
+ b" \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04"
+ b" \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12"
+ b' \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12"\n\x12\x63haracter_coverage\x18\n'
+ b" \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b"
+ b" \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12"
+ b' \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12"\n\x16training_sentence_size\x18\r'
+ b" \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e"
+ b" \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f"
+ b" \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12"
+ b" \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10"
+ b" \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11"
+ b" \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14"
+ b" \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15"
+ b" \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17"
+ b" \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16"
+ b" \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18"
+ b" \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19"
+ b" \x01(\x08:\x05\x66\x61lse\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e"
+ b" \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$"
+ b" \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18"
+ b' \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18"'
+ b" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18)"
+ b" \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+"
+ b" \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05\x12\x16\n\tbos_piece\x18."
+ b" \x01(\t:\x03\x12\x17\n\teos_piece\x18/ \x01(\t:\x04\x12\x18\n\tpad_piece\x18\x30"
+ b" \x01(\t:\x05\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87"
+ b" \x12+\n\x1ctrain_extremely_large_corpus\x18\x31"
+ b' \x01(\x08:\x05\x66\x61lse"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01'
+ b" \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03"
+ b" \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12"
+ b" \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06"
+ b' \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01'
+ b' \x03(\x0b\x32".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01'
+ b" \x01(\t\x12\x10\n\x08\x65xpected\x18\x02"
+ b' \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01'
+ b" \x03(\x0b\x32'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02"
+ b" \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03"
+ b" \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04"
+ b" \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05"
+ b" \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01"
+ b" \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03"
+ b' \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03'
+ ),
+)
+
+
+_TRAINERSPEC_MODELTYPE = _descriptor.EnumDescriptor(
+ name="ModelType",
+ full_name="sentencepiece.TrainerSpec.ModelType",
+ filename=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ values=[
+ _descriptor.EnumValueDescriptor(
+ name="UNIGRAM",
+ index=0,
+ number=1,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.EnumValueDescriptor(
+ name="BPE",
+ index=1,
+ number=2,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.EnumValueDescriptor(
+ name="WORD",
+ index=2,
+ number=3,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.EnumValueDescriptor(
+ name="CHAR",
+ index=3,
+ number=4,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ ],
+ containing_type=None,
+ serialized_options=None,
+ serialized_start=1294,
+ serialized_end=1347,
+)
+_sym_db.RegisterEnumDescriptor(_TRAINERSPEC_MODELTYPE)
+
+_MODELPROTO_SENTENCEPIECE_TYPE = _descriptor.EnumDescriptor(
+ name="Type",
+ full_name="sentencepiece.ModelProto.SentencePiece.Type",
+ filename=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ values=[
+ _descriptor.EnumValueDescriptor(
+ name="NORMAL",
+ index=0,
+ number=1,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.EnumValueDescriptor(
+ name="UNKNOWN",
+ index=1,
+ number=2,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.EnumValueDescriptor(
+ name="CONTROL",
+ index=2,
+ number=3,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.EnumValueDescriptor(
+ name="USER_DEFINED",
+ index=3,
+ number=4,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.EnumValueDescriptor(
+ name="BYTE",
+ index=4,
+ number=6,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.EnumValueDescriptor(
+ name="UNUSED",
+ index=5,
+ number=5,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ ],
+ containing_type=None,
+ serialized_options=None,
+ serialized_start=2100,
+ serialized_end=2184,
+)
+_sym_db.RegisterEnumDescriptor(_MODELPROTO_SENTENCEPIECE_TYPE)
+
+
+_TRAINERSPEC = _descriptor.Descriptor(
+ name="TrainerSpec",
+ full_name="sentencepiece.TrainerSpec",
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ create_key=_descriptor._internal_create_key,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name="input",
+ full_name="sentencepiece.TrainerSpec.input",
+ index=0,
+ number=1,
+ type=9,
+ cpp_type=9,
+ label=3,
+ has_default_value=False,
+ default_value=[],
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="input_format",
+ full_name="sentencepiece.TrainerSpec.input_format",
+ index=1,
+ number=7,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="model_prefix",
+ full_name="sentencepiece.TrainerSpec.model_prefix",
+ index=2,
+ number=2,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="model_type",
+ full_name="sentencepiece.TrainerSpec.model_type",
+ index=3,
+ number=3,
+ type=14,
+ cpp_type=8,
+ label=1,
+ has_default_value=True,
+ default_value=1,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="vocab_size",
+ full_name="sentencepiece.TrainerSpec.vocab_size",
+ index=4,
+ number=4,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=8000,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="accept_language",
+ full_name="sentencepiece.TrainerSpec.accept_language",
+ index=5,
+ number=5,
+ type=9,
+ cpp_type=9,
+ label=3,
+ has_default_value=False,
+ default_value=[],
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="self_test_sample_size",
+ full_name="sentencepiece.TrainerSpec.self_test_sample_size",
+ index=6,
+ number=6,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=0,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="character_coverage",
+ full_name="sentencepiece.TrainerSpec.character_coverage",
+ index=7,
+ number=10,
+ type=2,
+ cpp_type=6,
+ label=1,
+ has_default_value=True,
+ default_value=float(0.9995),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="input_sentence_size",
+ full_name="sentencepiece.TrainerSpec.input_sentence_size",
+ index=8,
+ number=11,
+ type=4,
+ cpp_type=4,
+ label=1,
+ has_default_value=True,
+ default_value=0,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="shuffle_input_sentence",
+ full_name="sentencepiece.TrainerSpec.shuffle_input_sentence",
+ index=9,
+ number=19,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="mining_sentence_size",
+ full_name="sentencepiece.TrainerSpec.mining_sentence_size",
+ index=10,
+ number=12,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=False,
+ default_value=0,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=b"\030\001",
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="training_sentence_size",
+ full_name="sentencepiece.TrainerSpec.training_sentence_size",
+ index=11,
+ number=13,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=False,
+ default_value=0,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=b"\030\001",
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="seed_sentencepiece_size",
+ full_name="sentencepiece.TrainerSpec.seed_sentencepiece_size",
+ index=12,
+ number=14,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=1000000,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="shrinking_factor",
+ full_name="sentencepiece.TrainerSpec.shrinking_factor",
+ index=13,
+ number=15,
+ type=2,
+ cpp_type=6,
+ label=1,
+ has_default_value=True,
+ default_value=float(0.75),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="max_sentence_length",
+ full_name="sentencepiece.TrainerSpec.max_sentence_length",
+ index=14,
+ number=18,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=4192,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="num_threads",
+ full_name="sentencepiece.TrainerSpec.num_threads",
+ index=15,
+ number=16,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=16,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="num_sub_iterations",
+ full_name="sentencepiece.TrainerSpec.num_sub_iterations",
+ index=16,
+ number=17,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=2,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="max_sentencepiece_length",
+ full_name="sentencepiece.TrainerSpec.max_sentencepiece_length",
+ index=17,
+ number=20,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=16,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="split_by_unicode_script",
+ full_name="sentencepiece.TrainerSpec.split_by_unicode_script",
+ index=18,
+ number=21,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="split_by_number",
+ full_name="sentencepiece.TrainerSpec.split_by_number",
+ index=19,
+ number=23,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="split_by_whitespace",
+ full_name="sentencepiece.TrainerSpec.split_by_whitespace",
+ index=20,
+ number=22,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="treat_whitespace_as_suffix",
+ full_name="sentencepiece.TrainerSpec.treat_whitespace_as_suffix",
+ index=21,
+ number=24,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=False,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="split_digits",
+ full_name="sentencepiece.TrainerSpec.split_digits",
+ index=22,
+ number=25,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=False,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="control_symbols",
+ full_name="sentencepiece.TrainerSpec.control_symbols",
+ index=23,
+ number=30,
+ type=9,
+ cpp_type=9,
+ label=3,
+ has_default_value=False,
+ default_value=[],
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="user_defined_symbols",
+ full_name="sentencepiece.TrainerSpec.user_defined_symbols",
+ index=24,
+ number=31,
+ type=9,
+ cpp_type=9,
+ label=3,
+ has_default_value=False,
+ default_value=[],
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="required_chars",
+ full_name="sentencepiece.TrainerSpec.required_chars",
+ index=25,
+ number=36,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="byte_fallback",
+ full_name="sentencepiece.TrainerSpec.byte_fallback",
+ index=26,
+ number=35,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=False,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="vocabulary_output_piece_score",
+ full_name="sentencepiece.TrainerSpec.vocabulary_output_piece_score",
+ index=27,
+ number=32,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="hard_vocab_limit",
+ full_name="sentencepiece.TrainerSpec.hard_vocab_limit",
+ index=28,
+ number=33,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="use_all_vocab",
+ full_name="sentencepiece.TrainerSpec.use_all_vocab",
+ index=29,
+ number=34,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=False,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="unk_id",
+ full_name="sentencepiece.TrainerSpec.unk_id",
+ index=30,
+ number=40,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=0,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="bos_id",
+ full_name="sentencepiece.TrainerSpec.bos_id",
+ index=31,
+ number=41,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=1,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="eos_id",
+ full_name="sentencepiece.TrainerSpec.eos_id",
+ index=32,
+ number=42,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=2,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="pad_id",
+ full_name="sentencepiece.TrainerSpec.pad_id",
+ index=33,
+ number=43,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=-1,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="unk_piece",
+ full_name="sentencepiece.TrainerSpec.unk_piece",
+ index=34,
+ number=45,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=True,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="bos_piece",
+ full_name="sentencepiece.TrainerSpec.bos_piece",
+ index=35,
+ number=46,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=True,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="eos_piece",
+ full_name="sentencepiece.TrainerSpec.eos_piece",
+ index=36,
+ number=47,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=True,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="pad_piece",
+ full_name="sentencepiece.TrainerSpec.pad_piece",
+ index=37,
+ number=48,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=True,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="unk_surface",
+ full_name="sentencepiece.TrainerSpec.unk_surface",
+ index=38,
+ number=44,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=True,
+ default_value=b" \342\201\207 ".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="train_extremely_large_corpus",
+ full_name="sentencepiece.TrainerSpec.train_extremely_large_corpus",
+ index=39,
+ number=49,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=False,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ ],
+ extensions=[],
+ nested_types=[],
+ enum_types=[
+ _TRAINERSPEC_MODELTYPE,
+ ],
+ serialized_options=None,
+ is_extendable=True,
+ syntax="proto2",
+ extension_ranges=[
+ (200, 536870912),
+ ],
+ oneofs=[],
+ serialized_start=45,
+ serialized_end=1358,
+)
+
+
+_NORMALIZERSPEC = _descriptor.Descriptor(
+ name="NormalizerSpec",
+ full_name="sentencepiece.NormalizerSpec",
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ create_key=_descriptor._internal_create_key,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name="name",
+ full_name="sentencepiece.NormalizerSpec.name",
+ index=0,
+ number=1,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="precompiled_charsmap",
+ full_name="sentencepiece.NormalizerSpec.precompiled_charsmap",
+ index=1,
+ number=2,
+ type=12,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"",
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="add_dummy_prefix",
+ full_name="sentencepiece.NormalizerSpec.add_dummy_prefix",
+ index=2,
+ number=3,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="remove_extra_whitespaces",
+ full_name="sentencepiece.NormalizerSpec.remove_extra_whitespaces",
+ index=3,
+ number=4,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="escape_whitespaces",
+ full_name="sentencepiece.NormalizerSpec.escape_whitespaces",
+ index=4,
+ number=5,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="normalization_rule_tsv",
+ full_name="sentencepiece.NormalizerSpec.normalization_rule_tsv",
+ index=5,
+ number=6,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ ],
+ extensions=[],
+ nested_types=[],
+ enum_types=[],
+ serialized_options=None,
+ is_extendable=True,
+ syntax="proto2",
+ extension_ranges=[
+ (200, 536870912),
+ ],
+ oneofs=[],
+ serialized_start=1361,
+ serialized_end=1570,
+)
+
+
+_SELFTESTDATA_SAMPLE = _descriptor.Descriptor(
+ name="Sample",
+ full_name="sentencepiece.SelfTestData.Sample",
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ create_key=_descriptor._internal_create_key,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name="input",
+ full_name="sentencepiece.SelfTestData.Sample.input",
+ index=0,
+ number=1,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="expected",
+ full_name="sentencepiece.SelfTestData.Sample.expected",
+ index=1,
+ number=2,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ ],
+ extensions=[],
+ nested_types=[],
+ enum_types=[],
+ serialized_options=None,
+ is_extendable=False,
+ syntax="proto2",
+ extension_ranges=[],
+ oneofs=[],
+ serialized_start=1641,
+ serialized_end=1682,
+)
+
+_SELFTESTDATA = _descriptor.Descriptor(
+ name="SelfTestData",
+ full_name="sentencepiece.SelfTestData",
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ create_key=_descriptor._internal_create_key,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name="samples",
+ full_name="sentencepiece.SelfTestData.samples",
+ index=0,
+ number=1,
+ type=11,
+ cpp_type=10,
+ label=3,
+ has_default_value=False,
+ default_value=[],
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ ],
+ extensions=[],
+ nested_types=[
+ _SELFTESTDATA_SAMPLE,
+ ],
+ enum_types=[],
+ serialized_options=None,
+ is_extendable=True,
+ syntax="proto2",
+ extension_ranges=[
+ (200, 536870912),
+ ],
+ oneofs=[],
+ serialized_start=1572,
+ serialized_end=1693,
+)
+
+
+_MODELPROTO_SENTENCEPIECE = _descriptor.Descriptor(
+ name="SentencePiece",
+ full_name="sentencepiece.ModelProto.SentencePiece",
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ create_key=_descriptor._internal_create_key,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name="piece",
+ full_name="sentencepiece.ModelProto.SentencePiece.piece",
+ index=0,
+ number=1,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="score",
+ full_name="sentencepiece.ModelProto.SentencePiece.score",
+ index=1,
+ number=2,
+ type=2,
+ cpp_type=6,
+ label=1,
+ has_default_value=False,
+ default_value=float(0),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="type",
+ full_name="sentencepiece.ModelProto.SentencePiece.type",
+ index=2,
+ number=3,
+ type=14,
+ cpp_type=8,
+ label=1,
+ has_default_value=True,
+ default_value=1,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ ],
+ extensions=[],
+ nested_types=[],
+ enum_types=[
+ _MODELPROTO_SENTENCEPIECE_TYPE,
+ ],
+ serialized_options=None,
+ is_extendable=True,
+ syntax="proto2",
+ extension_ranges=[
+ (200, 536870912),
+ ],
+ oneofs=[],
+ serialized_start=1985,
+ serialized_end=2195,
+)
+
+_MODELPROTO = _descriptor.Descriptor(
+ name="ModelProto",
+ full_name="sentencepiece.ModelProto",
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ create_key=_descriptor._internal_create_key,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name="pieces",
+ full_name="sentencepiece.ModelProto.pieces",
+ index=0,
+ number=1,
+ type=11,
+ cpp_type=10,
+ label=3,
+ has_default_value=False,
+ default_value=[],
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="trainer_spec",
+ full_name="sentencepiece.ModelProto.trainer_spec",
+ index=1,
+ number=2,
+ type=11,
+ cpp_type=10,
+ label=1,
+ has_default_value=False,
+ default_value=None,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="normalizer_spec",
+ full_name="sentencepiece.ModelProto.normalizer_spec",
+ index=2,
+ number=3,
+ type=11,
+ cpp_type=10,
+ label=1,
+ has_default_value=False,
+ default_value=None,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="self_test_data",
+ full_name="sentencepiece.ModelProto.self_test_data",
+ index=3,
+ number=4,
+ type=11,
+ cpp_type=10,
+ label=1,
+ has_default_value=False,
+ default_value=None,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="denormalizer_spec",
+ full_name="sentencepiece.ModelProto.denormalizer_spec",
+ index=4,
+ number=5,
+ type=11,
+ cpp_type=10,
+ label=1,
+ has_default_value=False,
+ default_value=None,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ ],
+ extensions=[],
+ nested_types=[
+ _MODELPROTO_SENTENCEPIECE,
+ ],
+ enum_types=[],
+ serialized_options=None,
+ is_extendable=True,
+ syntax="proto2",
+ extension_ranges=[
+ (200, 536870912),
+ ],
+ oneofs=[],
+ serialized_start=1696,
+ serialized_end=2206,
+)
+
+_TRAINERSPEC.fields_by_name["model_type"].enum_type = _TRAINERSPEC_MODELTYPE
+_TRAINERSPEC_MODELTYPE.containing_type = _TRAINERSPEC
+_SELFTESTDATA_SAMPLE.containing_type = _SELFTESTDATA
+_SELFTESTDATA.fields_by_name["samples"].message_type = _SELFTESTDATA_SAMPLE
+_MODELPROTO_SENTENCEPIECE.fields_by_name["type"].enum_type = _MODELPROTO_SENTENCEPIECE_TYPE
+_MODELPROTO_SENTENCEPIECE.containing_type = _MODELPROTO
+_MODELPROTO_SENTENCEPIECE_TYPE.containing_type = _MODELPROTO_SENTENCEPIECE
+_MODELPROTO.fields_by_name["pieces"].message_type = _MODELPROTO_SENTENCEPIECE
+_MODELPROTO.fields_by_name["trainer_spec"].message_type = _TRAINERSPEC
+_MODELPROTO.fields_by_name["normalizer_spec"].message_type = _NORMALIZERSPEC
+_MODELPROTO.fields_by_name["self_test_data"].message_type = _SELFTESTDATA
+_MODELPROTO.fields_by_name["denormalizer_spec"].message_type = _NORMALIZERSPEC
+DESCRIPTOR.message_types_by_name["TrainerSpec"] = _TRAINERSPEC
+DESCRIPTOR.message_types_by_name["NormalizerSpec"] = _NORMALIZERSPEC
+DESCRIPTOR.message_types_by_name["SelfTestData"] = _SELFTESTDATA
+DESCRIPTOR.message_types_by_name["ModelProto"] = _MODELPROTO
+_sym_db.RegisterFileDescriptor(DESCRIPTOR)
+
+TrainerSpec = _reflection.GeneratedProtocolMessageType(
+ "TrainerSpec",
+ (_message.Message,),
+ {
+ "DESCRIPTOR": _TRAINERSPEC,
+ "__module__": "sentencepiece_model_pb2",
+ # @@protoc_insertion_point(class_scope:sentencepiece.TrainerSpec)
+ },
+)
+_sym_db.RegisterMessage(TrainerSpec)
+
+NormalizerSpec = _reflection.GeneratedProtocolMessageType(
+ "NormalizerSpec",
+ (_message.Message,),
+ {
+ "DESCRIPTOR": _NORMALIZERSPEC,
+ "__module__": "sentencepiece_model_pb2",
+ # @@protoc_insertion_point(class_scope:sentencepiece.NormalizerSpec)
+ },
+)
+_sym_db.RegisterMessage(NormalizerSpec)
+
+SelfTestData = _reflection.GeneratedProtocolMessageType(
+ "SelfTestData",
+ (_message.Message,),
+ {
+ "Sample": _reflection.GeneratedProtocolMessageType(
+ "Sample",
+ (_message.Message,),
+ {
+ "DESCRIPTOR": _SELFTESTDATA_SAMPLE,
+ "__module__": "sentencepiece_model_pb2",
+ # @@protoc_insertion_point(class_scope:sentencepiece.SelfTestData.Sample)
+ },
+ ),
+ "DESCRIPTOR": _SELFTESTDATA,
+ "__module__": "sentencepiece_model_pb2",
+ # @@protoc_insertion_point(class_scope:sentencepiece.SelfTestData)
+ },
+)
+_sym_db.RegisterMessage(SelfTestData)
+_sym_db.RegisterMessage(SelfTestData.Sample)
+
+ModelProto = _reflection.GeneratedProtocolMessageType(
+ "ModelProto",
+ (_message.Message,),
+ {
+ "SentencePiece": _reflection.GeneratedProtocolMessageType(
+ "SentencePiece",
+ (_message.Message,),
+ {
+ "DESCRIPTOR": _MODELPROTO_SENTENCEPIECE,
+ "__module__": "sentencepiece_model_pb2",
+ # @@protoc_insertion_point(class_scope:sentencepiece.ModelProto.SentencePiece)
+ },
+ ),
+ "DESCRIPTOR": _MODELPROTO,
+ "__module__": "sentencepiece_model_pb2",
+ # @@protoc_insertion_point(class_scope:sentencepiece.ModelProto)
+ },
+)
+_sym_db.RegisterMessage(ModelProto)
+_sym_db.RegisterMessage(ModelProto.SentencePiece)
+
+
+DESCRIPTOR._options = None
+_TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None
+_TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None
+# @@protoc_insertion_point(module_scope)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/sentencepiece_model_pb2_new.py b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/sentencepiece_model_pb2_new.py
new file mode 100644
index 0000000000000000000000000000000000000000..65d03e5a28153528839f695e97544b9f528f5075
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/sentencepiece_model_pb2_new.py
@@ -0,0 +1,48 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: sentencepiece_model.proto
+"""Generated protocol buffer code."""
+
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+
+
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(
+ b'\n\x19sentencepiece_model.proto\x12\rsentencepiece"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05\x12\x16\n\tbos_piece\x18. \x01(\t:\x03\x12\x17\n\teos_piece\x18/ \x01(\t:\x04\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03'
+)
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "sentencepiece_model_pb2", _globals)
+if _descriptor._USE_C_DESCRIPTORS is False:
+ DESCRIPTOR._options = None
+ DESCRIPTOR._serialized_options = b"H\003"
+ # (generated by protobuf compiler, but `_TRAINERSPEC` is not defined)
+ # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None
+ # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001"
+ # _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None
+ # _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001"
+ _globals["_TRAINERSPEC"]._serialized_start = 45
+ _globals["_TRAINERSPEC"]._serialized_end = 1581
+ _globals["_TRAINERSPEC_MODELTYPE"]._serialized_start = 1517
+ _globals["_TRAINERSPEC_MODELTYPE"]._serialized_end = 1570
+ _globals["_NORMALIZERSPEC"]._serialized_start = 1584
+ _globals["_NORMALIZERSPEC"]._serialized_end = 1793
+ _globals["_SELFTESTDATA"]._serialized_start = 1795
+ _globals["_SELFTESTDATA"]._serialized_end = 1916
+ _globals["_SELFTESTDATA_SAMPLE"]._serialized_start = 1864
+ _globals["_SELFTESTDATA_SAMPLE"]._serialized_end = 1905
+ _globals["_MODELPROTO"]._serialized_start = 1919
+ _globals["_MODELPROTO"]._serialized_end = 2429
+ _globals["_MODELPROTO_SENTENCEPIECE"]._serialized_start = 2208
+ _globals["_MODELPROTO_SENTENCEPIECE"]._serialized_end = 2418
+ _globals["_MODELPROTO_SENTENCEPIECE_TYPE"]._serialized_start = 2323
+ _globals["_MODELPROTO_SENTENCEPIECE_TYPE"]._serialized_end = 2407
+# @@protoc_insertion_point(module_scope)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/versions.py b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/versions.py
new file mode 100644
index 0000000000000000000000000000000000000000..85dabec8b659022655ce570b4642febd715b6d52
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/src/transformers/utils/versions.py
@@ -0,0 +1,117 @@
+# 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.
+"""
+Utilities for working with package versions
+"""
+
+import importlib.metadata
+import operator
+import re
+import sys
+from typing import Optional
+
+from packaging import version
+
+
+ops = {
+ "<": operator.lt,
+ "<=": operator.le,
+ "==": operator.eq,
+ "!=": operator.ne,
+ ">=": operator.ge,
+ ">": operator.gt,
+}
+
+
+def _compare_versions(op, got_ver, want_ver, requirement, pkg, hint):
+ if got_ver is None or want_ver is None:
+ raise ValueError(
+ f"Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider"
+ f" reinstalling {pkg}."
+ )
+ if not ops[op](version.parse(got_ver), version.parse(want_ver)):
+ raise ImportError(
+ f"{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}"
+ )
+
+
+def require_version(requirement: str, hint: Optional[str] = None) -> None:
+ """
+ Perform a runtime check of the dependency versions, using the exact same syntax used by pip.
+
+ The installed module version comes from the *site-packages* dir via *importlib.metadata*.
+
+ Args:
+ requirement (`str`): pip style definition, e.g., "tokenizers==0.9.4", "tqdm>=4.27", "numpy"
+ hint (`str`, *optional*): what suggestion to print in case of requirements not being met
+
+ Example:
+
+ ```python
+ require_version("pandas>1.1.2")
+ require_version("numpy>1.18.5", "this is important to have for whatever reason")
+ ```"""
+
+ hint = f"\n{hint}" if hint is not None else ""
+
+ # non-versioned check
+ if re.match(r"^[\w_\-\d]+$", requirement):
+ pkg, op, want_ver = requirement, None, None
+ else:
+ match = re.findall(r"^([^!=<>\s]+)([\s!=<>]{1,2}.+)", requirement)
+ if not match:
+ raise ValueError(
+ "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but"
+ f" got {requirement}"
+ )
+ pkg, want_full = match[0]
+ want_range = want_full.split(",") # there could be multiple requirements
+ wanted = {}
+ for w in want_range:
+ match = re.findall(r"^([\s!=<>]{1,2})(.+)", w)
+ if not match:
+ raise ValueError(
+ "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,"
+ f" but got {requirement}"
+ )
+ op, want_ver = match[0]
+ wanted[op] = want_ver
+ if op not in ops:
+ raise ValueError(f"{requirement}: need one of {list(ops.keys())}, but got {op}")
+
+ # special case
+ if pkg == "python":
+ got_ver = ".".join([str(x) for x in sys.version_info[:3]])
+ for op, want_ver in wanted.items():
+ _compare_versions(op, got_ver, want_ver, requirement, pkg, hint)
+ return
+
+ # check if any version is installed
+ try:
+ got_ver = importlib.metadata.version(pkg)
+ except importlib.metadata.PackageNotFoundError:
+ raise importlib.metadata.PackageNotFoundError(
+ f"The '{requirement}' distribution was not found and is required by this application. {hint}"
+ )
+
+ # check that the right version is installed if version number or a range was provided
+ if want_ver is not None:
+ for op, want_ver in wanted.items():
+ _compare_versions(op, got_ver, want_ver, requirement, pkg, hint)
+
+
+def require_version_core(requirement):
+ """require_version wrapper which emits a core-specific hint on failure"""
+ hint = "Try: `pip install transformers -U` or `pip install -e '.[dev]'` if you're working with git main"
+ return require_version(requirement, hint)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_missing_tokenization_test/README.md b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_missing_tokenization_test/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..935f21c5ca8ab22d043bdee76041c279baf58866
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_missing_tokenization_test/README.md
@@ -0,0 +1,39 @@
+
+
+This folder contains a template to add a tokenization test.
+
+## Usage
+
+Using the `cookiecutter` utility requires to have all the `dev` dependencies installed.
+
+Let's first [fork](https://docs.github.com/en/get-started/quickstart/fork-a-repo) the `transformers` repo on github. Once it's done you can clone your fork and install `transformers` in our environment:
+
+```shell script
+git clone https://github.com/YOUR-USERNAME/transformers
+cd transformers
+pip install -e ".[dev]"
+```
+
+Once the installation is done, you can generate the template by running the following command. Be careful, the template will be generated inside a new folder in your current working directory.
+
+```shell script
+cookiecutter path-to-the folder/adding_a_missing_tokenization_test/
+```
+
+You will then have to answer some questions about the tokenizer for which you want to add tests. The `modelname` should be cased according to the plain text casing, i.e., BERT, RoBERTa, DeBERTa.
+
+Once the command has finished, you should have a one new file inside the newly created folder named `test_tokenization_Xxx.py`. At this point the template is finished and you can move it to the sub-folder of the corresponding model in the test folder.
diff --git a/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_missing_tokenization_test/cookiecutter-template-{{cookiecutter.modelname}}/test_tokenization_{{cookiecutter.lowercase_modelname}}.py b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_missing_tokenization_test/cookiecutter-template-{{cookiecutter.modelname}}/test_tokenization_{{cookiecutter.lowercase_modelname}}.py
new file mode 100644
index 0000000000000000000000000000000000000000..6cbe8bd481ac55b00468928eca2dba87cbeac319
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_missing_tokenization_test/cookiecutter-template-{{cookiecutter.modelname}}/test_tokenization_{{cookiecutter.lowercase_modelname}}.py
@@ -0,0 +1,78 @@
+# coding=utf-8
+# Copyright 2022 {{cookiecutter.authors}}. 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.
+""" Testing suite for the {{cookiecutter.modelname}} tokenizer. """
+
+
+import unittest
+
+{% if cookiecutter.has_slow_class == "True" and cookiecutter.has_fast_class == "True" -%}
+from transformers import {{cookiecutter.camelcase_modelname}}Tokenizer, {{cookiecutter.camelcase_modelname}}TokenizerFast
+{% elif cookiecutter.has_slow_class == "True" -%}
+from transformers import {{cookiecutter.camelcase_modelname}}Tokenizer
+{% elif cookiecutter.has_fast_class == "True" -%}
+from transformers import {{cookiecutter.camelcase_modelname}}TokenizerFast
+{% endif -%}
+{% if cookiecutter.has_fast_class == "True" and cookiecutter.slow_tokenizer_use_sentencepiece == "True" -%}
+from transformers.testing_utils import require_sentencepiece, require_tokenizers
+from ...test_tokenization_common import TokenizerTesterMixin
+
+
+@require_sentencepiece
+@require_tokenizers
+{% elif cookiecutter.slow_tokenizer_use_sentencepiece == "True" -%}
+from transformers.testing_utils import require_sentencepiece
+from ...test_tokenization_common import TokenizerTesterMixin
+
+
+@require_sentencepiece
+{% elif cookiecutter.has_fast_class == "True" -%}
+from transformers.testing_utils import require_tokenizers
+from ...test_tokenization_common import TokenizerTesterMixin
+
+
+@require_tokenizers
+{% else -%}
+from ...test_tokenization_common import TokenizerTesterMixin
+
+
+{% endif -%}
+class {{cookiecutter.camelcase_modelname}}TokenizationTest(TokenizerTesterMixin, unittest.TestCase):
+ {% if cookiecutter.has_slow_class == "True" -%}
+ tokenizer_class = {{cookiecutter.camelcase_modelname}}Tokenizer
+ test_slow_tokenizer = True
+ {% else -%}
+ tokenizer_class = None
+ test_slow_tokenizer = False
+ {% endif -%}
+ {% if cookiecutter.has_fast_class == "True" -%}
+ rust_tokenizer_class = {{cookiecutter.camelcase_modelname}}TokenizerFast
+ test_rust_tokenizer = True
+ {% else -%}
+ rust_tokenizer_class = None
+ test_rust_tokenizer = False
+ {% endif -%}
+ {% if cookiecutter.slow_tokenizer_use_sentencepiece == "True" -%}
+ test_sentencepiece = True
+ {% endif -%}
+ # TODO: Check in `TokenizerTesterMixin` if other attributes need to be changed
+ def setUp(self):
+ super().setUp()
+
+ raise NotImplementedError(
+ "Here you have to implement the saving of a toy tokenizer in "
+ "`self.tmpdirname`."
+ )
+
+ # TODO: add tests with hard-coded target values
diff --git a/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_missing_tokenization_test/cookiecutter.json b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_missing_tokenization_test/cookiecutter.json
new file mode 100644
index 0000000000000000000000000000000000000000..2e53818f9bb65842172365b7a6d9a9ec982f4390
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_missing_tokenization_test/cookiecutter.json
@@ -0,0 +1,10 @@
+{
+ "modelname": "BrandNewBERT",
+ "uppercase_modelname": "BRAND_NEW_BERT",
+ "lowercase_modelname": "brand_new_bert",
+ "camelcase_modelname": "BrandNewBert",
+ "has_slow_class": ["True", "False"],
+ "has_fast_class": ["True", "False"],
+ "slow_tokenizer_use_sentencepiece": ["True", "False"],
+ "authors": "The HuggingFace Team"
+}
diff --git a/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_example_script/README.md b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_example_script/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..87aa385aec209dc07b08f2e26fe3aa6923e97d07
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_example_script/README.md
@@ -0,0 +1,38 @@
+
+
+# How to add a new example script in 🤗 Transformers
+
+This folder provide a template for adding a new example script implementing a training or inference task with the
+models in the 🤗 Transformers library. To use it, you will need to install cookiecutter:
+```bash
+pip install cookiecutter
+```
+or refer to the installation page of the [cookiecutter documentation](https://cookiecutter.readthedocs.io/).
+
+You can then run the following command inside the `examples` folder of the transformers repo:
+```bash
+cookiecutter ../templates/adding_a_new_example_script/
+```
+and answer the questions asked, which will generate a new folder where you will find a pre-filled template for your
+example following the best practices we recommend for them.
+
+Adjust the way the data is preprocessed, the model is loaded or the Trainer is instantiated then when you're happy, add
+a `README.md` in the folder (or complete the existing one if you added a script to an existing folder) telling a user
+how to run your script.
+
+Make a PR to the 🤗 Transformers repo. Don't forget to tweet about your new example with a carbon screenshot of how to
+run it and tag @huggingface!
diff --git a/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_example_script/cookiecutter.json b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_example_script/cookiecutter.json
new file mode 100644
index 0000000000000000000000000000000000000000..dd8dfdae3f2c35f3ed2ecf0a1f05fe256306842a
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_example_script/cookiecutter.json
@@ -0,0 +1,9 @@
+{
+ "example_name": "text classification",
+ "directory_name": "{{cookiecutter.example_name|lower|replace(' ', '-')}}",
+ "example_shortcut": "{{cookiecutter.directory_name}}",
+ "model_class": "AutoModel",
+ "authors": "The HuggingFace Team",
+ "can_train_from_scratch": ["True", "False"],
+ "with_trainer": ["True", "False"]
+}
\ No newline at end of file
diff --git a/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_example_script/{{cookiecutter.directory_name}}/run_{{cookiecutter.example_shortcut}}.py b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_example_script/{{cookiecutter.directory_name}}/run_{{cookiecutter.example_shortcut}}.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2b753c103e18478f3dfb0273c7b1e6341468498
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_example_script/{{cookiecutter.directory_name}}/run_{{cookiecutter.example_shortcut}}.py
@@ -0,0 +1,946 @@
+#!/usr/bin/env python
+# coding=utf-8
+# Copyright 2022 {{cookiecutter.authors}} 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.
+"""
+Fine-tuning a 🤗 Transformers model on {{cookiecutter.example_name}}.
+"""
+# You can also adapt this script on your own {{cookiecutter.example_name}} task. Pointers for this are left as comments.
+
+{%- if cookiecutter.with_trainer == "True" %}
+
+import logging
+import math
+import os
+import sys
+from dataclasses import dataclass, field
+from typing import Optional, List
+
+import datasets
+import torch
+from datasets import load_dataset
+
+import transformers
+from transformers import (
+ CONFIG_MAPPING,
+ MODEL_MAPPING,
+ AutoConfig,
+ {{cookiecutter.model_class}},
+ AutoTokenizer,
+ DataCollatorWithPadding,
+ HfArgumentParser,
+ Trainer,
+ TrainingArguments,
+ default_data_collator,
+ set_seed,
+)
+from transformers.trainer_utils import get_last_checkpoint
+from transformers.utils import send_example_telemetry
+
+
+logger = logging.getLogger(__name__)
+
+
+{%- if cookiecutter.can_train_from_scratch == "True" %}
+# You should update this to your particular problem to have better documentation of `model_type`
+MODEL_CONFIG_CLASSES = list(MODEL_MAPPING.keys())
+MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
+
+
+@dataclass
+class ModelArguments:
+ """
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
+ """
+
+ model_name_or_path: Optional[str] = field(
+ default=None,
+ metadata={
+ "help": "The model checkpoint for weights initialization. "
+ "Don't set if you want to train a model from scratch."
+ },
+ )
+ model_type: Optional[str] = field(
+ default=None,
+ metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
+ )
+ config_name: Optional[str] = field(
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
+ )
+ tokenizer_name: Optional[str] = field(
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
+ )
+ cache_dir: Optional[str] = field(
+ default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}
+ )
+ use_fast_tokenizer: bool = field(
+ default=True,
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
+ )
+{%- elif cookiecutter.can_train_from_scratch == "False" %}
+@dataclass
+class ModelArguments:
+ """
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
+ """
+
+ model_name_or_path: str = field(
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
+ )
+ config_name: Optional[str] = field(
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
+ )
+ tokenizer_name: Optional[str] = field(
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
+ )
+ cache_dir: Optional[str] = field(
+ default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}
+ )
+ use_fast_tokenizer: bool = field(
+ default=True,
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
+ )
+ model_revision: str = field(
+ default="main",
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
+ )
+ token: str = field(
+ default=None,
+ metadata={
+ "help": (
+ "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
+ "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
+ )
+ },
+ )
+ trust_remote_code: bool = field(
+ default=False,
+ metadata={
+ "help": (
+ "Whether to trust the execution of code from datasets/models defined on the Hub."
+ " 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."
+ )
+ },
+ )
+{% endif %}
+
+
+@dataclass
+class DataTrainingArguments:
+ """
+ Arguments pertaining to what data we are going to input our model for training and eval.
+ """
+
+ dataset_name: Optional[str] = field(
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
+ )
+ dataset_config_name: Optional[str] = field(
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
+ )
+ train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
+ validation_file: Optional[str] = field(
+ default=None,
+ metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
+ )
+ test_file: Optional[str] = field(
+ default=None,
+ metadata={"help": "An optional input test data file to predict the label on (a text file)."},
+ )
+ overwrite_cache: bool = field(
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
+ )
+ preprocessing_num_workers: Optional[int] = field(
+ default=None,
+ metadata={"help": "The number of processes to use for the preprocessing."},
+ )
+ max_train_samples: Optional[int] = field(
+ default=None,
+ metadata={
+ "help": "For debugging purposes or quicker training, truncate the number of training examples to this "
+ "value if set."
+ },
+ )
+ max_eval_samples: Optional[int] = field(
+ default=None,
+ metadata={
+ "help": "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
+ "value if set."
+ },
+ )
+ max_predict_samples: Optional[int] = field(
+ default=None,
+ metadata={
+ "help": "For debugging purposes or quicker training, truncate the number of prediction examples to this "
+ "value if set."
+ },
+ )
+
+ def __post_init__(self):
+ if (
+ self.dataset_name is None
+ and self.train_file is None
+ and self.validation_file is None
+ and self.test_file is None
+ ):
+ raise ValueError("Need either a dataset name or a training/validation/test file.")
+ else:
+ if self.train_file is not None:
+ extension = self.train_file.split(".")[-1]
+ assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
+ if self.validation_file is not None:
+ extension = self.validation_file.split(".")[-1]
+ assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
+ if self.test_file is not None:
+ extension = self.test_file.split(".")[-1]
+ assert extension in ["csv", "json", "txt"], "`test_file` should be a csv, a json or a txt file."
+
+
+def main():
+ # See all possible arguments in src/transformers/training_args.py
+ # or by passing the --help flag to this script.
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
+
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
+ # If we pass only one argument to the script and it's the path to a json file,
+ # let's parse it to get our arguments.
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
+ else:
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
+
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
+ send_example_telemetry("run_{{cookiecutter.example_shortcut}}", model_args, data_args)
+
+ # Detecting last checkpoint.
+ last_checkpoint = None
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
+ raise ValueError(
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
+ "Use --overwrite_output_dir to overcome."
+ )
+ elif last_checkpoint is not None:
+ logger.info(
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
+ )
+
+ # Setup logging
+ 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)
+ transformers.utils.logging.enable_default_handler()
+ transformers.utils.logging.enable_explicit_format()
+
+ # Log on each process the small summary:
+ logger.warning(
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
+ + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
+ )
+ logger.info(f"Training/evaluation parameters {training_args}")
+
+ # Set seed before initializing model.
+ set_seed(training_args.seed)
+
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
+ # (the dataset will be downloaded automatically from the datasets Hub).
+ #
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
+ # 'text' is found. You can easily tweak this behavior (see below).
+ #
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
+ # download the dataset.
+ if data_args.dataset_name is not None:
+ # Downloading and loading a dataset from the hub.
+ raw_datasets = load_dataset(
+ data_args.dataset_name,
+ data_args.dataset_config_name,
+ trust_remote_code=model_args.trust_remote_code,
+ )
+ else:
+ data_files = {}
+ if data_args.train_file is not None:
+ data_files["train"] = data_args.train_file
+ extension = data_args.train_file.split(".")[-1]
+ if data_args.validation_file is not None:
+ data_files["validation"] = data_args.validation_file
+ extension = data_args.validation_file.split(".")[-1]
+ if data_args.test_file is not None:
+ data_files["test"] = data_args.test_file
+ extension = data_args.test_file.split(".")[-1]
+ if extension == "txt":
+ extension = "text"
+ raw_datasets = load_dataset(extension, data_files=data_files)
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
+ # https://huggingface.co/docs/datasets/loading_datasets.
+
+ # Load pretrained model and tokenizer
+ #
+ # Distributed training:
+ # The .from_pretrained methods guarantee that only one local process can concurrently
+ # download model & vocab.
+{%- if cookiecutter.can_train_from_scratch == "True" %}
+ config_kwargs = {
+ "cache_dir": model_args.cache_dir,
+ "revision": model_args.model_revision,
+ "token": model_args.token,
+ "trust_remote_code": model_args.trust_remote_code,
+ }
+ if model_args.config_name:
+ config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs)
+ elif model_args.model_name_or_path:
+ config = AutoConfig.from_pretrained(model_args.model_name_or_path, **config_kwargs)
+ else:
+ config = CONFIG_MAPPING[model_args.model_type]()
+ logger.warning("You are instantiating a new config instance from scratch.")
+
+ tokenizer_kwargs = {
+ "cache_dir": model_args.cache_dir,
+ "use_fast": model_args.use_fast_tokenizer,
+ "revision": model_args.model_revision,
+ "token": model_args.token,
+ "trust_remote_code": model_args.trust_remote_code,
+ }
+ if model_args.tokenizer_name:
+ tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, **tokenizer_kwargs)
+ elif model_args.model_name_or_path:
+ tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, **tokenizer_kwargs)
+ else:
+ raise ValueError(
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script. "
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
+ )
+
+ if model_args.model_name_or_path:
+ model = {{cookiecutter.model_class}}.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=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
+ )
+ else:
+ logger.info("Training new model from scratch")
+ model = {{cookiecutter.model_class}}.from_config(config)
+
+ model.resize_token_embeddings(len(tokenizer))
+{%- elif cookiecutter.can_train_from_scratch == "False" %}
+ config = AutoConfig.from_pretrained(
+ model_args.config_name if model_args.config_name else model_args.model_name_or_path,
+ # num_labels=num_labels, Uncomment if you have a certain number of labels
+ finetuning_task=data_args.task_name,
+ cache_dir=model_args.cache_dir,
+ revision=model_args.model_revision,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
+ )
+ tokenizer = AutoTokenizer.from_pretrained(
+ model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
+ cache_dir=model_args.cache_dir,
+ use_fast=model_args.use_fast_tokenizer,
+ revision=model_args.model_revision,
+ token=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
+ )
+ model = 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=model_args.token,
+ trust_remote_code=model_args.trust_remote_code,
+ )
+{% endif %}
+
+ # Preprocessing the datasets.
+ # First we tokenize all the texts.
+ if training_args.do_train:
+ column_names = raw_datasets["train"].column_names
+ elif training_args.do_eval:
+ column_names = raw_datasets["validation"].column_names
+ elif training_args.do_predict:
+ column_names = raw_datasets["test"].column_names
+ text_column_name = "text" if "text" in column_names else column_names[0]
+
+ def tokenize_function(examples):
+ return tokenizer(examples[text_column_name], padding="max_length", truncation=True)
+
+ if training_args.do_train:
+ if "train" not in raw_datasets:
+ raise ValueError("--do_train requires a train dataset")
+ train_dataset = raw_datasets["train"]
+ if data_args.max_train_samples is not None:
+ # Select Sample from Dataset
+ train_dataset = train_dataset.select(range(data_args.max_train_samples))
+ # tokenize train dataset in batch
+ with training_args.main_process_first(desc="train dataset map tokenization"):
+ train_dataset = train_dataset.map(
+ tokenize_function,
+ batched=True,
+ num_proc=data_args.preprocessing_num_workers,
+ remove_columns=[text_column_name],
+ load_from_cache_file=not data_args.overwrite_cache,
+ )
+
+ if training_args.do_eval:
+ if "validation" not in raw_datasets:
+ raise ValueError("--do_eval requires a validation dataset")
+ eval_dataset = raw_datasets["validation"]
+ # Selecting samples from dataset
+ if data_args.max_eval_samples is not None:
+ eval_dataset = eval_dataset.select(range(data_args.max_eval_samples))
+ # tokenize validation dataset
+ with training_args.main_process_first(desc="validation dataset map tokenization"):
+ eval_dataset = eval_dataset.map(
+ tokenize_function,
+ batched=True,
+ num_proc=data_args.preprocessing_num_workers,
+ remove_columns=[text_column_name],
+ load_from_cache_file=not data_args.overwrite_cache,
+ )
+
+ if training_args.do_predict:
+ if "test" not in raw_datasets:
+ raise ValueError("--do_predict requires a test dataset")
+ predict_dataset = raw_datasets["test"]
+ # Selecting samples from dataset
+ if data_args.max_predict_samples is not None:
+ predict_dataset = predict_dataset.select(range(data_args.max_predict_samples))
+ # tokenize predict dataset
+ with training_args.main_process_first(desc="prediction dataset map tokenization"):
+ predict_dataset = predict_dataset.map(
+ tokenize_function,
+ batched=True,
+ num_proc=data_args.preprocessing_num_workers,
+ remove_columns=[text_column_name],
+ load_from_cache_file=not data_args.overwrite_cache,
+ )
+
+ # Data collator
+ data_collator=default_data_collator if not training_args.fp16 else DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8)
+
+ # Initialize our Trainer
+ trainer = Trainer(
+ model=model,
+ args=training_args,
+ train_dataset=train_dataset if training_args.do_train else None,
+ eval_dataset=eval_dataset if training_args.do_eval else None,
+ processing_class=tokenizer,
+ data_collator=data_collator,
+ )
+
+ # Training
+ if training_args.do_train:
+{%- if cookiecutter.can_train_from_scratch == "False" %}
+ if last_checkpoint is not None:
+ checkpoint = last_checkpoint
+ elif os.path.isdir(model_args.model_name_or_path):
+ checkpoint = model_args.model_name_or_path
+ else:
+ checkpoint = None
+{%- elif cookiecutter.can_train_from_scratch == "True" %}
+ if last_checkpoint is not None:
+ checkpoint = last_checkpoint
+ elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path):
+ checkpoint = model_args.model_name_or_path
+ else:
+ checkpoint = None
+{% endif %}
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
+ trainer.save_model() # Saves the tokenizer too for easy upload
+
+ metrics = train_result.metrics
+ max_train_samples = (
+ data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)
+ )
+ metrics["train_samples"] = min(max_train_samples, len(train_dataset))
+
+ trainer.log_metrics("train", metrics)
+ trainer.save_metrics("train", metrics)
+ trainer.save_state()
+
+ # Evaluation
+ if training_args.do_eval:
+ logger.info("*** Evaluate ***")
+
+ metrics = trainer.evaluate()
+
+ max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset)
+ metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset))
+
+ trainer.log_metrics("eval", metrics)
+ trainer.save_metrics("eval", metrics)
+
+ # Prediction
+ if training_args.do_predict:
+ logger.info("*** Predict ***")
+ predictions, labels, metrics = trainer.predict(predict_dataset)
+
+ max_predict_samples = data_args.max_predict_samples if data_args.max_predict_samples is not None else len(predict_dataset)
+ metrics["predict_samples"] = min(max_predict_samples, len(predict_dataset))
+
+ trainer.log_metrics("predict", metrics)
+ trainer.save_metrics("predict", metrics)
+
+ # write custom code for saving predictions according to task
+
+def _mp_fn(index):
+ # For xla_spawn (TPUs)
+ main()
+
+
+if __name__ == "__main__":
+ main()
+
+{%- elif cookiecutter.with_trainer == "False" %}
+
+import argparse
+import logging
+import math
+import os
+import random
+
+import datasets
+from datasets import load_dataset, load_metric
+from torch.utils.data import DataLoader
+from tqdm.auto import tqdm
+
+import transformers
+from accelerate import Accelerator
+from transformers import (
+ CONFIG_MAPPING,
+ MODEL_MAPPING,
+ AdamW,
+ AutoConfig,
+ {{cookiecutter.model_class}},
+ AutoTokenizer,
+ DataCollatorWithPadding,
+ PretrainedConfig,
+ SchedulerType,
+ default_data_collator,
+ get_scheduler,
+ set_seed,
+)
+from transformers.utils import send_example_telemetry
+
+
+logger = logging.getLogger(__name__)
+
+
+{%- if cookiecutter.can_train_from_scratch == "True" %}
+# You should update this to your particular problem to have better documentation of `model_type`
+MODEL_CONFIG_CLASSES = list(MODEL_MAPPING.keys())
+MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
+{% endif %}
+
+def parse_args():
+ parser = argparse.ArgumentParser(description="Finetune a transformers model on a text classification task")
+ parser.add_argument(
+ "--dataset_name",
+ type=str,
+ default=None,
+ help="The name of the dataset to use (via the datasets library).",
+ )
+ parser.add_argument(
+ "--dataset_config_name",
+ type=str,
+ default=None,
+ help= "The configuration name of the dataset to use (via the datasets library).",
+ )
+ parser.add_argument(
+ "--trust_remote_code",
+ action="store_true",
+ help=(
+ "Whether to trust the execution of code from datasets/models defined on the Hub."
+ " 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."
+ ),
+ )
+ parser.add_argument(
+ "--train_file", type=str, default=None, help="A csv or a json file containing the training data."
+ )
+ parser.add_argument(
+ "--validation_file", type=str, default=None, help="A csv or a json file containing the validation data."
+ )
+ parser.add_argument(
+ "--max_length",
+ type=int,
+ default=128,
+ help=(
+ "The maximum total input sequence length after tokenization. Sequences longer than this will be truncated,"
+ " sequences shorter will be padded if `--pad_to_max_length` is passed."
+ ),
+ )
+ parser.add_argument(
+ "--pad_to_max_length",
+ action="store_true",
+ help="If passed, pad all samples to `max_length`. Otherwise, dynamic padding is used.",
+ )
+ parser.add_argument(
+ "--model_name_or_path",
+ type=str,
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
+ required=True,
+ )
+ parser.add_argument(
+ "--config_name",
+ type=str,
+ default=None,
+ help="Pretrained config name or path if not the same as model_name",
+ )
+ parser.add_argument(
+ "--tokenizer_name",
+ type=str,
+ default=None,
+ help="Pretrained tokenizer name or path if not the same as model_name",
+ )
+ parser.add_argument(
+ "--use_slow_tokenizer",
+ action="store_true",
+ help="If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).",
+ )
+ parser.add_argument(
+ "--per_device_train_batch_size",
+ type=int,
+ default=8,
+ help="Batch size (per device) for the training dataloader.",
+ )
+ parser.add_argument(
+ "--per_device_eval_batch_size",
+ type=int,
+ default=8,
+ help="Batch size (per device) for the evaluation dataloader.",
+ )
+ parser.add_argument(
+ "--learning_rate",
+ type=float,
+ default=5e-5,
+ help="Initial learning rate (after the potential warmup period) to use.",
+ )
+ parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.")
+ parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.")
+ parser.add_argument(
+ "--max_train_steps",
+ type=int,
+ default=None,
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
+ )
+ parser.add_argument(
+ "--gradient_accumulation_steps",
+ type=int,
+ default=1,
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
+ )
+ parser.add_argument(
+ "--lr_scheduler_type",
+ type=SchedulerType,
+ default="linear",
+ help="The scheduler type to use.",
+ choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"],
+ )
+ parser.add_argument(
+ "--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler."
+ )
+ parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.")
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
+{%- if cookiecutter.can_train_from_scratch == "True" %}
+ parser.add_argument(
+ "--model_type",
+ type=str,
+ default=None,
+ help="Model type to use if training from scratch.",
+ choices=MODEL_TYPES,
+ )
+{% endif %}
+ args = parser.parse_args()
+
+ # Sanity checks
+ if args.task_name is None and args.train_file is None and args.validation_file is None:
+ raise ValueError("Need either a task name or a training/validation file.")
+ else:
+ if args.train_file is not None:
+ extension = args.train_file.split(".")[-1]
+ assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
+ if args.validation_file is not None:
+ extension = args.validation_file.split(".")[-1]
+ assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."
+
+ if args.output_dir is not None:
+ os.makedirs(args.output_dir, exist_ok=True)
+
+ return args
+
+
+def main():
+ args = parse_args()
+
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
+ send_example_telemetry("run_{{cookiecutter.example_shortcut}", args)
+
+ # Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
+ accelerator = Accelerator()
+ # Make one log on every process with the configuration for debugging.
+ logging.basicConfig(
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
+ datefmt="%m/%d/%Y %H:%M:%S",
+ level=logging.INFO,
+ )
+ logger.info(accelerator.state)
+
+ # Setup logging, we only want one process per machine to log things on the screen.
+ # accelerator.is_local_main_process is only True for one process per machine.
+ logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR)
+ if accelerator.is_local_main_process:
+ datasets.utils.logging.set_verbosity_warning()
+ transformers.utils.logging.set_verbosity_info()
+ else:
+ datasets.utils.logging.set_verbosity_error()
+ transformers.utils.logging.set_verbosity_error()
+
+ # If passed along, set the training seed now.
+ if args.seed is not None:
+ set_seed(args.seed)
+
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
+ # (the dataset will be downloaded automatically from the datasets Hub).
+ #
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
+ # 'text' is found. You can easily tweak this behavior (see below).
+ #
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
+ # download the dataset.
+ if args.dataset_name is not None:
+ # Downloading and loading a dataset from the hub.
+ raw_datasets = load_dataset(
+ args.dataset_name, args.dataset_config_name, trust_remote_code=args.trust_remote_code
+ )
+ else:
+ data_files = {}
+ if args.train_file is not None:
+ data_files["train"] = args.train_file
+ extension = args.train_file.split(".")[-1]
+ if args.validation_file is not None:
+ data_files["validation"] = args.validation_file
+ extension = args.validation_file.split(".")[-1]
+ raw_datasets = load_dataset(extension, data_files=data_files)
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
+ # https://huggingface.co/docs/datasets/loading_datasets.
+
+ # Load pretrained model and tokenizer
+ #
+ # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
+ # download model & vocab.
+{%- if cookiecutter.can_train_from_scratch == "True" %}
+ if model_args.config_name:
+ config = AutoConfig.from_pretrained(args.model_name_or_path)
+ elif model_args.model_name_or_path:
+ config = AutoConfig.from_pretrained(args.model_name_or_path)
+ else:
+ config = CONFIG_MAPPING[args.model_type]()
+ logger.warning("You are instantiating a new config instance from scratch.")
+
+ if model_args.tokenizer_name:
+ tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, use_fast=not args.use_slow_tokenizer)
+ elif model_args.model_name_or_path:
+ tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, use_fast=not args.use_slow_tokenizer)
+ else:
+ raise ValueError(
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script. "
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
+ )
+
+ if model_args.model_name_or_path:
+ model = {{cookiecutter.model_class}}.from_pretrained(
+ model_args.model_name_or_path,
+ from_tf=bool(".ckpt" in model_args.model_name_or_path),
+ config=config,
+ )
+ else:
+ logger.info("Training new model from scratch")
+ model = {{cookiecutter.model_class}}.from_config(config)
+
+ model.resize_token_embeddings(len(tokenizer))
+{%- elif cookiecutter.can_train_from_scratch == "False" %}
+ config = AutoConfig.from_pretrained(
+ args.config_name if model_args.config_name else args.model_name_or_path,
+ # num_labels=num_labels, Uncomment if you have a certain number of labels
+ finetuning_task=data_args.task_name,
+ )
+ tokenizer = AutoTokenizer.from_pretrained(
+ args.tokenizer_name if model_args.tokenizer_name else args.model_name_or_path,
+ use_fast=not args.use_slow_tokenizer,
+ )
+ model = AutoModelForSequenceClassification.from_pretrained(
+ model_args.model_name_or_path,
+ from_tf=bool(".ckpt" in model_args.model_name_or_path),
+ config=config,
+ )
+{% endif %}
+
+ # Preprocessing the datasets.
+ # First we tokenize all the texts.
+ column_names = raw_datasets["train"].column_names
+ text_column_name = "text" if "text" in column_names else column_names[0]
+
+ padding = "max_length" if args.pad_to_max_length else False
+ def tokenize_function(examples):
+ result = tokenizer(examples[text_column_name], padding=padding, max_length=args.max_length, truncation=True)
+ if "label" in examples:
+ result["labels"] = examples["label"]
+ return result
+
+ processed_datasets = raw_datasets.map(
+ preprocess_function, batched=True, remove_columns=raw_datasets["train"].column_names
+ )
+
+ train_dataset = processed_datasets["train"]
+ eval_dataset = processed_datasets["validation"]
+
+ # Log a few random samples from the training set:
+ for index in random.sample(range(len(train_dataset)), 3):
+ logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
+
+ # DataLoaders creation:
+ if args.pad_to_max_length:
+ # If padding was already done ot max length, we use the default data collator that will just convert everything
+ # to tensors.
+ data_collator = default_data_collator
+ else:
+ # Otherwise, `DataCollatorWithPadding` will apply dynamic padding for us (by padding to the maximum length of
+ # the samples passed). When using mixed precision, we add `pad_to_multiple_of=8` to pad all tensors to multiple
+ # of 8s, which will enable the use of Tensor Cores on NVIDIA hardware with compute capability >= 7.5 (Volta).
+ # For fp8, we pad to multiple of 16.
+ if accelerator.mixed_precision == "fp8":
+ pad_to_multiple_of = 16
+ elif accelerator.mixed_precision != "no":
+ pad_to_multiple_of = 8
+ else:
+ pad_to_multiple_of = None
+ data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=pad_to_multiple_of)
+
+ train_dataloader = DataLoader(
+ train_dataset, shuffle=True, collate_fn=data_collator, batch_size=args.per_device_train_batch_size
+ )
+ eval_dataloader = DataLoader(eval_dataset, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size)
+
+ # Optimizer
+ # Split weights in two groups, one with weight decay and the other not.
+ no_decay = ["bias", "LayerNorm.weight"]
+ optimizer_grouped_parameters = [
+ {
+ "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
+ "weight_decay": args.weight_decay,
+ },
+ {
+ "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)],
+ "weight_decay": 0.0,
+ },
+ ]
+ optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate)
+
+ # Prepare everything with our `accelerator`.
+ model, optimizer, train_dataloader, eval_dataloader = accelerator.prepare(
+ model, optimizer, train_dataloader, eval_dataloader
+ )
+
+ # Note -> the training dataloader needs to be prepared before we grab his length below (cause its length will be
+ # shorter in multiprocess)
+
+ # Scheduler and math around the number of training steps.
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
+ if args.max_train_steps is None:
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
+ else:
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
+
+ lr_scheduler = get_scheduler(
+ name=args.lr_scheduler_type,
+ optimizer=optimizer,
+ num_warmup_steps=args.num_warmup_steps,
+ num_training_steps=args.max_train_steps,
+ )
+
+ # TODO Get the proper metric function
+ # metric = load_metric(xxx)
+
+ # Train!
+ total_batch_size = args.per_device_train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
+
+ logger.info("***** Running training *****")
+ logger.info(f" Num examples = {len(train_dataset)}")
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
+ logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}")
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
+ # Only show the progress bar once on each machine.
+ progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)
+ completed_steps = 0
+
+ for epoch in range(args.num_train_epochs):
+ model.train()
+ for step, batch in enumerate(train_dataloader):
+ outputs = model(**batch)
+ loss = outputs.loss
+ loss = loss / args.gradient_accumulation_steps
+ accelerator.backward(loss)
+ if step % args.gradient_accumulation_steps == 0 or step == len(train_dataloader) - 1:
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+ progress_bar.update(1)
+ completed_steps += 1
+
+ if completed_steps >= args.max_train_steps:
+ break
+
+ model.eval()
+ for step, batch in enumerate(eval_dataloader):
+ with torch.no_grad():
+ outputs = model(**batch)
+ predictions = outputs.logits.argmax(dim=-1)
+ metric.add_batch(
+ predictions=accelerator.gather(predictions),
+ references=accelerator.gather(batch["labels"]),
+ )
+
+ eval_metric = metric.compute()
+ logger.info(f"epoch {epoch}: {eval_metric}")
+
+ if args.output_dir is not None:
+ accelerator.wait_for_everyone()
+ unwrapped_model = accelerator.unwrap_model(model)
+ unwrapped_model.save_pretrained(args.output_dir, save_function=accelerator.save)
+
+
+if __name__ == "__main__":
+ main()
+
+{% endif %}
diff --git a/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_model/ADD_NEW_MODEL_PROPOSAL_TEMPLATE.md b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_model/ADD_NEW_MODEL_PROPOSAL_TEMPLATE.md
new file mode 100644
index 0000000000000000000000000000000000000000..dc7143465d4e52c374c663b5d1394248cf938e0c
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_model/ADD_NEW_MODEL_PROPOSAL_TEMPLATE.md
@@ -0,0 +1,1141 @@
+**TEMPLATE**
+=====================================
+
+*search & replace the following keywords, e.g.:*
+`:%s/\[name of model\]/brand_new_bert/g`
+
+-[lowercase name of model] # e.g. brand_new_bert
+
+-[camelcase name of model] # e.g. BrandNewBert
+
+-[name of mentor] # e.g. [Peter](https://github.com/peter)
+
+-[link to original repo]
+
+-[start date]
+
+-[end date]
+
+
+
+How to add [camelcase name of model] to 🤗 Transformers?
+=====================================
+
+Mentor: [name of mentor]
+
+Begin: [start date]
+
+Estimated End: [end date]
+
+Adding a new model is often difficult and requires an in-depth knowledge
+of the 🤗 Transformers library and ideally also of the model's original
+repository. At Hugging Face, we are trying to empower the community more
+and more to add models independently.
+
+The following sections explain in detail how to add [camelcase name of model]
+to Transformers. You will work closely with [name of mentor] to
+integrate [camelcase name of model] into Transformers. By doing so, you will both gain a
+theoretical and deep practical understanding of [camelcase name of model].
+But more importantly, you will have made a major
+open-source contribution to Transformers. Along the way, you will:
+
+- get insights into open-source best practices
+- understand the design principles of one of the most popular NLP
+ libraries
+- learn how to do efficiently test large NLP models
+- learn how to integrate Python utilities like `black`, `ruff`,
+ `make fix-copies` into a library to always ensure clean and readable
+ code
+
+To start, let's try to get a general overview of the Transformers
+library.
+
+General overview of 🤗 Transformers
+----------------------------------
+
+First, you should get a general overview of 🤗 Transformers. Transformers
+is a very opinionated library, so there is a chance that
+you don't agree with some of the library's philosophies or design
+choices. From our experience, however, we found that the fundamental
+design choices and philosophies of the library are crucial to
+efficiently scale Transformers while keeping maintenance costs at a
+reasonable level.
+
+A good first starting point to better understand the library is to read
+the [documentation of our philosophy](https://huggingface.co/transformers/philosophy.html).
+As a result of our way of working, there are some choices that we try to apply to all models:
+
+- Composition is generally favored over abstraction
+- Duplicating code is not always bad if it strongly improves the
+ readability or accessibility of a model
+- Model files are as self-contained as possible so that when you read
+ the code of a specific model, you ideally only have to look into the
+ respective `modeling_....py` file.
+
+In our opinion, the library's code is not just a means to provide a
+product, *e.g.*, the ability to use BERT for inference, but also as the
+very product that we want to improve. Hence, when adding a model, the
+user is not only the person that will use your model, but also everybody
+that will read, try to understand, and possibly tweak your code.
+
+With this in mind, let's go a bit deeper into the general library
+design.
+
+### Overview of models
+
+To successfully add a model, it is important to understand the
+interaction between your model and its config,
+`PreTrainedModel`, and `PretrainedConfig`. For
+exemplary purposes, we will call the PyTorch model to be added to 🤗 Transformers
+`BrandNewBert`.
+
+Let's take a look:
+
+
+
+As you can see, we do make use of inheritance in 🤗 Transformers, but we
+keep the level of abstraction to an absolute minimum. There are never
+more than two levels of abstraction for any model in the library.
+`BrandNewBertModel` inherits from
+`BrandNewBertPreTrainedModel` which in
+turn inherits from `PreTrainedModel` and that's it.
+As a general rule, we want to make sure
+that a new model only depends on `PreTrainedModel`. The
+important functionalities that are automatically provided to every new
+model are
+`PreTrainedModel.from_pretrained` and `PreTrainedModel.save_pretrained`, which are
+used for serialization and deserialization. All
+of the other important functionalities, such as
+`BrandNewBertModel.forward` should be
+completely defined in the new `modeling_brand_new_bert.py` module. Next,
+we want to make sure that a model with a specific head layer, such as
+`BrandNewBertForMaskedLM` does not inherit
+from `BrandNewBertModel`, but rather uses
+`BrandNewBertModel` as a component that
+can be called in its forward pass to keep the level of abstraction low.
+Every new model requires a configuration class, called
+`BrandNewBertConfig`. This configuration
+is always stored as an attribute in
+`PreTrainedModel`, and
+thus can be accessed via the `config` attribute for all classes
+inheriting from `BrandNewBertPreTrainedModel`
+
+```python
+# assuming that `brand_new_bert` belongs to the organization `brandy`
+model = BrandNewBertModel.from_pretrained("brandy/brand_new_bert")
+model.config # model has access to its config
+```
+
+Similar to the model, the configuration inherits basic serialization and
+deserialization functionalities from
+`PretrainedConfig`. Note
+that the configuration and the model are always serialized into two
+different formats - the model to a `pytorch_model.bin` file
+and the configuration to a `config.json` file. Calling
+`PreTrainedModel.save_pretrained` will automatically call
+`PretrainedConfig.save_pretrained`, so that both model and configuration are saved.
+
+### Overview of tokenizers
+
+Not quite ready yet :-( This section will be added soon!
+
+Step-by-step recipe to add a model to 🤗 Transformers
+----------------------------------------------------
+
+Everyone has different preferences of how to port a model so it can be
+very helpful for you to take a look at summaries of how other
+contributors ported models to Hugging Face. Here is a list of community
+blog posts on how to port a model:
+
+1. [Porting GPT2
+ Model](https://medium.com/huggingface/from-tensorflow-to-pytorch-265f40ef2a28)
+ by [Thomas](https://huggingface.co/thomwolf)
+2. [Porting WMT19 MT Model](https://huggingface.co/blog/porting-fsmt)
+ by [Stas](https://huggingface.co/stas)
+
+From experience, we can tell you that the most important things to keep
+in mind when adding a model are:
+
+- Don't reinvent the wheel! Most parts of the code you will add for
+ the new 🤗 Transformers model already exist somewhere in 🤗
+ Transformers. Take some time to find similar, already existing
+ models and tokenizers you can copy from.
+ [grep](https://www.gnu.org/software/grep/) and
+ [rg](https://github.com/BurntSushi/ripgrep) are your friends. Note
+ that it might very well happen that your model's tokenizer is based
+ on one model implementation, and your model's modeling code on
+ another one. *E.g.*, FSMT's modeling code is based on BART, while
+ FSMT's tokenizer code is based on XLM.
+- It's more of an engineering challenge than a scientific challenge.
+ You should spend more time on creating an efficient debugging
+ environment than trying to understand all theoretical aspects of the
+ model in the paper.
+- Ask for help when you're stuck! Models are the core component of 🤗
+ Transformers so we, at Hugging Face, are more than happy to help
+ you at every step to add your model. Don't hesitate to ask if you
+ notice you are not making progress.
+
+In the following, we try to give you a general recipe that we found most
+useful when porting a model to 🤗 Transformers.
+
+The following list is a summary of everything that has to be done to add
+a model and can be used by you as a To-Do List:
+
+1. [ ] (Optional) Understood theoretical aspects
+
+2. [ ] Prepared transformers dev environment
+
+3. [ ] Set up debugging environment of the original repository
+
+4. [ ] Created script that successfully runs forward pass using
+ original repository and checkpoint
+
+5. [ ] Successfully opened a PR and added the model skeleton to Transformers
+
+6. [ ] Successfully converted original checkpoint to Transformers
+ checkpoint
+
+7. [ ] Successfully ran forward pass in Transformers that gives
+ identical output to original checkpoint
+
+8. [ ] Finished model tests in Transformers
+
+9. [ ] Successfully added Tokenizer in Transformers
+
+10. [ ] Run end-to-end integration tests
+
+11. [ ] Finished docs
+
+12. [ ] Uploaded model weights to the hub
+
+13. [ ] Submitted the pull request for review
+
+14. [ ] (Optional) Added a demo notebook
+
+To begin with, we usually recommend to start by getting a good
+theoretical understanding of `[camelcase name of model]`. However, if you prefer to
+understand the theoretical aspects of the model *on-the-job*, then it is
+totally fine to directly dive into the `[camelcase name of model]`'s code-base. This
+option might suit you better, if your engineering skills are better than
+your theoretical skill, if you have trouble understanding
+`[camelcase name of model]`'s paper, or if you just enjoy programming much more than
+reading scientific papers.
+
+### 1. (Optional) Theoretical aspects of [camelcase name of model]
+
+You should take some time to read *[camelcase name of model]'s* paper, if such
+descriptive work exists. There might be large sections of the paper that
+are difficult to understand. If this is the case, this is fine - don't
+worry! The goal is not to get a deep theoretical understanding of the
+paper, but to extract the necessary information required to effectively
+re-implement the model in 🤗 Transformers. That being said, you don't
+have to spend too much time on the theoretical aspects, but rather focus
+on the practical ones, namely:
+
+- What type of model is *[camelcase name of model]*? BERT-like encoder-only
+ model? GPT2-like decoder-only model? BART-like encoder-decoder
+ model? Look at the `model_summary` if
+ you're not familiar with the differences between those.
+- What are the applications of *[camelcase name of model]*? Text
+ classification? Text generation? Seq2Seq tasks, *e.g.,*
+ summarization?
+- What is the novel feature of the model making it different from
+ BERT/GPT-2/BART?
+- Which of the already existing [🤗 Transformers
+ models](https://huggingface.co/transformers/#contents) is most
+ similar to *[camelcase name of model]*?
+- What type of tokenizer is used? A sentencepiece tokenizer? Word
+ piece tokenizer? Is it the same tokenizer as used for BERT or BART?
+
+After you feel like you have gotten a good overview of the architecture
+of the model, you might want to write to [name of mentor] with any
+questions you might have. This might include questions regarding the
+model's architecture, its attention layer, etc. We will be more than
+happy to help you.
+
+
+#### Additional resources
+
+ Before diving into the code, here are some additional resources that might be worth taking a look at:
+
+ - [link 1]
+ - [link 2]
+ - [link 3]
+ - ...
+
+#### Make sure you've understood the fundamental aspects of [camelcase name of model]
+
+Alright, now you should be ready to take a closer look into the actual code of [camelcase name of model].
+You should have understood the following aspects of [camelcase name of model] by now:
+
+- [characteristic 1 of [camelcase name of model]]
+- [characteristic 2 of [camelcase name of model]]
+- ...
+
+If any of the mentioned aspects above are **not** clear to you, now is a great time to talk to [name of mentor].
+
+### 2. Next prepare your environment
+
+1. Fork the [repository](https://github.com/huggingface/transformers)
+ by clicking on the 'Fork' button on the repository's page. This
+ creates a copy of the code under your GitHub user account.
+
+2. Clone your `transformers` fork to your local disk, and add the base
+ repository as a remote:
+
+ ```bash
+ git clone https://github.com/[your Github handle]/transformers.git
+ cd transformers
+ git remote add upstream https://github.com/huggingface/transformers.git
+ ```
+
+3. Set up a development environment, for instance by running the
+ following command:
+
+ ```bash
+ python -m venv .env
+ source .env/bin/activate
+ pip install -e ".[dev]"
+ ```
+
+and return to the parent directory
+
+```bash
+cd ..
+```
+
+4. We recommend adding the PyTorch version of *[camelcase name of model]* to
+ Transformers. To install PyTorch, please follow the instructions [here](https://pytorch.org/get-started/locally/).
+
+**Note:** You don't need to have CUDA installed. Making the new model
+work on CPU is sufficient.
+
+5. To port *[camelcase name of model]*, you will also need access to its
+ original repository:
+
+```bash
+git clone [link to original repo].git
+cd [lowercase name of model]
+pip install -e .
+```
+
+Now you have set up a development environment to port *[camelcase name of model]*
+to 🤗 Transformers.
+
+### Run a pretrained checkpoint using the original repository
+
+**3. Set up debugging environment**
+
+At first, you will work on the original *[camelcase name of model]* repository.
+Often, the original implementation is very "researchy". Meaning that
+documentation might be lacking and the code can be difficult to
+understand. But this should be exactly your motivation to reimplement
+*[camelcase name of model]*. At Hugging Face, one of our main goals is to *make
+people stand on the shoulders of giants* which translates here very well
+into taking a working model and rewriting it to make it as **accessible,
+user-friendly, and beautiful** as possible. This is the number-one
+motivation to re-implement models into 🤗 Transformers - trying to make
+complex new NLP technology accessible to **everybody**.
+
+You should start thereby by diving into the [original repository]([link to original repo]).
+
+Successfully running the official pretrained model in the original
+repository is often **the most difficult** step. From our experience, it
+is very important to spend some time getting familiar with the original
+code-base. You need to figure out the following:
+
+- Where to find the pretrained weights?
+- How to load the pretrained weights into the corresponding model?
+- How to run the tokenizer independently from the model?
+- Trace one forward pass so that you know which classes and functions
+ are required for a simple forward pass. Usually, you only have to
+ reimplement those functions.
+- Be able to locate the important components of the model: Where is
+ the model's class? Are there model sub-classes, *e.g.*,
+ EncoderModel, DecoderModel? Where is the self-attention layer? Are
+ there multiple different attention layers, *e.g.*, *self-attention*,
+ *cross-attention*...?
+- How can you debug the model in the original environment of the repo?
+ Do you have to add `print` statements, can you work with
+ an interactive debugger like [ipdb](https://pypi.org/project/ipdb/), or should you use
+ an efficient IDE to debug the model, like PyCharm?
+
+It is very important that before you start the porting process, that you
+can **efficiently** debug code in the original repository! Also,
+remember that you are working with an open-source library, so do not
+hesitate to open an issue, or even a pull request in the original
+repository. The maintainers of this repository are most likely very
+happy about someone looking into their code!
+
+At this point, it is really up to you which debugging environment and
+strategy you prefer to use to debug the original model. We strongly
+advise against setting up a costly GPU environment, but simply work on a
+CPU both when starting to dive into the original repository and also
+when starting to write the 🤗 Transformers implementation of the model.
+Only at the very end, when the model has already been successfully
+ported to 🤗 Transformers, one should verify that the model also works as
+expected on GPU.
+
+In general, there are two possible debugging environments for running
+the original model
+
+- [Jupyter notebooks](https://jupyter.org/) / [google colab](https://colab.research.google.com/notebooks/intro.ipynb)
+- Local python scripts.
+
+Jupyter notebooks have the advantage that they allow for cell-by-cell
+execution which can be helpful to better split logical components from
+one another and to have faster debugging cycles as intermediate results
+can be stored. Also, notebooks are often easier to share with other
+contributors, which might be very helpful if you want to ask the Hugging
+Face team for help. If you are familiar with Jupyter notebooks, we
+strongly recommend you to work with them.
+
+The obvious disadvantage of Jupyter notebooks is that if you are not
+used to working with them you will have to spend some time adjusting to
+the new programming environment and that you might not be able to use
+your known debugging tools anymore, like `ipdb`.
+
+**4. Successfully run forward pass**
+
+For each code-base, a good first step is always to load a **small**
+pretrained checkpoint and to be able to reproduce a single forward pass
+using a dummy integer vector of input IDs as an input. Such a script
+could look like this (in pseudocode):
+
+```python
+model = [camelcase name of model]Model.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)
+```
+
+Next, regarding the debugging strategy, there are generally a few from
+which to choose from:
+
+- Decompose the original model into many small testable components and
+ run a forward pass on each of those for verification
+- Decompose the original model only into the original *tokenizer* and
+ the original *model*, run a forward pass on those, and use
+ intermediate print statements or breakpoints for verification
+
+Again, it is up to you which strategy to choose. Often, one or the other
+is advantageous depending on the original code base.
+
+If the original code-base allows you to decompose the model into smaller
+sub-components, *e.g.*, if the original code-base can easily be run in
+eager mode, it is usually worth the effort to do so. There are some
+important advantages to taking the more difficult road in the beginning:
+
+- at a later stage when comparing the original model to the Hugging
+ Face implementation, you can verify automatically for each component
+ individually that the corresponding component of the 🤗 Transformers
+ implementation matches instead of relying on visual comparison via
+ print statements
+- it can give you some rope to decompose the big problem of porting a
+ model into smaller problems of just porting individual components
+ and thus structure your work better
+- separating the model into logical meaningful components will help
+ you to get a better overview of the model's design and thus to
+ better understand the model
+- at a later stage those component-by-component tests help you to
+ ensure that no regression occurs as you continue changing your code
+
+[Lysandre's](https://gist.github.com/LysandreJik/db4c948f6b4483960de5cbac598ad4ed)
+integration checks for ELECTRA gives a nice example of how this can be
+done.
+
+However, if the original code-base is very complex or only allows
+intermediate components to be run in a compiled mode, it might be too
+time-consuming or even impossible to separate the model into smaller
+testable sub-components. A good example is [T5's
+MeshTensorFlow](https://github.com/tensorflow/mesh/tree/master/mesh_tensorflow)
+library which is very complex and does not offer a simple way to
+decompose the model into its sub-components. For such libraries, one
+often relies on verifying print statements.
+
+No matter which strategy you choose, the recommended procedure is often
+the same in that you should start to debug the starting layers first and
+the ending layers last.
+
+It is recommended that you retrieve the output, either by print
+statements or sub-component functions, of the following layers in the
+following order:
+
+1. Retrieve the input IDs passed to the model
+2. Retrieve the word embeddings
+3. Retrieve the input of the first Transformer layer
+4. Retrieve the output of the first Transformer layer
+5. Retrieve the output of the following n - 1 Transformer layers
+6. Retrieve the output of the whole [camelcase name of model] Model
+
+Input IDs should thereby consists of an array of integers, *e.g.*,
+`input_ids = [0, 4, 4, 3, 2, 4, 1, 7, 19]`
+
+The outputs of the following layers often consist of multi-dimensional
+float arrays and can look like this:
+
+```bash
+[[
+ [-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]]],
+```
+
+We expect that every model added to 🤗 Transformers passes a couple of
+integration tests, meaning that the original model and the reimplemented
+version in 🤗 Transformers have to give the exact same output up to a
+precision of 0.001! Since it is normal that the exact same model written
+in different libraries can give a slightly different output depending on
+the library framework, we accept an error tolerance of 1e-3 (0.001). It
+is not enough if the model gives nearly the same output, they have to be
+the almost identical. Therefore, you will certainly compare the
+intermediate outputs of the 🤗 Transformers version multiple times
+against the intermediate outputs of the original implementation of
+*[camelcase name of model]* in which case an **efficient** debugging environment
+of the original repository is absolutely important. Here is some advice
+to make your debugging environment as efficient as possible.
+
+- Find the best way of debugging intermediate results. Is the original
+ repository written in PyTorch? Then you should probably take the
+ time to write a longer script that decomposes the original model
+ into smaller sub-components to retrieve intermediate values. Is the
+ original repository written in Tensorflow 1? Then you might have to
+ rely on TensorFlow print operations like
+ [tf.print](https://www.tensorflow.org/api_docs/python/tf/print) to
+ output intermediate values. Is the original repository written in
+ Jax? Then make sure that the model is **not jitted** when running
+ the forward pass, *e.g.*, check-out [this
+ link](https://github.com/google/jax/issues/196).
+- Use the smallest pretrained checkpoint you can find. The smaller the
+ checkpoint, the faster your debug cycle becomes. It is not efficient
+ if your pretrained model is so big that your forward pass takes more
+ than 10 seconds. In case only very large checkpoints are available,
+ it might make more sense to create a dummy model in the new
+ environment with randomly initialized weights and save those weights
+ for comparison with the 🤗 Transformers version of your model
+- Make sure you are using the easiest way of calling a forward pass in
+ the original repository. Ideally, you want to find the function in
+ the original repository that **only** calls a single forward pass,
+ *i.e.* that is often called `predict`, `evaluate`, `forward` or
+ `__call__`. You don't want to debug a function that calls `forward`
+ multiple times, *e.g.*, to generate text, like
+ `autoregressive_sample`, `generate`.
+- Try to separate the tokenization from the model's
+ forward pass. If the original repository shows
+ examples where you have to input a string, then try to find out
+ where in the forward call the string input is changed to input ids
+ and start from this point. This might mean that you have to possibly
+ write a small script yourself or change the original code so that
+ you can directly input the ids instead of an input string.
+- Make sure that the model in your debugging setup is **not** in
+ training mode, which often causes the model to yield random outputs
+ due to multiple dropout layers in the model. Make sure that the
+ forward pass in your debugging environment is **deterministic** so
+ that the dropout layers are not used. Or use
+ `transformers.utils.set_seed` if the old and new
+ implementations are in the same framework.
+
+#### More details on how to create a debugging environment for [camelcase name of model]
+
+[TODO FILL: Here the mentor should add very specific information on what the student should do]
+[to set up an efficient environment for the special requirements of this model]
+
+### Port [camelcase name of model] to 🤗 Transformers
+
+Next, you can finally start adding new code to 🤗 Transformers. Go into
+the clone of your 🤗 Transformers' fork:
+
+ cd transformers
+
+In the special case that you are adding a model whose architecture
+exactly matches the model architecture of an existing model you only
+have to add a conversion script as described in [this
+section](#write-a-conversion-script). In this case, you can just re-use
+the whole model architecture of the already existing model.
+
+Otherwise, let's start generating a new model with the amazing
+Cookiecutter!
+
+**Use the Cookiecutter to automatically generate the model's code**
+
+To begin with head over to the [🤗 Transformers
+templates](https://github.com/huggingface/transformers/tree/main/templates/adding_a_new_model)
+to make use of our `cookiecutter` implementation to automatically
+generate all the relevant files for your model. Again, we recommend only
+adding the PyTorch version of the model at first. Make sure you follow
+the instructions of the `README.md` on the [🤗 Transformers
+templates](https://github.com/huggingface/transformers/tree/main/templates/adding_a_new_model)
+carefully.
+
+**Open a Pull Request on the main huggingface/transformers repo**
+
+Before starting to adapt the automatically generated code, now is the
+time to open a "Work in progress (WIP)" pull request, *e.g.*, "\[WIP\]
+Add *[camelcase name of model]*", in 🤗 Transformers so that you and the Hugging
+Face team can work side-by-side on integrating the model into 🤗
+Transformers.
+
+You should do the following:
+
+1. Create a branch with a descriptive name from your main branch
+
+```bash
+ git checkout -b add_[lowercase name of model]
+```
+
+2. Commit the automatically generated code:
+
+```bash
+ git add .
+ git commit
+```
+
+3. Fetch and rebase to current main
+
+```bash
+ git fetch upstream
+ git rebase upstream/main
+```
+
+4. Push the changes to your account using:
+
+```bash
+ git push -u origin a-descriptive-name-for-my-changes
+```
+
+5. Once you are satisfied, go to the webpage of your fork on GitHub.
+ Click on "Pull request". Make sure to add the GitHub handle of
+ [name of mentor] as a reviewer, so that the Hugging
+ Face team gets notified for future changes.
+
+6. Change the PR into a draft by clicking on "Convert to draft" on the
+ right of the GitHub pull request web page.
+
+In the following, whenever you have done some progress, don't forget to
+commit your work and push it to your account so that it shows in the
+pull request. Additionally, you should make sure to update your work
+with the current main from time to time by doing:
+
+ git fetch upstream
+ git merge upstream/main
+
+In general, all questions you might have regarding the model or your
+implementation should be asked in your PR and discussed/solved in the
+PR. This way, [name of mentor] will always be notified when you are
+committing new code or if you have a question. It is often very helpful
+to point [name of mentor] to your added code so that the Hugging
+Face team can efficiently understand your problem or question.
+
+To do so, you can go to the "Files changed" tab where you see all of
+your changes, go to a line regarding which you want to ask a question,
+and click on the "+" symbol to add a comment. Whenever a question or
+problem has been solved, you can click on the "Resolve" button of the
+created comment.
+
+In the same way, [name of mentor] will open comments when reviewing
+your code. We recommend asking most questions on GitHub on your PR. For
+some very general questions that are not very useful for the public,
+feel free to ping [name of mentor] by Slack or email.
+
+**5. Adapt the generated models code for [camelcase name of model]**
+
+At first, we will focus only on the model itself and not care about the
+tokenizer. All the relevant code should be found in the generated files
+`src/transformers/models/[lowercase name of model]/modeling_[lowercase name of model].py` and
+`src/transformers/models/[lowercase name of model]/configuration_[lowercase name of model].py`.
+
+Now you can finally start coding :). The generated code in
+`src/transformers/models/[lowercase name of model]/modeling_[lowercase name of model].py` will
+either have the same architecture as BERT if it's an encoder-only model
+or BART if it's an encoder-decoder model. At this point, you should
+remind yourself what you've learned in the beginning about the
+theoretical aspects of the model: *How is the model different from BERT
+or BART?*\". Implement those changes which often means to change the
+*self-attention* layer, the order of the normalization layer, etc...
+Again, it is often useful to look at the similar architecture of already
+existing models in Transformers to get a better feeling of how your
+model should be implemented.
+
+**Note** that at this point, you don't have to be very sure that your
+code is fully correct or clean. Rather, it is advised to add a first
+*unclean*, copy-pasted version of the original code to
+`src/transformers/models/[lowercase name of model]/modeling_[lowercase name of model].py`
+until you feel like all the necessary code is added. From our
+experience, it is much more efficient to quickly add a first version of
+the required code and improve/correct the code iteratively with the
+conversion script as described in the next section. The only thing that
+has to work at this point is that you can instantiate the 🤗 Transformers
+implementation of *[camelcase name of model]*, *i.e.* the following command
+should work:
+
+```python
+from transformers import [camelcase name of model]Model, [camelcase name of model]Config
+model = [camelcase name of model]Model([camelcase name of model]Config())
+```
+
+The above command will create a model according to the default
+parameters as defined in `[camelcase name of model]Config()` with random weights,
+thus making sure that the `init()` methods of all components works.
+
+[TODO FILL: Here the mentor should add very specific information on what exactly has to be changed for this model]
+[...]
+[...]
+
+**6. Write a conversion script**
+
+Next, you should write a conversion script that lets you convert the
+checkpoint you used to debug *[camelcase name of model]* in the original
+repository to a checkpoint compatible with your just created 🤗
+Transformers implementation of *[camelcase name of model]*. It is not advised to
+write the conversion script from scratch, but rather to look through
+already existing conversion scripts in 🤗 Transformers for one that has
+been used to convert a similar model that was written in the same
+framework as *[camelcase name of model]*. Usually, it is enough to copy an
+already existing conversion script and slightly adapt it for your use
+case. Don't hesitate to ask [name of mentor] to point you to a
+similar already existing conversion script for your model.
+
+- If you are porting a model from TensorFlow to PyTorch, a good
+ starting point might be BERT's conversion script
+ [here](https://github.com/huggingface/transformers/blob/7acfa95afb8194f8f9c1f4d2c6028224dbed35a2/src/transformers/models/bert/modeling_bert.py#L91)
+- If you are porting a model from PyTorch to PyTorch, a good starting
+ point might be BART's conversion script
+ [here](https://github.com/huggingface/transformers/blob/main/src/transformers/models/bart/convert_bart_original_pytorch_checkpoint_to_pytorch.py)
+
+In the following, we'll quickly explain how PyTorch models store layer
+weights and define layer names. In PyTorch, the name of a layer is
+defined by the name of the class attribute you give the layer. Let's
+define a dummy model in PyTorch, called `SimpleModel` as follows:
+
+```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)
+```
+
+Now we can create an instance of this model definition which will fill
+all weights: `dense`, `intermediate`, `layer_norm` with random weights.
+We can print the model to see its architecture
+
+```python
+model = SimpleModel()
+
+print(model)
+```
+
+This will print out the following:
+
+```bash
+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)
+)
+```
+
+We can see that the layer names are defined by the name of the class
+attribute in PyTorch. You can print out the weight values of a specific
+layer:
+
+```python
+print(model.dense.weight.data)
+```
+
+to see that the weights were randomly initialized
+
+```bash
+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, you should fill those randomly initialized
+weights with the exact weights of the corresponding layer in the
+checkpoint. *E.g.*,
+
+```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)
+```
+
+While doing so, you must verify that each randomly initialized weight of
+your PyTorch model and its corresponding pretrained checkpoint weight
+exactly match in both **shape and name**. To do so, it is **necessary**
+to add assert statements for the shape and print out the names of the
+checkpoints weights. *E.g.*, you should add statements like:
+
+```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"
+```
+
+Besides, you should also print out the names of both weights to make
+sure they match, *e.g.*,
+
+```python
+logger.info(f"Initialize PyTorch weight {layer_name} from {pretrained_weight.name}")
+```
+
+If either the shape or the name doesn't match, you probably assigned
+the wrong checkpoint weight to a randomly initialized layer of the 🤗
+Transformers implementation.
+
+An incorrect shape is most likely due to an incorrect setting of the
+config parameters in `[camelcase name of model]Config()` that do not exactly match
+those that were used for the checkpoint you want to convert. However, it
+could also be that PyTorch's implementation of a layer requires the
+weight to be transposed beforehand.
+
+Finally, you should also check that **all** required weights are
+initialized and print out all checkpoint weights that were not used for
+initialization to make sure the model is correctly converted. It is
+completely normal, that the conversion trials fail with either a wrong
+shape statement or wrong name assignment. This is most likely because
+either you used incorrect parameters in `[camelcase name of model]Config()`, have a
+wrong architecture in the 🤗 Transformers implementation, you have a bug
+in the `init()` functions of one of the components of the 🤗 Transformers
+implementation or you need to transpose one of the checkpoint weights.
+
+This step should be iterated with the previous step until all weights of
+the checkpoint are correctly loaded in the Transformers model. Having
+correctly loaded the checkpoint into the 🤗 Transformers implementation,
+you can then save the model under a folder of your choice
+`/path/to/converted/checkpoint/folder` that should then contain both a
+`pytorch_model.bin` file and a `config.json` file:
+
+```python
+model.save_pretrained("/path/to/converted/checkpoint/folder")
+```
+
+[TODO FILL: Here the mentor should add very specific information on what exactly has to be done for the conversion of this model]
+[...]
+[...]
+
+**7. Implement the forward pass**
+
+Having managed to correctly load the pretrained weights into the 🤗
+Transformers implementation, you should now make sure that the forward
+pass is correctly implemented. In [Get familiar with the original
+repository](#34-run-a-pretrained-checkpoint-using-the-original-repository),
+you have already created a script that runs a forward pass of the model
+using the original repository. Now you should write an analogous script
+using the 🤗 Transformers implementation instead of the original one. It
+should look as follows:
+
+[TODO FILL: Here the model name might have to be adapted, *e.g.*, maybe [camelcase name of model]ForConditionalGeneration instead of [camelcase name of model]Model]
+
+```python
+model = [camelcase name of model]Model.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
+```
+
+It is very likely that the 🤗 Transformers implementation and the
+original model implementation don't give the exact same output the very
+first time or that the forward pass throws an error. Don't be
+disappointed - it's expected! First, you should make sure that the
+forward pass doesn't throw any errors. It often happens that the wrong
+dimensions are used leading to a `"Dimensionality mismatch"`
+error or that the wrong data type object is used, *e.g.*, `torch.long`
+instead of `torch.float32`. Don't hesitate to ask [name of mentor]
+for help, if you don't manage to solve certain errors.
+
+The final part to make sure the 🤗 Transformers implementation works
+correctly is to ensure that the outputs are equivalent to a precision of
+`1e-3`. First, you should ensure that the output shapes are identical,
+*i.e.* `outputs.shape` should yield the same value for the script of the
+🤗 Transformers implementation and the original implementation. Next, you
+should make sure that the output values are identical as well. This one
+of the most difficult parts of adding a new model. Common mistakes why
+the outputs are not identical are:
+
+- Some layers were not added, *i.e.* an activation layer
+ was not added, or the residual connection was forgotten
+- The word embedding matrix was not tied
+- The wrong positional embeddings are used because the original
+ implementation uses on offset
+- Dropout is applied during the forward pass. To fix this make sure
+ `model.training is False` and that no dropout layer is
+ falsely activated during the forward pass, *i.e.* pass
+ `self.training` to [PyTorch's functional
+ dropout](https://pytorch.org/docs/stable/nn.functional.html?highlight=dropout#torch.nn.functional.dropout)
+
+The best way to fix the problem is usually to look at the forward pass
+of the original implementation and the 🤗 Transformers implementation
+side-by-side and check if there are any differences. Ideally, you should
+debug/print out intermediate outputs of both implementations of the
+forward pass to find the exact position in the network where the 🤗
+Transformers implementation shows a different output than the original
+implementation. First, make sure that the hard-coded `input_ids` in both
+scripts are identical. Next, verify that the outputs of the first
+transformation of the `input_ids` (usually the word embeddings) are
+identical. And then work your way up to the very last layer of the
+network. At some point, you will notice a difference between the two
+implementations, which should point you to the bug in the 🤗 Transformers
+implementation. From our experience, a simple and efficient way is to
+add many print statements in both the original implementation and 🤗
+Transformers implementation, at the same positions in the network
+respectively, and to successively remove print statements showing the
+same values for intermediate presentions.
+
+When you're confident that both implementations yield the same output,
+verifying the outputs with
+`torch.allclose(original_output, output, atol=1e-3)`, you're done with
+the most difficult part! Congratulations - the work left to be done
+should be a cakewalk 😊.
+
+**8. Adding all necessary model tests**
+
+At this point, you have successfully added a new model. However, it is
+very much possible that the model does not yet fully comply with the
+required design. To make sure, the implementation is fully compatible
+with 🤗 Transformers, all common tests should pass. The Cookiecutter
+should have automatically added a test file for your model, probably
+under the same `tests/test_modeling_[lowercase name of model].py`. Run this test
+file to verify that all common tests pass:
+
+```python
+pytest tests/test_modeling_[lowercase name of model].py
+```
+
+[TODO FILL: Here the mentor should add very specific information on what tests are likely to fail after having implemented the model
+, e.g. given the model, it might be very likely that `test_attention_output` fails]
+[...]
+[...]
+
+Having fixed all common tests, it is now crucial to ensure that all the
+nice work you have done is well tested, so that
+
+- a) The community can easily understand your work by looking at
+ specific tests of *[camelcase name of model]*
+
+- b) Future changes to your model will not break any important
+ feature of the model.
+
+At first, integration tests should be added. Those integration tests
+essentially do the same as the debugging scripts you used earlier to
+implement the model to 🤗 Transformers. A template of those model tests
+is already added by the Cookiecutter, called
+`[camelcase name of model]ModelIntegrationTests` and only has to be filled out by
+you. To ensure that those tests are passing, run
+
+```python
+RUN_SLOW=1 pytest -sv tests/test_modeling_[lowercase name of model].py::[camelcase name of model]ModelIntegrationTests
+```
+
+**Note:** In case you are using Windows, you should replace `RUN_SLOW=1` with `SET RUN_SLOW=1`
+
+Second, all features that are special to *[camelcase name of model]* should be
+tested additionally in a separate test under
+`[camelcase name of model]ModelTester`/`[camelcase name of model]ModelTest`. This part is often
+forgotten but is extremely useful in two ways:
+
+- It helps to transfer the knowledge you have acquired during the
+ model addition to the community by showing how the special features
+ of *[camelcase name of model]* should work.
+- Future contributors can quickly test changes to the model by running
+ those special tests.
+
+[TODO FILL: Here the mentor should add very specific information on what special features of the model should be tested additionally]
+[...]
+[...]
+
+**9. Implement the tokenizer**
+
+Next, we should add the tokenizer of *[camelcase name of model]*. Usually, the
+tokenizer is equivalent or very similar to an already existing tokenizer
+of 🤗 Transformers.
+
+[TODO FILL: Here the mentor should add a comment whether a new tokenizer is required or if this is not the case which existing tokenizer closest resembles
+ [camelcase name of model]'s tokenizer and how the tokenizer should be implemented]
+ [...]
+ [...]
+
+It is very important to find/extract the original tokenizer file and to
+manage to load this file into the 🤗 Transformers' implementation of the
+tokenizer.
+
+For [camelcase name of model], the tokenizer files can be found here:
+- [To be filled out by mentor]
+
+and having implemented the 🤗 Transformers' version of the tokenizer can be loaded as follows:
+
+[To be filled out by mentor]
+
+To ensure that the tokenizer works correctly, it is recommended to first
+create a script in the original repository that inputs a string and
+returns the `input_ids`. It could look similar to this (in pseudo-code):
+
+```bash
+input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words."
+model = [camelcase name of model]Model.load_pretrained_checkpoint("/path/to/checkpoint/")
+input_ids = model.tokenize(input_str)
+```
+
+You might have to take a deeper look again into the original repository
+to find the correct tokenizer function or you might even have to do
+changes to your clone of the original repository to only output the
+`input_ids`. Having written a functional tokenization script that uses
+the original repository, an analogous script for 🤗 Transformers should
+be created. It should look similar to this:
+
+```python
+from transformers import [camelcase name of model]Tokenizer
+input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words."
+
+tokenizer = [camelcase name of model]Tokenizer.from_pretrained("/path/to/tokenizer/folder/")
+
+input_ids = tokenizer(input_str).input_ids
+```
+
+When both `input_ids` yield the same values, as a final step a tokenizer
+test file should also be added.
+
+[TODO FILL: Here mentor should point the student to test files of similar tokenizers]
+
+Analogous to the modeling test files of *[camelcase name of model]*, the
+tokenization test files of *[camelcase name of model]* should contain a couple of
+hard-coded integration tests.
+
+[TODO FILL: Here mentor should again point to an existing similar test of another model that the student can copy & adapt]
+
+**10. Run End-to-end integration tests**
+
+Having added the tokenizer, you should also add a couple of end-to-end
+integration tests using both the model and the tokenizer to
+`tests/test_modeling_[lowercase name of model].py` in 🤗 Transformers. Such a test
+should show on a meaningful text-to-text sample that the 🤗 Transformers
+implementation works as expected. A meaningful text-to-text sample can
+include *e.g.* a source-to-target-translation pair, an
+article-to-summary pair, a question-to-answer pair, etc... If none of
+the ported checkpoints has been fine-tuned on a downstream task it is
+enough to simply rely on the model tests. In a final step to ensure that
+the model is fully functional, it is advised that you also run all tests
+on GPU. It can happen that you forgot to add some `.to(self.device)`
+statements to internal tensors of the model, which in such a test would
+show in an error. In case you have no access to a GPU, the Hugging Face
+team can take care of running those tests for you.
+
+**11. Add Docstring**
+
+Now, all the necessary functionality for *[camelcase name of model]* is added -
+you're almost done! The only thing left to add is a nice docstring and
+a doc page. The Cookiecutter should have added a template file called
+`docs/source/model_doc/[lowercase name of model].rst` that you should fill out.
+Users of your model will usually first look at this page before using
+your model. Hence, the documentation must be understandable and concise.
+It is very useful for the community to add some *Tips* to show how the
+model should be used. Don't hesitate to ping [name of mentor]
+regarding the docstrings.
+
+Next, make sure that the docstring added to
+`src/transformers/models/[lowercase name of model]/modeling_[lowercase name of model].py` is
+correct and included all necessary inputs and outputs. It is always to
+good to remind oneself that documentation should be treated at least as
+carefully as the code in 🤗 Transformers since the documentation is
+usually the first contact point of the community with the model.
+
+**Code refactor**
+
+Great, now you have added all the necessary code for *[camelcase name of model]*.
+At this point, you should correct some potential incorrect code style by
+running:
+
+```bash
+make style
+```
+
+and verify that your coding style passes the quality check:
+
+```bash
+make quality
+```
+
+There are a couple of other very strict design tests in 🤗 Transformers
+that might still be failing, which shows up in the tests of your pull
+request. This is often because of some missing information in the
+docstring or some incorrect naming. [name of mentor] will surely
+help you if you're stuck here.
+
+Lastly, it is always a good idea to refactor one's code after having
+ensured that the code works correctly. With all tests passing, now it's
+a good time to go over the added code again and do some refactoring.
+
+You have now finished the coding part, congratulation! 🎉 You are
+Awesome! 😎
+
+**12. Upload the models to the model hub**
+
+In this final part, you should convert and upload all checkpoints to the
+model hub and add a model card for each uploaded model checkpoint. You
+should work alongside [name of mentor] here to decide on a fitting
+name for each checkpoint and to get the required access rights to be
+able to upload the model under the author's organization of
+*[camelcase name of model]*.
+
+It is worth spending some time to create fitting model cards for each
+checkpoint. The model cards should highlight the specific
+characteristics of this particular checkpoint, *e.g.*, On which dataset
+was the checkpoint pretrained/fine-tuned on? On what down-stream task
+should the model be used? And also include some code on how to correctly
+use the model.
+
+**13. (Optional) Add notebook**
+
+It is very helpful to add a notebook that showcases in-detail how
+*[camelcase name of model]* can be used for inference and/or fine-tuned on a
+downstream task. This is not mandatory to merge your PR, but very useful
+for the community.
+
+**14. Submit your finished PR**
+
+You're done programming now and can move to the last step, which is
+getting your PR merged into main. Usually, [name of mentor]
+should have helped you already at this point, but it is worth taking
+some time to give your finished PR a nice description and eventually add
+comments to your code, if you want to point out certain design choices
+to your reviewer.
+
+### Share your work!!
+
+Now, it's time to get some credit from the community for your work!
+Having completed a model addition is a major contribution to
+Transformers and the whole NLP community. Your code and the ported
+pre-trained models will certainly be used by hundreds and possibly even
+thousands of developers and researchers. You should be proud of your
+work and share your achievement with the community.
+
+**You have made another model that is super easy to access for everyone
+in the community! 🤯**
diff --git a/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_model/README.md b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_model/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..8c8c7af0b333fb0bbf4bff956e40fdbd880591d1
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_model/README.md
@@ -0,0 +1,23 @@
+
+
+# Adding a new model
+
+This page has been updated in light of the removal of the `add_new_model` script in favor of the more complete
+`add_new_model_like` script.
+
+We recommend you checkout the documentation of [How to add a model](https://huggingface.co/docs/transformers/main/en/add_new_model)
+in the Hugging Face Transformers documentation for complete and up-to-date instructions.
diff --git a/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_model/open_model_proposals/ADD_BIG_BIRD.md b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_model/open_model_proposals/ADD_BIG_BIRD.md
new file mode 100644
index 0000000000000000000000000000000000000000..02c9fa32a2390f369d6fe9375099352640225cb0
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_model/open_model_proposals/ADD_BIG_BIRD.md
@@ -0,0 +1,1148 @@
+How to add BigBird to 🤗 Transformers?
+=====================================
+
+Mentor: [Patrick](https://github.com/patrickvonplaten)
+
+Begin: 12.02.2020
+
+Estimated End: 19.03.2020
+
+Contributor: [Vasudev](https://github.com/thevasudevgupta)
+
+Adding a new model is often difficult and requires an in-depth knowledge
+of the 🤗 Transformers library and ideally also of the model's original
+repository. At Hugging Face, we are trying to empower the community more
+and more to add models independently.
+
+The following sections explain in detail how to add BigBird
+to Transformers. You will work closely with Patrick to
+integrate BigBird into Transformers. By doing so, you will both gain a
+theoretical and deep practical understanding of BigBird.
+But more importantly, you will have made a major
+open-source contribution to Transformers. Along the way, you will:
+
+- get insights into open-source best practices
+- understand the design principles of one of the most popular NLP
+ libraries
+- learn how to do efficiently test large NLP models
+- learn how to integrate Python utilities like `black`, `ruff`,
+ `make fix-copies` into a library to always ensure clean and readable
+ code
+
+To start, let's try to get a general overview of the Transformers
+library.
+
+General overview of 🤗 Transformers
+----------------------------------
+
+First, you should get a general overview of 🤗 Transformers. Transformers
+is a very opinionated library, so there is a chance that
+you don't agree with some of the library's philosophies or design
+choices. From our experience, however, we found that the fundamental
+design choices and philosophies of the library are crucial to
+efficiently scale Transformers while keeping maintenance costs at a
+reasonable level.
+
+A good first starting point to better understand the library is to read
+the [documentation of our philosophy](https://huggingface.co/transformers/philosophy.html).
+As a result of our way of working, there are some choices that we try to apply to all models:
+
+- Composition is generally favored over abstraction
+- Duplicating code is not always bad if it strongly improves the
+ readability or accessibility of a model
+- Model files are as self-contained as possible so that when you read
+ the code of a specific model, you ideally only have to look into the
+ respective `modeling_....py` file.
+
+In our opinion, the library's code is not just a means to provide a
+product, *e.g.*, the ability to use BERT for inference, but also as the
+very product that we want to improve. Hence, when adding a model, the
+user is not only the person that will use your model, but also everybody
+that will read, try to understand, and possibly tweak your code.
+
+With this in mind, let's go a bit deeper into the general library
+design.
+
+### Overview of models
+
+To successfully add a model, it is important to understand the
+interaction between your model and its config,
+`PreTrainedModel`, and `PretrainedConfig`. For
+exemplary purposes, we will call the PyTorch model to be added to 🤗 Transformers
+`BrandNewBert`.
+
+Let's take a look:
+
+
+
+As you can see, we do make use of inheritance in 🤗 Transformers, but we
+keep the level of abstraction to an absolute minimum. There are never
+more than two levels of abstraction for any model in the library.
+`BrandNewBertModel` inherits from
+`BrandNewBertPreTrainedModel` which in
+turn inherits from `PreTrainedModel` and that's it.
+As a general rule, we want to make sure
+that a new model only depends on `PreTrainedModel`. The
+important functionalities that are automatically provided to every new
+model are
+`PreTrainedModel.from_pretrained` and `PreTrainedModel.save_pretrained`, which are
+used for serialization and deserialization. All
+of the other important functionalities, such as
+`BrandNewBertModel.forward` should be
+completely defined in the new `modeling_brand_new_bert.py` module. Next,
+we want to make sure that a model with a specific head layer, such as
+`BrandNewBertForMaskedLM` does not inherit
+from `BrandNewBertModel`, but rather uses
+`BrandNewBertModel` as a component that
+can be called in its forward pass to keep the level of abstraction low.
+Every new model requires a configuration class, called
+`BrandNewBertConfig`. This configuration
+is always stored as an attribute in
+`PreTrainedModel`, and
+thus can be accessed via the `config` attribute for all classes
+inheriting from `BrandNewBertPreTrainedModel`
+
+```python
+# assuming that `brand_new_bert` belongs to the organization `brandy`
+model = BrandNewBertModel.from_pretrained("brandy/brand_new_bert")
+model.config # model has access to its config
+```
+
+Similar to the model, the configuration inherits basic serialization and
+deserialization functionalities from
+`PretrainedConfig`. Note
+that the configuration and the model are always serialized into two
+different formats - the model to a `pytorch_model.bin` file
+and the configuration to a `config.json` file. Calling
+`PreTrainedModel.save_pretrained` will automatically call
+`PretrainedConfig.save_pretrained`, so that both model and configuration are saved.
+
+### Overview of tokenizers
+
+Not quite ready yet :-( This section will be added soon!
+
+Step-by-step recipe to add a model to 🤗 Transformers
+----------------------------------------------------
+
+Everyone has different preferences of how to port a model so it can be
+very helpful for you to take a look at summaries of how other
+contributors ported models to Hugging Face. Here is a list of community
+blog posts on how to port a model:
+
+1. [Porting GPT2
+ Model](https://medium.com/huggingface/from-tensorflow-to-pytorch-265f40ef2a28)
+ by [Thomas](https://huggingface.co/thomwolf)
+2. [Porting WMT19 MT Model](https://huggingface.co/blog/porting-fsmt)
+ by [Stas](https://huggingface.co/stas)
+
+From experience, we can tell you that the most important things to keep
+in mind when adding a model are:
+
+- Don't reinvent the wheel! Most parts of the code you will add for
+ the new 🤗 Transformers model already exist somewhere in 🤗
+ Transformers. Take some time to find similar, already existing
+ models and tokenizers you can copy from.
+ [grep](https://www.gnu.org/software/grep/) and
+ [rg](https://github.com/BurntSushi/ripgrep) are your friends. Note
+ that it might very well happen that your model's tokenizer is based
+ on one model implementation, and your model's modeling code on
+ another one. *E.g.*, FSMT's modeling code is based on BART, while
+ FSMT's tokenizer code is based on XLM.
+- It's more of an engineering challenge than a scientific challenge.
+ You should spend more time on creating an efficient debugging
+ environment than trying to understand all theoretical aspects of the
+ model in the paper.
+- Ask for help when you're stuck! Models are the core component of 🤗
+ Transformers so we, at Hugging Face, are more than happy to help
+ you at every step to add your model. Don't hesitate to ask if you
+ notice you are not making progress.
+
+In the following, we try to give you a general recipe that we found most
+useful when porting a model to 🤗 Transformers.
+
+The following list is a summary of everything that has to be done to add
+a model and can be used by you as a To-Do List:
+
+1. [ ] (Optional) Understood theoretical aspects
+
+2. [ ] Prepared transformers dev environment
+
+3. [ ] Set up debugging environment of the original repository
+
+4. [ ] Created script that successfully runs forward pass using
+ original repository and checkpoint
+
+5. [ ] Successfully opened a PR and added the model skeleton to Transformers
+
+6. [ ] Successfully converted original checkpoint to Transformers
+ checkpoint
+
+7. [ ] Successfully ran forward pass in Transformers that gives
+ identical output to original checkpoint
+
+8. [ ] Finished model tests in Transformers
+
+9. [ ] Successfully added Tokenizer in Transformers
+
+10. [ ] Run end-to-end integration tests
+
+11. [ ] Finished docs
+
+12. [ ] Uploaded model weights to the hub
+
+13. [ ] Submitted the pull request for review
+
+14. [ ] (Optional) Added a demo notebook
+
+To begin with, we usually recommend to start by getting a good
+theoretical understanding of `BigBird`. However, if you prefer to
+understand the theoretical aspects of the model *on-the-job*, then it is
+totally fine to directly dive into the `BigBird`'s code-base. This
+option might suit you better, if your engineering skills are better than
+your theoretical skill, if you have trouble understanding
+`BigBird`'s paper, or if you just enjoy programming much more than
+reading scientific papers.
+
+### 1. (Optional) Theoretical aspects of BigBird
+
+You should take some time to read *BigBird's* paper, if such
+descriptive work exists. There might be large sections of the paper that
+are difficult to understand. If this is the case, this is fine - don't
+worry! The goal is not to get a deep theoretical understanding of the
+paper, but to extract the necessary information required to effectively
+re-implement the model in 🤗 Transformers. That being said, you don't
+have to spend too much time on the theoretical aspects, but rather focus
+on the practical ones, namely:
+
+- What type of model is *BigBird*? BERT-like encoder-only
+ model? GPT2-like decoder-only model? BART-like encoder-decoder
+ model? Look at the `model_summary` if
+ you're not familiar with the differences between those.
+- What are the applications of *BigBird*? Text
+ classification? Text generation? Seq2Seq tasks, *e.g.,*
+ summarization?
+- What is the novel feature of the model making it different from
+ BERT/GPT-2/BART?
+- Which of the already existing [🤗 Transformers
+ models](https://huggingface.co/transformers/#contents) is most
+ similar to *BigBird*?
+- What type of tokenizer is used? A sentencepiece tokenizer? Word
+ piece tokenizer? Is it the same tokenizer as used for BERT or BART?
+
+After you feel like you have gotten a good overview of the architecture
+of the model, you might want to write to Patrick with any
+questions you might have. This might include questions regarding the
+model's architecture, its attention layer, etc. We will be more than
+happy to help you.
+
+
+#### Additional resources
+
+ Before diving into the code, here are some additional resources that might be worth taking a look at:
+
+ - [Yannic Kilcher's paper summary](https://www.youtube.com/watch?v=WVPE62Gk3EM&ab_channel=YannicKilcher)
+ - [Yannic Kilcher's summary of Longformer](https://www.youtube.com/watch?v=_8KNb5iqblE&ab_channel=YannicKilcher) - Longformer and BigBird are **very** similar models. Since Longformer has already been ported to 🤗 Transformers, it is useful to understand the differences between the two models
+ - [Blog post](https://medium.com/dsc-msit/is-google-bigbird-gonna-be-the-new-leader-in-nlp-domain-8c95cecc30f8) - A relatively superficial blog post about BigBird. Might be a good starting point to understand BigBird
+
+#### Make sure you've understood the fundamental aspects of BigBird
+
+Alright, now you should be ready to take a closer look into the actual code of BigBird.
+You should have understood the following aspects of BigBird by now:
+
+- BigBird provides a new attention layer for long-range sequence modelling that can be used
+ as a drop-in replacement for already existing architectures. This means that every transformer-based model architecture can replace its [Self-attention layer](https://towardsdatascience.com/illustrated-self-attention-2d627e33b20a) with BigBird's self-attention layer.
+- BigBird's self-attention layer is composed of three mechanisms: block sparse (local) self-attention, global self-attention, random self-attention
+- BigBird's block sparse (local) self-attention is different from Longformer's local self-attention. How so? Why does that matter? => Can be deployed on TPU much easier this way
+- BigBird can be implemented for both an encoder-only model **and**
+ for an encoder-decoder model, which means that we can reuse lots of [code from RoBERTa](https://github.com/huggingface/transformers/blob/main/src/transformers/models/roberta/modeling_roberta.py) and [from PEGASUS](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pegasus/modeling_pegasus.py) at a later stage.
+
+
+If any of the mentioned aspects above are **not** clear to you, now is a great time to talk to Patrick.
+
+### 2. Next prepare your environment
+
+1. Fork the [repository](https://github.com/huggingface/transformers)
+ by clicking on the 'Fork' button on the repository's page. This
+ creates a copy of the code under your GitHub user account.
+
+2. Clone your `transformers` fork to your local disk, and add the base
+ repository as a remote:
+
+ ```bash
+ git clone https://github.com/[your Github handle]/transformers.git
+ cd transformers
+ git remote add upstream https://github.com/huggingface/transformers.git
+ ```
+
+3. Set up a development environment, for instance by running the
+ following command:
+
+ ```bash
+ python -m venv .env
+ source .env/bin/activate
+ pip install -e ".[dev]"
+ ```
+
+and return to the parent directory
+
+```bash
+cd ..
+```
+
+4. We recommend adding the PyTorch version of *BigBird* to
+ Transformers. To install PyTorch, please follow the instructions [here](https://pytorch.org/get-started/locally/).
+
+**Note:** You don't need to have CUDA installed. Making the new model
+work on CPU is sufficient.
+
+5. To port *BigBird*, you will also need access to its
+ original repository:
+
+```bash
+git clone https://github.com/google-research/bigbird.git
+cd big_bird
+pip install -e .
+```
+
+Now you have set up a development environment to port *BigBird*
+to 🤗 Transformers.
+
+### Run a pretrained checkpoint using the original repository
+
+**3. Set up debugging environment**
+
+At first, you will work on the original *BigBird* repository.
+Often, the original implementation is very "researchy". Meaning that
+documentation might be lacking and the code can be difficult to
+understand. But this should be exactly your motivation to reimplement
+*BigBird*. At Hugging Face, one of our main goals is to *make
+people stand on the shoulders of giants* which translates here very well
+into taking a working model and rewriting it to make it as **accessible,
+user-friendly, and beautiful** as possible. This is the number-one
+motivation to re-implement models into 🤗 Transformers - trying to make
+complex new NLP technology accessible to **everybody**.
+
+You should start thereby by diving into the [original repository](https://github.com/google-research/bigbird).
+
+Successfully running the official pretrained model in the original
+repository is often **the most difficult** step. From our experience, it
+is very important to spend some time getting familiar with the original
+code-base. You need to figure out the following:
+
+- Where to find the pretrained weights?
+- How to load the pretrained weights into the corresponding model?
+- How to run the tokenizer independently from the model?
+- Trace one forward pass so that you know which classes and functions
+ are required for a simple forward pass. Usually, you only have to
+ reimplement those functions.
+- Be able to locate the important components of the model: Where is
+ the model's class? Are there model sub-classes, *e.g.*,
+ EncoderModel, DecoderModel? Where is the self-attention layer? Are
+ there multiple different attention layers, *e.g.*, *self-attention*,
+ *cross-attention*...?
+- How can you debug the model in the original environment of the repo?
+ Do you have to add `print` statements, can you work with
+ an interactive debugger like [ipdb](https://pypi.org/project/ipdb/), or should you use
+ an efficient IDE to debug the model, like PyCharm?
+
+It is very important that before you start the porting process, that you
+can **efficiently** debug code in the original repository! Also,
+remember that you are working with an open-source library, so do not
+hesitate to open an issue, or even a pull request in the original
+repository. The maintainers of this repository are most likely very
+happy about someone looking into their code!
+
+At this point, it is really up to you which debugging environment and
+strategy you prefer to use to debug the original model. We strongly
+advise against setting up a costly GPU environment, but simply work on a
+CPU both when starting to dive into the original repository and also
+when starting to write the 🤗 Transformers implementation of the model.
+Only at the very end, when the model has already been successfully
+ported to 🤗 Transformers, one should verify that the model also works as
+expected on GPU.
+
+In general, there are two possible debugging environments for running
+the original model
+
+- [Jupyter notebooks](https://jupyter.org/) / [google colab](https://colab.research.google.com/notebooks/intro.ipynb)
+- Local python scripts.
+
+Jupyter notebooks have the advantage that they allow for cell-by-cell
+execution which can be helpful to better split logical components from
+one another and to have faster debugging cycles as intermediate results
+can be stored. Also, notebooks are often easier to share with other
+contributors, which might be very helpful if you want to ask the Hugging
+Face team for help. If you are familiar with Jupyter notebooks, we
+strongly recommend you to work with them.
+
+The obvious disadvantage of Jupyter notebooks is that if you are not
+used to working with them you will have to spend some time adjusting to
+the new programming environment and that you might not be able to use
+your known debugging tools anymore, like `ipdb`.
+
+**4. Successfully run forward pass**
+
+For each code-base, a good first step is always to load a **small**
+pretrained checkpoint and to be able to reproduce a single forward pass
+using a dummy integer vector of input IDs as an input. Such a script
+could look something like this:
+
+```python
+from bigbird.core import modeling
+model = modeling.BertModel(bert_config)
+from bigbird.core import utils
+
+params = utils.BigBirdConfig(vocab_size=32000, hidden_size=512,
+ num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)
+
+ckpt_path = 'gs://bigbird-transformer/pretrain/bigbr_base/model.ckpt-0'
+ckpt_reader = tf.compat.v1.train.NewCheckpointReader(ckpt_path)
+model.set_weights([ckpt_reader.get_tensor(v.name[:-2]) for v in tqdm(model.trainable_weights, position=0)])
+
+input_ids = tf.constant([[31, 51, 99], [15, 5, 0]])
+_, pooled_output = model(input_ids=input_ids, token_type_ids=token_type_ids)
+...
+
+```
+
+Next, regarding the debugging strategy, there are generally a few from
+which to choose from:
+
+- Decompose the original model into many small testable components and
+ run a forward pass on each of those for verification
+- Decompose the original model only into the original *tokenizer* and
+ the original *model*, run a forward pass on those, and use
+ intermediate print statements or breakpoints for verification
+
+Again, it is up to you which strategy to choose. Often, one or the other
+is advantageous depending on the original code base.
+
+If the original code-base allows you to decompose the model into smaller
+sub-components, *e.g.*, if the original code-base can easily be run in
+eager mode, it is usually worth the effort to do so. There are some
+important advantages to taking the more difficult road in the beginning:
+
+- at a later stage when comparing the original model to the Hugging
+ Face implementation, you can verify automatically for each component
+ individually that the corresponding component of the 🤗 Transformers
+ implementation matches instead of relying on visual comparison via
+ print statements
+- it can give you some rope to decompose the big problem of porting a
+ model into smaller problems of just porting individual components
+ and thus structure your work better
+- separating the model into logical meaningful components will help
+ you to get a better overview of the model's design and thus to
+ better understand the model
+- at a later stage those component-by-component tests help you to
+ ensure that no regression occurs as you continue changing your code
+
+[Lysandre's](https://gist.github.com/LysandreJik/db4c948f6b4483960de5cbac598ad4ed)
+integration checks for ELECTRA gives a nice example of how this can be
+done.
+
+However, if the original code-base is very complex or only allows
+intermediate components to be run in a compiled mode, it might be too
+time-consuming or even impossible to separate the model into smaller
+testable sub-components. A good example is [T5's
+MeshTensorFlow](https://github.com/tensorflow/mesh/tree/master/mesh_tensorflow)
+library which is very complex and does not offer a simple way to
+decompose the model into its sub-components. For such libraries, one
+often relies on verifying print statements.
+
+No matter which strategy you choose, the recommended procedure is often
+the same in that you should start to debug the starting layers first and
+the ending layers last.
+
+It is recommended that you retrieve the output, either by print
+statements or sub-component functions, of the following layers in the
+following order:
+
+1. Retrieve the input IDs passed to the model
+2. Retrieve the word embeddings
+3. Retrieve the input of the first Transformer layer
+4. Retrieve the output of the first Transformer layer
+5. Retrieve the output of the following n - 1 Transformer layers
+6. Retrieve the output of the whole BigBird Model
+
+Input IDs should thereby consists of an array of integers, *e.g.*,
+`input_ids = [0, 4, 4, 3, 2, 4, 1, 7, 19]`
+
+The outputs of the following layers often consist of multi-dimensional
+float arrays and can look like this:
+
+```bash
+[[
+ [-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]]],
+```
+
+We expect that every model added to 🤗 Transformers passes a couple of
+integration tests, meaning that the original model and the reimplemented
+version in 🤗 Transformers have to give the exact same output up to a
+precision of 0.001! Since it is normal that the exact same model written
+in different libraries can give a slightly different output depending on
+the library framework, we accept an error tolerance of 1e-3 (0.001). It
+is not enough if the model gives nearly the same output, they have to be
+the almost identical. Therefore, you will certainly compare the
+intermediate outputs of the 🤗 Transformers version multiple times
+against the intermediate outputs of the original implementation of
+*BigBird* in which case an **efficient** debugging environment
+of the original repository is absolutely important. Here is some advice
+to make your debugging environment as efficient as possible.
+
+- Find the best way of debugging intermediate results. Is the original
+ repository written in PyTorch? Then you should probably take the
+ time to write a longer script that decomposes the original model
+ into smaller sub-components to retrieve intermediate values. Is the
+ original repository written in Tensorflow 1? Then you might have to
+ rely on TensorFlow print operations like
+ [tf.print](https://www.tensorflow.org/api_docs/python/tf/print) to
+ output intermediate values. Is the original repository written in
+ Jax? Then make sure that the model is **not jitted** when running
+ the forward pass, *e.g.*, check-out [this
+ link](https://github.com/google/jax/issues/196).
+- Use the smallest pretrained checkpoint you can find. The smaller the
+ checkpoint, the faster your debug cycle becomes. It is not efficient
+ if your pretrained model is so big that your forward pass takes more
+ than 10 seconds. In case only very large checkpoints are available,
+ it might make more sense to create a dummy model in the new
+ environment with randomly initialized weights and save those weights
+ for comparison with the 🤗 Transformers version of your model
+- Make sure you are using the easiest way of calling a forward pass in
+ the original repository. Ideally, you want to find the function in
+ the original repository that **only** calls a single forward pass,
+ *i.e.* that is often called `predict`, `evaluate`, `forward` or
+ `__call__`. You don't want to debug a function that calls `forward`
+ multiple times, *e.g.*, to generate text, like
+ `autoregressive_sample`, `generate`.
+- Try to separate the tokenization from the model's
+ forward pass. If the original repository shows
+ examples where you have to input a string, then try to find out
+ where in the forward call the string input is changed to input ids
+ and start from this point. This might mean that you have to possibly
+ write a small script yourself or change the original code so that
+ you can directly input the ids instead of an input string.
+- Make sure that the model in your debugging setup is **not** in
+ training mode, which often causes the model to yield random outputs
+ due to multiple dropout layers in the model. Make sure that the
+ forward pass in your debugging environment is **deterministic** so
+ that the dropout layers are not used. Or use
+ `transformers.utils.set_seed` if the old and new
+ implementations are in the same framework.
+
+#### (Important) More details on how to create a debugging environment for BigBird
+
+- BigBird has multiple pretrained checkpoints that should eventually all be ported to
+ 🤗 Transformers. The pretrained checkpoints can be found [here](https://console.cloud.google.com/storage/browser/bigbird-transformer/pretrain;tab=objects?prefix=&forceOnObjectsSortingFiltering=false).
+ Those checkpoints include both pretrained weights for encoder-only (BERT/RoBERTa) under the folder `bigbr_base` and encoder-decoder (PEGASUS) under the folder `bigbp_large`.
+ You should start by porting the `bigbr_base` model. The encoder-decoder model
+ can be ported afterward.
+ for an encoder-decoder architecture as well as an encoder-only architecture.
+- BigBird was written in tf.compat meaning that a mixture of a TensorFlow 1 and
+ TensorFlow 2 API was used.
+- The most important part of the BigBird code-base is [bigbird.bigbird.core](https://github.com/google-research/bigbird/tree/master/bigbird/core) which includes all logic necessary
+ to implement BigBird.
+- The first goal should be to successfully run a forward pass using the RoBERTa checkpoint `bigbr_base/model.ckpt-0.data-00000-of-00001` and `bigbr_base/model.ckpt-0.index`.
+
+
+### Port BigBird to 🤗 Transformers
+
+Next, you can finally start adding new code to 🤗 Transformers. Go into
+the clone of your 🤗 Transformers' fork:
+
+ cd transformers
+
+In the special case that you are adding a model whose architecture
+exactly matches the model architecture of an existing model you only
+have to add a conversion script as described in [this
+section](#write-a-conversion-script). In this case, you can just re-use
+the whole model architecture of the already existing model.
+
+Otherwise, let's start generating a new model with the amazing
+Cookiecutter!
+
+**Use the Cookiecutter to automatically generate the model's code**
+
+To begin with head over to the [🤗 Transformers
+templates](https://github.com/huggingface/transformers/tree/main/templates/adding_a_new_model)
+to make use of our `cookiecutter` implementation to automatically
+generate all the relevant files for your model. Again, we recommend only
+adding the PyTorch version of the model at first. Make sure you follow
+the instructions of the `README.md` on the [🤗 Transformers
+templates](https://github.com/huggingface/transformers/tree/main/templates/adding_a_new_model)
+carefully.
+Since you will first implement the Encoder-only/RoBERTa-like version of BigBird you should
+select the `is_encoder_decoder_model = False` option in the cookiecutter. Also, it is recommended
+that you implement the model only in PyTorch in the beginning and select "Standalone" as the
+tokenizer type for now.
+
+**Open a Pull Request on the main huggingface/transformers repo**
+
+Before starting to adapt the automatically generated code, now is the
+time to open a "Work in progress (WIP)" pull request, *e.g.*, "\[WIP\]
+Add *BigBird*", in 🤗 Transformers so that you and the Hugging
+Face team can work side-by-side on integrating the model into 🤗
+Transformers.
+
+You should do the following:
+
+1. Create a branch with a descriptive name from your main branch
+
+```bash
+ git checkout -b add_big_bird
+```
+
+2. Commit the automatically generated code:
+
+```bash
+ git add .
+ git commit
+```
+
+3. Fetch and rebase to current main
+
+```bash
+ git fetch upstream
+ git rebase upstream/main
+```
+
+4. Push the changes to your account using:
+
+```bash
+ git push -u origin a-descriptive-name-for-my-changes
+```
+
+5. Once you are satisfied, go to the webpage of your fork on GitHub.
+ Click on "Pull request". Make sure to add the GitHub handle of Patrick
+ as one reviewer, so that the Hugging Face team gets notified for future changes.
+
+6. Change the PR into a draft by clicking on "Convert to draft" on the
+ right of the GitHub pull request web page.
+
+In the following, whenever you have done some progress, don't forget to
+commit your work and push it to your account so that it shows in the
+pull request. Additionally, you should make sure to update your work
+with the current main from time to time by doing:
+
+ git fetch upstream
+ git merge upstream/main
+
+In general, all questions you might have regarding the model or your
+implementation should be asked in your PR and discussed/solved in the
+PR. This way, Patrick will always be notified when you are
+committing new code or if you have a question. It is often very helpful
+to point Patrick to your added code so that the Hugging
+Face team can efficiently understand your problem or question.
+
+To do so, you can go to the "Files changed" tab where you see all of
+your changes, go to a line regarding which you want to ask a question,
+and click on the "+" symbol to add a comment. Whenever a question or
+problem has been solved, you can click on the "Resolve" button of the
+created comment.
+
+In the same way, Patrick will open comments when reviewing
+your code. We recommend asking most questions on GitHub on your PR. For
+some very general questions that are not very useful for the public,
+feel free to ping Patrick by Slack or email.
+
+**5. Adapt the generated models code for BigBird**
+
+At first, we will focus only on the model itself and not care about the
+tokenizer. All the relevant code should be found in the generated files
+`src/transformers/models/big_bird/modeling_big_bird.py` and
+`src/transformers/models/big_bird/configuration_big_bird.py`.
+
+Now you can finally start coding :). The generated code in
+`src/transformers/models/big_bird/modeling_big_bird.py` will
+either have the same architecture as BERT if it's an encoder-only model
+or BART if it's an encoder-decoder model. At this point, you should
+remind yourself what you've learned in the beginning about the
+theoretical aspects of the model: *How is the model different from BERT
+or BART?*\". Implement those changes which often means to change the
+*self-attention* layer, the order of the normalization layer, etc...
+Again, it is often useful to look at the similar architecture of already
+existing models in Transformers to get a better feeling of how your
+model should be implemented.
+
+**Note** that at this point, you don't have to be very sure that your
+code is fully correct or clean. Rather, it is advised to add a first
+*unclean*, copy-pasted version of the original code to
+`src/transformers/models/big_bird/modeling_big_bird.py`
+until you feel like all the necessary code is added. From our
+experience, it is much more efficient to quickly add a first version of
+the required code and improve/correct the code iteratively with the
+conversion script as described in the next section. The only thing that
+has to work at this point is that you can instantiate the 🤗 Transformers
+implementation of *BigBird*, *i.e.* the following command
+should work:
+
+```python
+from transformers import BigBirdModel, BigBirdConfig
+model = BigBirdModel(BigBirdConfig())
+```
+
+The above command will create a model according to the default
+parameters as defined in `BigBirdConfig()` with random weights,
+thus making sure that the `init()` methods of all components works.
+
+Note that for BigBird you have to change the attention layer. BigBird's attention
+layer is quite complex as you can see [here](https://github.com/google-research/bigbird/blob/103a3345f94bf6364749b51189ed93024ca5ef26/bigbird/core/attention.py#L560). Don't
+feel discouraged by this! In a first step you should simply make sure that
+the layer `BigBirdAttention` has the correct weights as can be found in the
+pretrained checkpoints. This means that you have to make sure that in the
+`__init__(self, ...)` function of `BigBirdAttention`, all submodules include all
+necessary `nn.Module` layers. Only at a later stage do we need to fully rewrite
+the complex attention function.
+
+**6. Write a conversion script**
+
+Next, you should write a conversion script that lets you convert the
+checkpoint you used to debug *BigBird* in the original
+repository to a checkpoint compatible with your just created 🤗
+Transformers implementation of *BigBird*. It is not advised to
+write the conversion script from scratch, but rather to look through
+already existing conversion scripts in 🤗 Transformers for one that has
+been used to convert a similar model that was written in the same
+framework as *BigBird*. Usually, it is enough to copy an
+already existing conversion script and slightly adapt it for your use
+case. Don't hesitate to ask Patrick to point you to a
+similar already existing conversion script for your model.
+
+- A good starting point to convert the original TF BigBird implementation to the PT Hugging Face implementation is probably BERT's conversion script
+ [here](https://github.com/huggingface/transformers/blob/7acfa95afb8194f8f9c1f4d2c6028224dbed35a2/src/transformers/models/bert/modeling_bert.py#L91)
+
+You can copy paste the conversion function into `modeling_big_bird.py` and then adapt it
+to your needs.
+
+In the following, we'll quickly explain how PyTorch models store layer
+weights and define layer names. In PyTorch, the name of a layer is
+defined by the name of the class attribute you give the layer. Let's
+define a dummy model in PyTorch, called `SimpleModel` as follows:
+
+```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)
+```
+
+Now we can create an instance of this model definition which will fill
+all weights: `dense`, `intermediate`, `layer_norm` with random weights.
+We can print the model to see its architecture
+
+```python
+model = SimpleModel()
+
+print(model)
+```
+
+This will print out the following:
+
+```bash
+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)
+)
+```
+
+We can see that the layer names are defined by the name of the class
+attribute in PyTorch. You can print out the weight values of a specific
+layer:
+
+```python
+print(model.dense.weight.data)
+```
+
+to see that the weights were randomly initialized
+
+```bash
+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, you should fill those randomly initialized
+weights with the exact weights of the corresponding layer in the
+checkpoint. *E.g.*,
+
+```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)
+```
+
+While doing so, you must verify that each randomly initialized weight of
+your PyTorch model and its corresponding pretrained checkpoint weight
+exactly match in both **shape and name**. To do so, it is **necessary**
+to add assert statements for the shape and print out the names of the
+checkpoints weights. *E.g.*, you should add statements like:
+
+```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"
+```
+
+Besides, you should also print out the names of both weights to make
+sure they match, *e.g.*,
+
+```python
+logger.info(f"Initialize PyTorch weight {layer_name} from {pretrained_weight.name}")
+```
+
+If either the shape or the name doesn't match, you probably assigned
+the wrong checkpoint weight to a randomly initialized layer of the 🤗
+Transformers implementation.
+
+An incorrect shape is most likely due to an incorrect setting of the
+config parameters in `BigBirdConfig()` that do not exactly match
+those that were used for the checkpoint you want to convert. However, it
+could also be that PyTorch's implementation of a layer requires the
+weight to be transposed beforehand.
+
+Finally, you should also check that **all** required weights are
+initialized and print out all checkpoint weights that were not used for
+initialization to make sure the model is correctly converted. It is
+completely normal, that the conversion trials fail with either a wrong
+shape statement or wrong name assignment. This is most likely because
+either you used incorrect parameters in `BigBirdConfig()`, have a
+wrong architecture in the 🤗 Transformers implementation, you have a bug
+in the `init()` functions of one of the components of the 🤗 Transformers
+implementation or you need to transpose one of the checkpoint weights.
+
+This step should be iterated with the previous step until all weights of
+the checkpoint are correctly loaded in the Transformers model. Having
+correctly loaded the checkpoint into the 🤗 Transformers implementation,
+you can then save the model under a folder of your choice
+`/path/to/converted/checkpoint/folder` that should then contain both a
+`pytorch_model.bin` file and a `config.json` file:
+
+```python
+model.save_pretrained("/path/to/converted/checkpoint/folder")
+```
+
+**7. Implement the forward pass**
+
+Having managed to correctly load the pretrained weights into the 🤗
+Transformers implementation, you should now make sure that the forward
+pass is correctly implemented. In [Get familiar with the original
+repository](#run-a-pretrained-checkpoint-using-the-original-repository),
+you have already created a script that runs a forward pass of the model
+using the original repository. Now you should write an analogous script
+using the 🤗 Transformers implementation instead of the original one. It
+should look as follows:
+
+[Here the model name might have to be adapted, *e.g.*, maybe BigBirdForConditionalGeneration instead of BigBirdModel]
+
+```python
+model = BigBirdModel.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
+```
+
+It is very likely that the 🤗 Transformers implementation and the
+original model implementation don't give the exact same output the very
+first time or that the forward pass throws an error. Don't be
+disappointed - it's expected! First, you should make sure that the
+forward pass doesn't throw any errors. It often happens that the wrong
+dimensions are used leading to a `"Dimensionality mismatch"`
+error or that the wrong data type object is used, *e.g.*, `torch.long`
+instead of `torch.float32`. Don't hesitate to ask Patrick
+for help, if you don't manage to solve certain errors.
+
+The final part to make sure the 🤗 Transformers implementation works
+correctly is to ensure that the outputs are equivalent to a precision of
+`1e-3`. First, you should ensure that the output shapes are identical,
+*i.e.* `outputs.shape` should yield the same value for the script of the
+🤗 Transformers implementation and the original implementation. Next, you
+should make sure that the output values are identical as well. This one
+of the most difficult parts of adding a new model. Common mistakes why
+the outputs are not identical are:
+
+- Some layers were not added, *i.e.* an activation layer
+ was not added, or the residual connection was forgotten
+- The word embedding matrix was not tied
+- The wrong positional embeddings are used because the original
+ implementation uses on offset
+- Dropout is applied during the forward pass. To fix this make sure
+ `model.training is False` and that no dropout layer is
+ falsely activated during the forward pass, *i.e.* pass
+ `self.training` to [PyTorch's functional
+ dropout](https://pytorch.org/docs/stable/nn.functional.html?highlight=dropout#torch.nn.functional.dropout)
+
+The best way to fix the problem is usually to look at the forward pass
+of the original implementation and the 🤗 Transformers implementation
+side-by-side and check if there are any differences. Ideally, you should
+debug/print out intermediate outputs of both implementations of the
+forward pass to find the exact position in the network where the 🤗
+Transformers implementation shows a different output than the original
+implementation. First, make sure that the hard-coded `input_ids` in both
+scripts are identical. Next, verify that the outputs of the first
+transformation of the `input_ids` (usually the word embeddings) are
+identical. And then work your way up to the very last layer of the
+network. At some point, you will notice a difference between the two
+implementations, which should point you to the bug in the 🤗 Transformers
+implementation. From our experience, a simple and efficient way is to
+add many print statements in both the original implementation and 🤗
+Transformers implementation, at the same positions in the network
+respectively, and to successively remove print statements showing the
+same values for intermediate presentions.
+
+When you're confident that both implementations yield the same output,
+verifying the outputs with
+`torch.allclose(original_output, output, atol=1e-3)`, you're done with
+the most difficult part! Congratulations - the work left to be done
+should be a cakewalk 😊.
+
+**8. Adding all necessary model tests**
+
+At this point, you have successfully added a new model. However, it is
+very much possible that the model does not yet fully comply with the
+required design. To make sure, the implementation is fully compatible
+with 🤗 Transformers, all common tests should pass. The Cookiecutter
+should have automatically added a test file for your model, probably
+under the same `tests/test_modeling_big_bird.py`. Run this test
+file to verify that all common tests pass:
+
+```python
+pytest tests/test_modeling_big_bird.py
+```
+
+Having fixed all common tests, it is now crucial to ensure that all the
+nice work you have done is well tested, so that
+
+- a) The community can easily understand your work by looking at
+ specific tests of *BigBird*
+
+- b) Future changes to your model will not break any important
+ feature of the model.
+
+At first, integration tests should be added. Those integration tests
+essentially do the same as the debugging scripts you used earlier to
+implement the model to 🤗 Transformers. A template of those model tests
+is already added by the Cookiecutter, called
+`BigBirdModelIntegrationTests` and only has to be filled out by
+you. To ensure that those tests are passing, run
+
+```python
+RUN_SLOW=1 pytest -sv tests/test_modeling_big_bird.py::BigBirdModelIntegrationTests
+```
+
+**Note**: In case you are using Windows, you should replace `RUN_SLOW=1` with
+`SET RUN_SLOW=1`
+
+Second, all features that are special to *BigBird* should be
+tested additionally in a separate test under
+`BigBirdModelTester`/`BigBirdModelTest`. This part is often
+forgotten but is extremely useful in two ways:
+
+- It helps to transfer the knowledge you have acquired during the
+ model addition to the community by showing how the special features
+ of *BigBird* should work.
+- Future contributors can quickly test changes to the model by running
+ those special tests.
+
+BigBird has quite a complex attention layer, so it is very important
+to add more tests verifying the all parts of BigBird's self-attention layer
+works as expected. This means that there should be at least 3 additional tests:
+
+- 1. Verify that the sparse attention works correctly
+- 2. Verify that the global attention works correctly
+- 3. Verify that the random attention works correctly
+
+**9. Implement the tokenizer**
+
+Next, we should add the tokenizer of *BigBird*. Usually, the
+tokenizer is equivalent or very similar to an already existing tokenizer
+of 🤗 Transformers.
+
+In the case of BigBird you should be able to just rely on an already existing tokenizer.
+If not mistaken, BigBird uses the same tokenizer that was used for `BertGenerationTokenizer`,
+which is based on `sentencepiece`. So you should be able to just set the config parameter
+`tokenizer_class` to `BertGenerationTokenizer` without having to implement any new tokenizer.
+
+It is very important to find/extract the original tokenizer file and to
+manage to load this file into the 🤗 Transformers' implementation of the
+tokenizer.
+
+For BigBird, the tokenizer (sentencepiece) files can be found [here](https://github.com/google-research/bigbird/blob/master/bigbird/vocab/gpt2.model), which you should be able to load
+as easily as:
+
+```python
+from transformers import BertGenerationTokenizer
+tokenizer = BertGenerationTokenizer("/path/to/gpt2.model/file")
+```
+
+To ensure that the tokenizer works correctly, it is recommended to first
+create a script in the original repository that inputs a string and
+returns the `input_ids`. It could look similar to this (in pseudo-code):
+
+```bash
+input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words."
+model = BigBirdModel.load_pretrained_checkpoint("/path/to/checkpoint/")
+input_ids = model.tokenize(input_str)
+```
+
+You might have to take a deeper look again into the original repository
+to find the correct tokenizer function or you might even have to do
+changes to your clone of the original repository to only output the
+`input_ids`. Having written a functional tokenization script that uses
+the original repository, an analogous script for 🤗 Transformers should
+be created. It should look similar to this:
+
+```python
+from transformers import BertGenerationTokenizer
+input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words."
+
+tokenizer = BertGenerationTokenizer.from_pretrained("/path/big/bird/folder")
+
+input_ids = tokenizer(input_str).input_ids
+```
+
+When both `input_ids` yield the same values, as a final step a tokenizer
+test file should also be added.
+
+Since BigBird is most likely fully based on `BertGenerationTokenizer`,
+you should only add a couple of "slow" integration tests. However, in this
+case you do **not** need to add any `BigBirdTokenizationTest`.
+
+**10. Run End-to-end integration tests**
+
+Having added the tokenizer, you should also add a couple of end-to-end
+integration tests using both the model and the tokenizer to
+`tests/test_modeling_big_bird.py` in 🤗 Transformers. Such a test
+should show on a meaningful text-to-text sample that the 🤗 Transformers
+implementation works as expected. A meaningful text-to-text sample can
+include, *e.g.*, a source-to-target-translation pair, an
+article-to-summary pair, a question-to-answer pair, etc... If none of
+the ported checkpoints has been fine-tuned on a downstream task it is
+enough to simply rely on the model tests. In a final step to ensure that
+the model is fully functional, it is advised that you also run all tests
+on GPU. It can happen that you forgot to add some `.to(self.device)`
+statements to internal tensors of the model, which in such a test would
+show in an error. In case you have no access to a GPU, the Hugging Face
+team can take care of running those tests for you.
+
+**11. Add Docstring**
+
+Now, all the necessary functionality for *BigBird* is added -
+you're almost done! The only thing left to add is a nice docstring and
+a doc page. The Cookiecutter should have added a template file called
+`docs/source/model_doc/big_bird.rst` that you should fill out.
+Users of your model will usually first look at this page before using
+your model. Hence, the documentation must be understandable and concise.
+It is very useful for the community to add some *Tips* to show how the
+model should be used. Don't hesitate to ping Patrick
+regarding the docstrings.
+
+Next, make sure that the docstring added to
+`src/transformers/models/big_bird/modeling_big_bird.py` is
+correct and included all necessary inputs and outputs. It is always to
+good to remind oneself that documentation should be treated at least as
+carefully as the code in 🤗 Transformers since the documentation is
+usually the first contact point of the community with the model.
+
+**Code refactor**
+
+Great, now you have added all the necessary code for *BigBird*.
+At this point, you should correct some potential incorrect code style by
+running:
+
+```bash
+make style
+```
+
+and verify that your coding style passes the quality check:
+
+```bash
+make quality
+```
+
+There are a couple of other very strict design tests in 🤗 Transformers
+that might still be failing, which shows up in the tests of your pull
+request. This is often because of some missing information in the
+docstring or some incorrect naming. Patrick will surely
+help you if you're stuck here.
+
+Lastly, it is always a good idea to refactor one's code after having
+ensured that the code works correctly. With all tests passing, now it's
+a good time to go over the added code again and do some refactoring.
+
+You have now finished the coding part, congratulation! 🎉 You are
+Awesome! 😎
+
+**12. Upload the models to the model hub**
+
+In this final part, you should convert and upload all checkpoints to the
+model hub and add a model card for each uploaded model checkpoint. You
+should work alongside Patrick here to decide on a fitting
+name for each checkpoint and to get the required access rights to be
+able to upload the model under the author's organization of
+*BigBird*.
+
+It is worth spending some time to create fitting model cards for each
+checkpoint. The model cards should highlight the specific
+characteristics of this particular checkpoint, *e.g.*, On which dataset
+was the checkpoint pretrained/fine-tuned on? On what down-stream task
+should the model be used? And also include some code on how to correctly
+use the model.
+
+**13. (Optional) Add notebook**
+
+It is very helpful to add a notebook that showcases in-detail how
+*BigBird* can be used for inference and/or fine-tuned on a
+downstream task. This is not mandatory to merge your PR, but very useful
+for the community.
+
+**14. Submit your finished PR**
+
+You're done programming now and can move to the last step, which is
+getting your PR merged into main. Usually, Patrick
+should have helped you already at this point, but it is worth taking
+some time to give your finished PR a nice description and eventually add
+comments to your code, if you want to point out certain design choices
+to your reviewer.
+
+### Share your work!!
+
+Now, it's time to get some credit from the community for your work!
+Having completed a model addition is a major contribution to
+Transformers and the whole NLP community. Your code and the ported
+pre-trained models will certainly be used by hundreds and possibly even
+thousands of developers and researchers. You should be proud of your
+work and share your achievement with the community.
+
+**You have made another model that is super easy to access for everyone
+in the community! 🤯**
diff --git a/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_model/open_model_proposals/README.md b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_model/open_model_proposals/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..dd254209f007540e9607c83b887065e9ad46fe85
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/templates/adding_a_new_model/open_model_proposals/README.md
@@ -0,0 +1,3 @@
+Currently the following model proposals are available:
+
+- [BigBird (Google)](./ADD_BIG_BIRD.md)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/__init__.py b/tasks/tasksmith-441eeab80047/tests/source/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/agents/__init__.py b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_agent_types.py b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_agent_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fb56417d5c3e1cf1d6946a8bac8fd253c0834ba
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_agent_types.py
@@ -0,0 +1,121 @@
+# coding=utf-8
+# Copyright 2023 HuggingFace Inc.
+#
+# 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 tempfile
+import unittest
+import uuid
+from pathlib import Path
+
+from transformers.agents.agent_types import AgentAudio, AgentImage, AgentText
+from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision
+from transformers.utils import is_soundfile_available, is_torch_available, is_vision_available
+
+
+if is_torch_available():
+ import torch
+
+if is_soundfile_available():
+ import soundfile as sf
+
+if is_vision_available():
+ from PIL import Image
+
+
+def get_new_path(suffix="") -> str:
+ directory = tempfile.mkdtemp()
+ return os.path.join(directory, str(uuid.uuid4()) + suffix)
+
+
+@require_soundfile
+@require_torch
+class AgentAudioTests(unittest.TestCase):
+ def test_from_tensor(self):
+ tensor = torch.rand(12, dtype=torch.float64) - 0.5
+ agent_type = AgentAudio(tensor)
+ path = str(agent_type.to_string())
+
+ # Ensure that the tensor and the agent_type's tensor are the same
+ torch.testing.assert_close(tensor, agent_type.to_raw(), rtol=1e-4, atol=1e-4)
+
+ del agent_type
+
+ # Ensure the path remains even after the object deletion
+ self.assertTrue(os.path.exists(path))
+
+ # Ensure that the file contains the same value as the original tensor
+ new_tensor, _ = sf.read(path)
+ torch.testing.assert_close(tensor, torch.tensor(new_tensor), rtol=1e-4, atol=1e-4)
+
+ def test_from_string(self):
+ tensor = torch.rand(12, dtype=torch.float64) - 0.5
+ path = get_new_path(suffix=".wav")
+ sf.write(path, tensor, 16000)
+
+ agent_type = AgentAudio(path)
+
+ torch.testing.assert_close(tensor, agent_type.to_raw(), rtol=1e-4, atol=1e-4)
+ self.assertEqual(agent_type.to_string(), path)
+
+
+@require_vision
+@require_torch
+class AgentImageTests(unittest.TestCase):
+ def test_from_tensor(self):
+ tensor = torch.randint(0, 256, (64, 64, 3))
+ agent_type = AgentImage(tensor)
+ path = str(agent_type.to_string())
+
+ # Ensure that the tensor and the agent_type's tensor are the same
+ torch.testing.assert_close(tensor, agent_type._tensor, rtol=1e-4, atol=1e-4)
+
+ self.assertIsInstance(agent_type.to_raw(), Image.Image)
+
+ # Ensure the path remains even after the object deletion
+ del agent_type
+ self.assertTrue(os.path.exists(path))
+
+ def test_from_string(self):
+ path = Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png"
+ image = Image.open(path)
+ agent_type = AgentImage(path)
+
+ self.assertTrue(path.samefile(agent_type.to_string()))
+ self.assertTrue(image == agent_type.to_raw())
+
+ # Ensure the path remains even after the object deletion
+ del agent_type
+ self.assertTrue(os.path.exists(path))
+
+ def test_from_image(self):
+ path = Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png"
+ image = Image.open(path)
+ agent_type = AgentImage(image)
+
+ self.assertFalse(path.samefile(agent_type.to_string()))
+ self.assertTrue(image == agent_type.to_raw())
+
+ # Ensure the path remains even after the object deletion
+ del agent_type
+ self.assertTrue(os.path.exists(path))
+
+
+class AgentTextTests(unittest.TestCase):
+ def test_from_string(self):
+ string = "Hey!"
+ agent_type = AgentText(string)
+
+ self.assertEqual(string, agent_type.to_string())
+ self.assertEqual(string, agent_type.to_raw())
+ self.assertEqual(string, agent_type)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_agents.py b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_agents.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f24abbeedd8f183ed108ddd8ee9d2b7d4cd7238
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_agents.py
@@ -0,0 +1,258 @@
+# coding=utf-8
+# Copyright 2024 HuggingFace Inc.
+#
+# 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 tempfile
+import unittest
+import uuid
+
+import pytest
+
+from transformers.agents.agent_types import AgentText
+from transformers.agents.agents import (
+ AgentMaxIterationsError,
+ CodeAgent,
+ ManagedAgent,
+ ReactCodeAgent,
+ ReactJsonAgent,
+ Toolbox,
+)
+from transformers.agents.default_tools import PythonInterpreterTool
+from transformers.testing_utils import require_torch
+
+
+def get_new_path(suffix="") -> str:
+ directory = tempfile.mkdtemp()
+ return os.path.join(directory, str(uuid.uuid4()) + suffix)
+
+
+def fake_react_json_llm(messages, stop_sequences=None, grammar=None) -> str:
+ prompt = str(messages)
+
+ if "special_marker" not in prompt:
+ return """
+Thought: I should multiply 2 by 3.6452. special_marker
+Action:
+{
+ "action": "python_interpreter",
+ "action_input": {"code": "2*3.6452"}
+}
+"""
+ else: # We're at step 2
+ return """
+Thought: I can now answer the initial question
+Action:
+{
+ "action": "final_answer",
+ "action_input": {"answer": "7.2904"}
+}
+"""
+
+
+def fake_react_code_llm(messages, stop_sequences=None, grammar=None) -> str:
+ prompt = str(messages)
+ if "special_marker" not in prompt:
+ return """
+Thought: I should multiply 2 by 3.6452. special_marker
+Code:
+```py
+result = 2**3.6452
+```
+"""
+ else: # We're at step 2
+ return """
+Thought: I can now answer the initial question
+Code:
+```py
+final_answer(7.2904)
+```
+"""
+
+
+def fake_react_code_llm_error(messages, stop_sequences=None) -> str:
+ prompt = str(messages)
+ if "special_marker" not in prompt:
+ return """
+Thought: I should multiply 2 by 3.6452. special_marker
+Code:
+```py
+print = 2
+```
+"""
+ else: # We're at step 2
+ return """
+Thought: I can now answer the initial question
+Code:
+```py
+final_answer("got an error")
+```
+"""
+
+
+def fake_react_code_functiondef(messages, stop_sequences=None) -> str:
+ prompt = str(messages)
+ if "special_marker" not in prompt:
+ return """
+Thought: Let's define the function. special_marker
+Code:
+```py
+import numpy as np
+
+def moving_average(x, w):
+ return np.convolve(x, np.ones(w), 'valid') / w
+```
+"""
+ else: # We're at step 2
+ return """
+Thought: I can now answer the initial question
+Code:
+```py
+x, w = [0, 1, 2, 3, 4, 5], 2
+res = moving_average(x, w)
+final_answer(res)
+```
+"""
+
+
+def fake_code_llm_oneshot(messages, stop_sequences=None, grammar=None) -> str:
+ return """
+Thought: I should multiply 2 by 3.6452. special_marker
+Code:
+```py
+result = python_interpreter(code="2*3.6452")
+final_answer(result)
+```
+"""
+
+
+def fake_code_llm_no_return(messages, stop_sequences=None, grammar=None) -> str:
+ return """
+Thought: I should multiply 2 by 3.6452. special_marker
+Code:
+```py
+result = python_interpreter(code="2*3.6452")
+print(result)
+```
+"""
+
+
+class AgentTests(unittest.TestCase):
+ def test_fake_code_agent(self):
+ agent = CodeAgent(tools=[PythonInterpreterTool()], llm_engine=fake_code_llm_oneshot)
+ output = agent.run("What is 2 multiplied by 3.6452?")
+ assert isinstance(output, str)
+ assert output == "7.2904"
+
+ def test_fake_react_json_agent(self):
+ agent = ReactJsonAgent(tools=[PythonInterpreterTool()], llm_engine=fake_react_json_llm)
+ output = agent.run("What is 2 multiplied by 3.6452?")
+ assert isinstance(output, str)
+ assert output == "7.2904"
+ assert agent.logs[0]["task"] == "What is 2 multiplied by 3.6452?"
+ assert agent.logs[1]["observation"] == "7.2904"
+ assert agent.logs[1]["rationale"].strip() == "Thought: I should multiply 2 by 3.6452. special_marker"
+ assert (
+ agent.logs[2]["llm_output"]
+ == """
+Thought: I can now answer the initial question
+Action:
+{
+ "action": "final_answer",
+ "action_input": {"answer": "7.2904"}
+}
+"""
+ )
+
+ def test_fake_react_code_agent(self):
+ agent = ReactCodeAgent(tools=[PythonInterpreterTool()], llm_engine=fake_react_code_llm)
+ output = agent.run("What is 2 multiplied by 3.6452?")
+ assert isinstance(output, float)
+ assert output == 7.2904
+ assert agent.logs[0]["task"] == "What is 2 multiplied by 3.6452?"
+ assert agent.logs[2]["tool_call"] == {
+ "tool_arguments": "final_answer(7.2904)",
+ "tool_name": "code interpreter",
+ }
+
+ def test_react_code_agent_code_errors_show_offending_lines(self):
+ agent = ReactCodeAgent(tools=[PythonInterpreterTool()], llm_engine=fake_react_code_llm_error)
+ output = agent.run("What is 2 multiplied by 3.6452?")
+ assert isinstance(output, AgentText)
+ assert output == "got an error"
+ assert "Evaluation stopped at line 'print = 2' because of" in str(agent.logs)
+
+ def test_setup_agent_with_empty_toolbox(self):
+ ReactJsonAgent(llm_engine=fake_react_json_llm, tools=[])
+
+ def test_react_fails_max_iterations(self):
+ agent = ReactCodeAgent(
+ tools=[PythonInterpreterTool()],
+ llm_engine=fake_code_llm_no_return, # use this callable because it never ends
+ max_iterations=5,
+ )
+ agent.run("What is 2 multiplied by 3.6452?")
+ assert len(agent.logs) == 7
+ assert type(agent.logs[-1]["error"]) is AgentMaxIterationsError
+
+ @require_torch
+ def test_init_agent_with_different_toolsets(self):
+ toolset_1 = []
+ agent = ReactCodeAgent(tools=toolset_1, llm_engine=fake_react_code_llm)
+ assert (
+ len(agent.toolbox.tools) == 1
+ ) # when no tools are provided, only the final_answer tool is added by default
+
+ toolset_2 = [PythonInterpreterTool(), PythonInterpreterTool()]
+ agent = ReactCodeAgent(tools=toolset_2, llm_engine=fake_react_code_llm)
+ assert (
+ len(agent.toolbox.tools) == 2
+ ) # deduplication of tools, so only one python_interpreter tool is added in addition to final_answer
+
+ toolset_3 = Toolbox(toolset_2)
+ agent = ReactCodeAgent(tools=toolset_3, llm_engine=fake_react_code_llm)
+ assert (
+ len(agent.toolbox.tools) == 2
+ ) # same as previous one, where toolset_3 is an instantiation of previous one
+
+ # check that add_base_tools will not interfere with existing tools
+ with pytest.raises(KeyError) as e:
+ agent = ReactJsonAgent(tools=toolset_3, llm_engine=fake_react_json_llm, add_base_tools=True)
+ assert "already exists in the toolbox" in str(e)
+
+ # check that python_interpreter base tool does not get added to code agents
+ agent = ReactCodeAgent(tools=[], llm_engine=fake_react_code_llm, add_base_tools=True)
+ assert len(agent.toolbox.tools) == 7 # added final_answer tool + 6 base tools (excluding interpreter)
+
+ def test_function_persistence_across_steps(self):
+ agent = ReactCodeAgent(
+ tools=[], llm_engine=fake_react_code_functiondef, max_iterations=2, additional_authorized_imports=["numpy"]
+ )
+ res = agent.run("ok")
+ assert res[0] == 0.5
+
+ def test_init_managed_agent(self):
+ agent = ReactCodeAgent(tools=[], llm_engine=fake_react_code_functiondef)
+ managed_agent = ManagedAgent(agent, name="managed_agent", description="Empty")
+ assert managed_agent.name == "managed_agent"
+ assert managed_agent.description == "Empty"
+
+ def test_agent_description_gets_correctly_inserted_in_system_prompt(self):
+ agent = ReactCodeAgent(tools=[], llm_engine=fake_react_code_functiondef)
+ managed_agent = ManagedAgent(agent, name="managed_agent", description="Empty")
+ manager_agent = ReactCodeAgent(
+ tools=[], llm_engine=fake_react_code_functiondef, managed_agents=[managed_agent]
+ )
+ assert "You can also give requests to team members." not in agent.system_prompt
+ assert "<>" not in agent.system_prompt
+ assert "You can also give requests to team members." in manager_agent.system_prompt
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_document_question_answering.py b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_document_question_answering.py
new file mode 100644
index 0000000000000000000000000000000000000000..d135551084bc97f1ee2b5f4c9b79c41470d31d04
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_document_question_answering.py
@@ -0,0 +1,41 @@
+# coding=utf-8
+# Copyright 2023 HuggingFace Inc.
+#
+# 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 unittest
+
+from datasets import load_dataset
+
+from transformers import load_tool
+
+from .test_tools_common import ToolTesterMixin
+
+
+class DocumentQuestionAnsweringToolTester(unittest.TestCase, ToolTesterMixin):
+ def setUp(self):
+ self.tool = load_tool("document_question_answering")
+ self.tool.setup()
+
+ def test_exact_match_arg(self):
+ dataset = load_dataset("hf-internal-testing/example-documents", split="test")
+ document = dataset[0]["image"]
+
+ result = self.tool(document, "When is the coffee break?")
+ self.assertEqual(result, "11-14 to 11:39 a.m.")
+
+ def test_exact_match_kwarg(self):
+ dataset = load_dataset("hf-internal-testing/example-documents", split="test")
+ document = dataset[0]["image"]
+
+ self.tool(document=document, question="When is the coffee break?")
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_final_answer.py b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_final_answer.py
new file mode 100644
index 0000000000000000000000000000000000000000..91bdd65e89a822a5ee457360dbacde69e64e3b52
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_final_answer.py
@@ -0,0 +1,71 @@
+# coding=utf-8
+# Copyright 2024 HuggingFace Inc.
+#
+# 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 unittest
+from pathlib import Path
+
+import numpy as np
+from PIL import Image
+
+from transformers import is_torch_available
+from transformers.agents.agent_types import AGENT_TYPE_MAPPING
+from transformers.agents.default_tools import FinalAnswerTool
+from transformers.testing_utils import get_tests_dir, require_torch
+
+from .test_tools_common import ToolTesterMixin
+
+
+if is_torch_available():
+ import torch
+
+
+class FinalAnswerToolTester(unittest.TestCase, ToolTesterMixin):
+ def setUp(self):
+ self.inputs = {"answer": "Final answer"}
+ self.tool = FinalAnswerTool()
+
+ def test_exact_match_arg(self):
+ result = self.tool("Final answer")
+ self.assertEqual(result, "Final answer")
+
+ def test_exact_match_kwarg(self):
+ result = self.tool(answer=self.inputs["answer"])
+ self.assertEqual(result, "Final answer")
+
+ def create_inputs(self):
+ inputs_text = {"answer": "Text input"}
+ inputs_image = {
+ "answer": Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png").resize(
+ (512, 512)
+ )
+ }
+ inputs_audio = {"answer": torch.Tensor(np.ones(3000))}
+ return {"string": inputs_text, "image": inputs_image, "audio": inputs_audio}
+
+ @require_torch
+ def test_agent_type_output(self):
+ inputs = self.create_inputs()
+ for input_type, input in inputs.items():
+ output = self.tool(**input)
+ agent_type = AGENT_TYPE_MAPPING[input_type]
+ self.assertTrue(isinstance(output, agent_type))
+
+ @require_torch
+ def test_agent_types_inputs(self):
+ inputs = self.create_inputs()
+ for input_type, input in inputs.items():
+ output = self.tool(**input)
+ agent_type = AGENT_TYPE_MAPPING[input_type]
+ self.assertTrue(isinstance(output, agent_type))
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_image_question_answering.py b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_image_question_answering.py
new file mode 100644
index 0000000000000000000000000000000000000000..405933e78a1156ebbf1834886c32f82e034ae723
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_image_question_answering.py
@@ -0,0 +1,42 @@
+# coding=utf-8
+# Copyright 2023 HuggingFace Inc.
+#
+# 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 unittest
+from pathlib import Path
+
+from transformers import is_vision_available, load_tool
+from transformers.testing_utils import get_tests_dir
+
+from .test_tools_common import ToolTesterMixin
+
+
+if is_vision_available():
+ from PIL import Image
+
+
+class ImageQuestionAnsweringToolTester(unittest.TestCase, ToolTesterMixin):
+ def setUp(self):
+ self.tool = load_tool("image_question_answering")
+ self.tool.setup()
+
+ def test_exact_match_arg(self):
+ image = Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png")
+ result = self.tool(image, "How many cats are sleeping on the couch?")
+ self.assertEqual(result, "2")
+
+ def test_exact_match_kwarg(self):
+ image = Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png")
+ result = self.tool(image=image, question="How many cats are sleeping on the couch?")
+ self.assertEqual(result, "2")
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_monitoring.py b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_monitoring.py
new file mode 100644
index 0000000000000000000000000000000000000000..c35074270ea272136abfa52b4956e477f752801c
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_monitoring.py
@@ -0,0 +1,166 @@
+# coding=utf-8
+# Copyright 2024 HuggingFace Inc.
+#
+# 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 unittest
+
+from transformers.agents.agent_types import AgentImage
+from transformers.agents.agents import AgentError, ReactCodeAgent, ReactJsonAgent
+from transformers.agents.monitoring import stream_to_gradio
+
+
+class MonitoringTester(unittest.TestCase):
+ def test_code_agent_metrics(self):
+ class FakeLLMEngine:
+ def __init__(self):
+ self.last_input_token_count = 10
+ self.last_output_token_count = 20
+
+ def __call__(self, prompt, **kwargs):
+ return """
+Code:
+```py
+final_answer('This is the final answer.')
+```"""
+
+ agent = ReactCodeAgent(
+ tools=[],
+ llm_engine=FakeLLMEngine(),
+ max_iterations=1,
+ )
+
+ agent.run("Fake task")
+
+ self.assertEqual(agent.monitor.total_input_token_count, 10)
+ self.assertEqual(agent.monitor.total_output_token_count, 20)
+
+ def test_json_agent_metrics(self):
+ class FakeLLMEngine:
+ def __init__(self):
+ self.last_input_token_count = 10
+ self.last_output_token_count = 20
+
+ def __call__(self, prompt, **kwargs):
+ return 'Action:{"action": "final_answer", "action_input": {"answer": "image"}}'
+
+ agent = ReactJsonAgent(
+ tools=[],
+ llm_engine=FakeLLMEngine(),
+ max_iterations=1,
+ )
+
+ agent.run("Fake task")
+
+ self.assertEqual(agent.monitor.total_input_token_count, 10)
+ self.assertEqual(agent.monitor.total_output_token_count, 20)
+
+ def test_code_agent_metrics_max_iterations(self):
+ class FakeLLMEngine:
+ def __init__(self):
+ self.last_input_token_count = 10
+ self.last_output_token_count = 20
+
+ def __call__(self, prompt, **kwargs):
+ return "Malformed answer"
+
+ agent = ReactCodeAgent(
+ tools=[],
+ llm_engine=FakeLLMEngine(),
+ max_iterations=1,
+ )
+
+ agent.run("Fake task")
+
+ self.assertEqual(agent.monitor.total_input_token_count, 20)
+ self.assertEqual(agent.monitor.total_output_token_count, 40)
+
+ def test_code_agent_metrics_generation_error(self):
+ class FakeLLMEngine:
+ def __init__(self):
+ self.last_input_token_count = 10
+ self.last_output_token_count = 20
+
+ def __call__(self, prompt, **kwargs):
+ raise AgentError
+
+ agent = ReactCodeAgent(
+ tools=[],
+ llm_engine=FakeLLMEngine(),
+ max_iterations=1,
+ )
+
+ agent.run("Fake task")
+
+ self.assertEqual(agent.monitor.total_input_token_count, 20)
+ self.assertEqual(agent.monitor.total_output_token_count, 40)
+
+ def test_streaming_agent_text_output(self):
+ def dummy_llm_engine(prompt, **kwargs):
+ return """
+Code:
+```py
+final_answer('This is the final answer.')
+```"""
+
+ agent = ReactCodeAgent(
+ tools=[],
+ llm_engine=dummy_llm_engine,
+ max_iterations=1,
+ )
+
+ # Use stream_to_gradio to capture the output
+ outputs = list(stream_to_gradio(agent, task="Test task", test_mode=True))
+
+ self.assertEqual(len(outputs), 3)
+ final_message = outputs[-1]
+ self.assertEqual(final_message.role, "assistant")
+ self.assertIn("This is the final answer.", final_message.content)
+
+ def test_streaming_agent_image_output(self):
+ def dummy_llm_engine(prompt, **kwargs):
+ return 'Action:{"action": "final_answer", "action_input": {"answer": "image"}}'
+
+ agent = ReactJsonAgent(
+ tools=[],
+ llm_engine=dummy_llm_engine,
+ max_iterations=1,
+ )
+
+ # Use stream_to_gradio to capture the output
+ outputs = list(stream_to_gradio(agent, task="Test task", image=AgentImage(value="path.png"), test_mode=True))
+
+ self.assertEqual(len(outputs), 2)
+ final_message = outputs[-1]
+ self.assertEqual(final_message.role, "assistant")
+ self.assertIsInstance(final_message.content, dict)
+ self.assertEqual(final_message.content["path"], "path.png")
+ self.assertEqual(final_message.content["mime_type"], "image/png")
+
+ def test_streaming_with_agent_error(self):
+ def dummy_llm_engine(prompt, **kwargs):
+ raise AgentError("Simulated agent error")
+
+ agent = ReactCodeAgent(
+ tools=[],
+ llm_engine=dummy_llm_engine,
+ max_iterations=1,
+ )
+
+ # Use stream_to_gradio to capture the output
+ outputs = list(stream_to_gradio(agent, task="Test task", test_mode=True))
+
+ self.assertEqual(len(outputs), 3)
+ final_message = outputs[-1]
+ self.assertEqual(final_message.role, "assistant")
+ self.assertIn("Simulated agent error", final_message.content)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_python_interpreter.py b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_python_interpreter.py
new file mode 100644
index 0000000000000000000000000000000000000000..15e5ad7bb3a3c78516eee3ea2070bdaaa607234e
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_python_interpreter.py
@@ -0,0 +1,837 @@
+# coding=utf-8
+# Copyright 2024 HuggingFace Inc.
+#
+# 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 unittest
+
+import numpy as np
+import pytest
+
+from transformers import load_tool
+from transformers.agents.agent_types import AGENT_TYPE_MAPPING
+from transformers.agents.default_tools import BASE_PYTHON_TOOLS
+from transformers.agents.python_interpreter import InterpreterError, evaluate_python_code
+
+from .test_tools_common import ToolTesterMixin
+
+
+# Fake function we will use as tool
+def add_two(x):
+ return x + 2
+
+
+class PythonInterpreterToolTester(unittest.TestCase, ToolTesterMixin):
+ def setUp(self):
+ self.tool = load_tool("python_interpreter", authorized_imports=["sqlite3"])
+ self.tool.setup()
+
+ def test_exact_match_arg(self):
+ result = self.tool("(2 / 2) * 4")
+ self.assertEqual(result, "4.0")
+
+ def test_exact_match_kwarg(self):
+ result = self.tool(code="(2 / 2) * 4")
+ self.assertEqual(result, "4.0")
+
+ def test_agent_type_output(self):
+ inputs = ["2 * 2"]
+ output = self.tool(*inputs)
+ output_type = AGENT_TYPE_MAPPING[self.tool.output_type]
+ self.assertTrue(isinstance(output, output_type))
+
+ def test_agent_types_inputs(self):
+ inputs = ["2 * 2"]
+ _inputs = []
+
+ for _input, expected_input in zip(inputs, self.tool.inputs.values()):
+ input_type = expected_input["type"]
+ if isinstance(input_type, list):
+ _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input) for _input_type in input_type])
+ else:
+ _inputs.append(AGENT_TYPE_MAPPING[input_type](_input))
+
+ # Should not raise an error
+ output = self.tool(*inputs)
+ output_type = AGENT_TYPE_MAPPING[self.tool.output_type]
+ self.assertTrue(isinstance(output, output_type))
+
+
+class PythonInterpreterTester(unittest.TestCase):
+ def test_evaluate_assign(self):
+ code = "x = 3"
+ state = {}
+ result = evaluate_python_code(code, {}, state=state)
+ assert result == 3
+ self.assertDictEqual(state, {"x": 3, "print_outputs": ""})
+
+ code = "x = y"
+ state = {"y": 5}
+ result = evaluate_python_code(code, {}, state=state)
+ # evaluate returns the value of the last assignment.
+ assert result == 5
+ self.assertDictEqual(state, {"x": 5, "y": 5, "print_outputs": ""})
+
+ code = "a=1;b=None"
+ result = evaluate_python_code(code, {}, state={})
+ # evaluate returns the value of the last assignment.
+ assert result is None
+
+ def test_assignment_cannot_overwrite_tool(self):
+ code = "print = '3'"
+ with pytest.raises(InterpreterError) as e:
+ evaluate_python_code(code, {"print": print}, state={})
+ assert "Cannot assign to name 'print': doing this would erase the existing tool!" in str(e)
+
+ def test_evaluate_call(self):
+ code = "y = add_two(x)"
+ state = {"x": 3}
+ result = evaluate_python_code(code, {"add_two": add_two}, state=state)
+ assert result == 5
+ self.assertDictEqual(state, {"x": 3, "y": 5, "print_outputs": ""})
+
+ # Should not work without the tool
+ with pytest.raises(InterpreterError) as e:
+ evaluate_python_code(code, {}, state=state)
+ assert "tried to execute add_two" in str(e.value)
+
+ def test_evaluate_constant(self):
+ code = "x = 3"
+ state = {}
+ result = evaluate_python_code(code, {}, state=state)
+ assert result == 3
+ self.assertDictEqual(state, {"x": 3, "print_outputs": ""})
+
+ def test_evaluate_dict(self):
+ code = "test_dict = {'x': x, 'y': add_two(x)}"
+ state = {"x": 3}
+ result = evaluate_python_code(code, {"add_two": add_two}, state=state)
+ self.assertDictEqual(result, {"x": 3, "y": 5})
+ self.assertDictEqual(state, {"x": 3, "test_dict": {"x": 3, "y": 5}, "print_outputs": ""})
+
+ def test_evaluate_expression(self):
+ code = "x = 3\ny = 5"
+ state = {}
+ result = evaluate_python_code(code, {}, state=state)
+ # evaluate returns the value of the last assignment.
+ assert result == 5
+ self.assertDictEqual(state, {"x": 3, "y": 5, "print_outputs": ""})
+
+ def test_evaluate_f_string(self):
+ code = "text = f'This is x: {x}.'"
+ state = {"x": 3}
+ result = evaluate_python_code(code, {}, state=state)
+ # evaluate returns the value of the last assignment.
+ assert result == "This is x: 3."
+ self.assertDictEqual(state, {"x": 3, "text": "This is x: 3.", "print_outputs": ""})
+
+ def test_evaluate_if(self):
+ code = "if x <= 3:\n y = 2\nelse:\n y = 5"
+ state = {"x": 3}
+ result = evaluate_python_code(code, {}, state=state)
+ # evaluate returns the value of the last assignment.
+ assert result == 2
+ self.assertDictEqual(state, {"x": 3, "y": 2, "print_outputs": ""})
+
+ state = {"x": 8}
+ result = evaluate_python_code(code, {}, state=state)
+ # evaluate returns the value of the last assignment.
+ assert result == 5
+ self.assertDictEqual(state, {"x": 8, "y": 5, "print_outputs": ""})
+
+ def test_evaluate_list(self):
+ code = "test_list = [x, add_two(x)]"
+ state = {"x": 3}
+ result = evaluate_python_code(code, {"add_two": add_two}, state=state)
+ self.assertListEqual(result, [3, 5])
+ self.assertDictEqual(state, {"x": 3, "test_list": [3, 5], "print_outputs": ""})
+
+ def test_evaluate_name(self):
+ code = "y = x"
+ state = {"x": 3}
+ result = evaluate_python_code(code, {}, state=state)
+ assert result == 3
+ self.assertDictEqual(state, {"x": 3, "y": 3, "print_outputs": ""})
+
+ def test_evaluate_subscript(self):
+ code = "test_list = [x, add_two(x)]\ntest_list[1]"
+ state = {"x": 3}
+ result = evaluate_python_code(code, {"add_two": add_two}, state=state)
+ assert result == 5
+ self.assertDictEqual(state, {"x": 3, "test_list": [3, 5], "print_outputs": ""})
+
+ code = "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']"
+ state = {"x": 3}
+ result = evaluate_python_code(code, {"add_two": add_two}, state=state)
+ assert result == 5
+ self.assertDictEqual(state, {"x": 3, "test_dict": {"x": 3, "y": 5}, "print_outputs": ""})
+
+ code = "vendor = {'revenue': 31000, 'rent': 50312}; vendor['ratio'] = round(vendor['revenue'] / vendor['rent'], 2)"
+ state = {}
+ evaluate_python_code(code, {"min": min, "print": print, "round": round}, state=state)
+ assert state["vendor"] == {"revenue": 31000, "rent": 50312, "ratio": 0.62}
+
+ def test_subscript_string_with_string_index_raises_appropriate_error(self):
+ code = """
+search_results = "[{'title': 'Paris, Ville de Paris, France Weather Forecast | AccuWeather', 'href': 'https://www.accuweather.com/en/fr/paris/623/weather-forecast/623', 'body': 'Get the latest weather forecast for Paris, Ville de Paris, France , including hourly, daily, and 10-day outlooks. AccuWeather provides you with reliable and accurate information on temperature ...'}]"
+for result in search_results:
+ if 'current' in result['title'].lower() or 'temperature' in result['title'].lower():
+ current_weather_url = result['href']
+ print(current_weather_url)
+ break"""
+ with pytest.raises(InterpreterError) as e:
+ evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert "You're trying to subscript a string with a string index" in e
+
+ def test_evaluate_for(self):
+ code = "x = 0\nfor i in range(3):\n x = i"
+ state = {}
+ result = evaluate_python_code(code, {"range": range}, state=state)
+ assert result == 2
+ self.assertDictEqual(state, {"x": 2, "i": 2, "print_outputs": ""})
+
+ def test_evaluate_binop(self):
+ code = "y + x"
+ state = {"x": 3, "y": 6}
+ result = evaluate_python_code(code, {}, state=state)
+ assert result == 9
+ self.assertDictEqual(state, {"x": 3, "y": 6, "print_outputs": ""})
+
+ def test_recursive_function(self):
+ code = """
+def recur_fibo(n):
+ if n <= 1:
+ return n
+ else:
+ return(recur_fibo(n-1) + recur_fibo(n-2))
+recur_fibo(6)"""
+ result = evaluate_python_code(code, {}, state={})
+ assert result == 8
+
+ def test_evaluate_string_methods(self):
+ code = "'hello'.replace('h', 'o').split('e')"
+ result = evaluate_python_code(code, {}, state={})
+ assert result == ["o", "llo"]
+
+ def test_evaluate_slicing(self):
+ code = "'hello'[1:3][::-1]"
+ result = evaluate_python_code(code, {}, state={})
+ assert result == "le"
+
+ def test_access_attributes(self):
+ code = "integer = 1\nobj_class = integer.__class__\nobj_class"
+ result = evaluate_python_code(code, {}, state={})
+ assert result is int
+
+ def test_list_comprehension(self):
+ code = "sentence = 'THESEAGULL43'\nmeaningful_sentence = '-'.join([char.lower() for char in sentence if char.isalpha()])"
+ result = evaluate_python_code(code, {}, state={})
+ assert result == "t-h-e-s-e-a-g-u-l-l"
+
+ def test_string_indexing(self):
+ code = """text_block = [
+ "THESE",
+ "AGULL"
+]
+sentence = ""
+for block in text_block:
+ for col in range(len(text_block[0])):
+ sentence += block[col]
+ """
+ result = evaluate_python_code(code, {"len": len, "range": range}, state={})
+ assert result == "THESEAGULL"
+
+ def test_tuples(self):
+ code = "x = (1, 2, 3)\nx[1]"
+ result = evaluate_python_code(code, {}, state={})
+ assert result == 2
+
+ code = """
+digits, i = [1, 2, 3], 1
+digits[i], digits[i + 1] = digits[i + 1], digits[i]"""
+ evaluate_python_code(code, {"range": range, "print": print, "int": int}, {})
+
+ code = """
+def calculate_isbn_10_check_digit(number):
+ total = sum((10 - i) * int(digit) for i, digit in enumerate(number))
+ remainder = total % 11
+ check_digit = 11 - remainder
+ if check_digit == 10:
+ return 'X'
+ elif check_digit == 11:
+ return '0'
+ else:
+ return str(check_digit)
+
+# Given 9-digit numbers
+numbers = [
+ "478225952",
+ "643485613",
+ "739394228",
+ "291726859",
+ "875262394",
+ "542617795",
+ "031810713",
+ "957007669",
+ "871467426"
+]
+
+# Calculate check digits for each number
+check_digits = [calculate_isbn_10_check_digit(number) for number in numbers]
+print(check_digits)
+"""
+ state = {}
+ evaluate_python_code(
+ code, {"range": range, "print": print, "sum": sum, "enumerate": enumerate, "int": int, "str": str}, state
+ )
+
+ def test_listcomp(self):
+ code = "x = [i for i in range(3)]"
+ result = evaluate_python_code(code, {"range": range}, state={})
+ assert result == [0, 1, 2]
+
+ def test_break_continue(self):
+ code = "for i in range(10):\n if i == 5:\n break\ni"
+ result = evaluate_python_code(code, {"range": range}, state={})
+ assert result == 5
+
+ code = "for i in range(10):\n if i == 5:\n continue\ni"
+ result = evaluate_python_code(code, {"range": range}, state={})
+ assert result == 9
+
+ def test_call_int(self):
+ code = "import math\nstr(math.ceil(149))"
+ result = evaluate_python_code(code, {"str": lambda x: str(x)}, state={})
+ assert result == "149"
+
+ def test_lambda(self):
+ code = "f = lambda x: x + 2\nf(3)"
+ result = evaluate_python_code(code, {}, state={})
+ assert result == 5
+
+ def test_dictcomp(self):
+ code = "x = {i: i**2 for i in range(3)}"
+ result = evaluate_python_code(code, {"range": range}, state={})
+ assert result == {0: 0, 1: 1, 2: 4}
+
+ code = "{num: name for num, name in {101: 'a', 102: 'b'}.items() if name not in ['a']}"
+ result = evaluate_python_code(code, {"print": print}, state={}, authorized_imports=["pandas"])
+ assert result == {102: "b"}
+
+ code = """
+shifts = {'A': ('6:45', '8:00'), 'B': ('10:00', '11:45')}
+shift_minutes = {worker: ('a', 'b') for worker, (start, end) in shifts.items()}
+"""
+ result = evaluate_python_code(code, {}, state={})
+ assert result == {"A": ("a", "b"), "B": ("a", "b")}
+
+ def test_tuple_assignment(self):
+ code = "a, b = 0, 1\nb"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert result == 1
+
+ def test_while(self):
+ code = "i = 0\nwhile i < 3:\n i += 1\ni"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert result == 3
+
+ # test infinite loop
+ code = "i = 0\nwhile i < 3:\n i -= 1\ni"
+ with pytest.raises(InterpreterError) as e:
+ evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert "iterations in While loop exceeded" in str(e)
+
+ # test lazy evaluation
+ code = """
+house_positions = [0, 7, 10, 15, 18, 22, 22]
+i, n, loc = 0, 7, 30
+while i < n and house_positions[i] <= loc:
+ i += 1
+"""
+ state = {}
+ evaluate_python_code(code, BASE_PYTHON_TOOLS, state=state)
+
+ def test_generator(self):
+ code = "a = [1, 2, 3, 4, 5]; b = (i**2 for i in a); list(b)"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert result == [1, 4, 9, 16, 25]
+
+ def test_boolops(self):
+ code = """if (not (a > b and a > c)) or d > e:
+ best_city = "Brooklyn"
+else:
+ best_city = "Manhattan"
+ best_city
+ """
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={"a": 1, "b": 2, "c": 3, "d": 4, "e": 5})
+ assert result == "Brooklyn"
+
+ code = """if d > e and a < b:
+ best_city = "Brooklyn"
+elif d < e and a < b:
+ best_city = "Sacramento"
+else:
+ best_city = "Manhattan"
+ best_city
+ """
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={"a": 1, "b": 2, "c": 3, "d": 4, "e": 5})
+ assert result == "Sacramento"
+
+ def test_if_conditions(self):
+ code = """char='a'
+if char.isalpha():
+ print('2')"""
+ state = {}
+ evaluate_python_code(code, BASE_PYTHON_TOOLS, state=state)
+ assert state["print_outputs"] == "2\n"
+
+ def test_imports(self):
+ code = "import math\nmath.sqrt(4)"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert result == 2.0
+
+ code = "from random import choice, seed\nseed(12)\nchoice(['win', 'lose', 'draw'])"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert result == "lose"
+
+ code = "import time, re\ntime.sleep(0.1)"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert result is None
+
+ code = "from queue import Queue\nq = Queue()\nq.put(1)\nq.get()"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert result == 1
+
+ code = "import itertools\nlist(itertools.islice(range(10), 3))"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert result == [0, 1, 2]
+
+ code = "import re\nre.search('a', 'abc').group()"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert result == "a"
+
+ code = "import stat\nstat.S_ISREG(0o100644)"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert result
+
+ code = "import statistics\nstatistics.mean([1, 2, 3, 4, 4])"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert result == 2.8
+
+ code = "import unicodedata\nunicodedata.name('A')"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert result == "LATIN CAPITAL LETTER A"
+
+ # Test submodules are handled properly, thus not raising error
+ code = "import numpy.random as rd\nrng = rd.default_rng(12345)\nrng.random()"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={}, authorized_imports=["numpy"])
+
+ code = "from numpy.random import default_rng as d_rng\nrng = d_rng(12345)\nrng.random()"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={}, authorized_imports=["numpy"])
+
+ def test_additional_imports(self):
+ code = "import numpy as np"
+ evaluate_python_code(code, authorized_imports=["numpy"], state={})
+
+ code = "import numpy.random as rd"
+ evaluate_python_code(code, authorized_imports=["numpy.random"], state={})
+ evaluate_python_code(code, authorized_imports=["numpy"], state={})
+ with pytest.raises(InterpreterError):
+ evaluate_python_code(code, authorized_imports=["random"], state={})
+
+ def test_multiple_comparators(self):
+ code = "0 <= -1 < 4 and 0 <= -5 < 4"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert not result
+
+ code = "0 <= 1 < 4 and 0 <= -5 < 4"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert not result
+
+ code = "0 <= 4 < 4 and 0 <= 3 < 4"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert not result
+
+ code = "0 <= 3 < 4 and 0 <= 3 < 4"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert result
+
+ def test_print_output(self):
+ code = "print('Hello world!')\nprint('Ok no one cares')"
+ state = {}
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state=state)
+ assert result is None
+ assert state["print_outputs"] == "Hello world!\nOk no one cares\n"
+
+ # test print in function
+ code = """
+print("1")
+def function():
+ print("2")
+function()"""
+ state = {}
+ evaluate_python_code(code, {"print": print}, state=state)
+ assert state["print_outputs"] == "1\n2\n"
+
+ def test_tuple_target_in_iterator(self):
+ code = "for a, b in [('Ralf Weikert', 'Austria'), ('Samuel Seungwon Lee', 'South Korea')]:res = a.split()[0]"
+ result = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert result == "Samuel"
+
+ def test_classes(self):
+ code = """
+class Animal:
+ species = "Generic Animal"
+
+ def __init__(self, name, age):
+ self.name = name
+ self.age = age
+
+ def sound(self):
+ return "The animal makes a sound."
+
+ def __str__(self):
+ return f"{self.name}, {self.age} years old"
+
+class Dog(Animal):
+ species = "Canine"
+
+ def __init__(self, name, age, breed):
+ super().__init__(name, age)
+ self.breed = breed
+
+ def sound(self):
+ return "The dog barks."
+
+ def __str__(self):
+ return f"{self.name}, {self.age} years old, {self.breed}"
+
+class Cat(Animal):
+ def sound(self):
+ return "The cat meows."
+
+ def __str__(self):
+ return f"{self.name}, {self.age} years old, {self.species}"
+
+
+# Testing multiple instances
+dog1 = Dog("Fido", 3, "Labrador")
+dog2 = Dog("Buddy", 5, "Golden Retriever")
+
+# Testing method with built-in function
+animals = [dog1, dog2, Cat("Whiskers", 2)]
+num_animals = len(animals)
+
+# Testing exceptions in methods
+class ExceptionTest:
+ def method_that_raises(self):
+ raise ValueError("An error occurred")
+
+try:
+ exc_test = ExceptionTest()
+ exc_test.method_that_raises()
+except ValueError as e:
+ exception_message = str(e)
+
+
+# Collecting results
+dog1_sound = dog1.sound()
+dog1_str = str(dog1)
+dog2_sound = dog2.sound()
+dog2_str = str(dog2)
+cat = Cat("Whiskers", 2)
+cat_sound = cat.sound()
+cat_str = str(cat)
+ """
+ state = {}
+ evaluate_python_code(code, {"print": print, "len": len, "super": super, "str": str, "sum": sum}, state=state)
+
+ # Assert results
+ assert state["dog1_sound"] == "The dog barks."
+ assert state["dog1_str"] == "Fido, 3 years old, Labrador"
+ assert state["dog2_sound"] == "The dog barks."
+ assert state["dog2_str"] == "Buddy, 5 years old, Golden Retriever"
+ assert state["cat_sound"] == "The cat meows."
+ assert state["cat_str"] == "Whiskers, 2 years old, Generic Animal"
+ assert state["num_animals"] == 3
+ assert state["exception_message"] == "An error occurred"
+
+ def test_variable_args(self):
+ code = """
+def var_args_method(self, *args, **kwargs):
+ return sum(args) + sum(kwargs.values())
+
+var_args_method(1, 2, 3, x=4, y=5)
+"""
+ state = {}
+ result = evaluate_python_code(code, {"sum": sum}, state=state)
+ assert result == 15
+
+ def test_exceptions(self):
+ code = """
+def method_that_raises(self):
+ raise ValueError("An error occurred")
+
+try:
+ method_that_raises()
+except ValueError as e:
+ exception_message = str(e)
+ """
+ state = {}
+ evaluate_python_code(code, {"print": print, "len": len, "super": super, "str": str, "sum": sum}, state=state)
+ assert state["exception_message"] == "An error occurred"
+
+ def test_print(self):
+ code = "print(min([1, 2, 3]))"
+ state = {}
+ evaluate_python_code(code, {"min": min, "print": print}, state=state)
+ assert state["print_outputs"] == "1\n"
+
+ def test_types_as_objects(self):
+ code = "type_a = float(2); type_b = str; type_c = int"
+ state = {}
+ result = evaluate_python_code(code, {"float": float, "str": str, "int": int}, state=state)
+ assert result is int
+
+ def test_tuple_id(self):
+ code = """
+food_items = {"apple": 2, "banana": 3, "orange": 1, "pear": 1}
+unique_food_items = [item for item, count in food_item_counts.items() if count == 1]
+"""
+ state = {}
+ result = evaluate_python_code(code, {}, state=state)
+ assert result == ["orange", "pear"]
+
+ def test_nonsimple_augassign(self):
+ code = """
+counts_dict = {'a': 0}
+counts_dict['a'] += 1
+counts_list = [1, 2, 3]
+counts_list += [4, 5, 6]
+
+class Counter:
+ self.count = 0
+
+a = Counter()
+a.count += 1
+"""
+ state = {}
+ evaluate_python_code(code, {}, state=state)
+ assert state["counts_dict"] == {"a": 1}
+ assert state["counts_list"] == [1, 2, 3, 4, 5, 6]
+ assert state["a"].count == 1
+
+ def test_adding_int_to_list_raises_error(self):
+ code = """
+counts = [1, 2, 3]
+counts += 1"""
+ with pytest.raises(InterpreterError) as e:
+ evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert "Cannot add non-list value 1 to a list." in str(e)
+
+ def test_error_highlights_correct_line_of_code(self):
+ code = """# Ok this is a very long code
+# It has many commented lines
+a = 1
+b = 2
+
+# Here is another piece
+counts = [1, 2, 3]
+counts += 1
+b += 1"""
+ with pytest.raises(InterpreterError) as e:
+ evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert "Evaluation stopped at line 'counts += 1" in str(e)
+
+ def test_assert(self):
+ code = """
+assert 1 == 1
+assert 1 == 2
+"""
+ with pytest.raises(AssertionError) as e:
+ evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
+ assert "1 == 2" in str(e) and "1 == 1" not in str(e)
+
+ def test_with_context_manager(self):
+ code = """
+class SimpleLock:
+ def __init__(self):
+ self.locked = False
+
+ def __enter__(self):
+ self.locked = True
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self.locked = False
+
+lock = SimpleLock()
+
+with lock as l:
+ assert l.locked == True
+
+assert lock.locked == False
+ """
+ state = {}
+ tools = {}
+ evaluate_python_code(code, tools, state=state)
+
+ def test_default_arg_in_function(self):
+ code = """
+def f(a, b=333, n=1000):
+ return b + n
+n = f(1, n=667)
+"""
+ res = evaluate_python_code(code, {}, {})
+ assert res == 1000
+
+ def test_set(self):
+ code = """
+S1 = {'a', 'b', 'c'}
+S2 = {'b', 'c', 'd'}
+S3 = S1.difference(S2)
+S4 = S1.intersection(S2)
+"""
+ state = {}
+ evaluate_python_code(code, {}, state=state)
+ assert state["S3"] == {"a"}
+ assert state["S4"] == {"b", "c"}
+
+ def test_break(self):
+ code = """
+i = 0
+
+while True:
+ i+= 1
+ if i==3:
+ break
+
+i"""
+ result = evaluate_python_code(code, {"print": print, "round": round}, state={})
+ assert result == 3
+
+ def test_return(self):
+ # test early returns
+ code = """
+def add_one(n, shift):
+ if True:
+ return n + shift
+ return n
+
+add_one(1, 1)
+"""
+ state = {}
+ result = evaluate_python_code(code, {"print": print, "range": range, "ord": ord, "chr": chr}, state=state)
+ assert result == 2
+
+ # test returning None
+ code = """
+def returns_none(a):
+ return
+
+returns_none(1)
+"""
+ state = {}
+ result = evaluate_python_code(code, {"print": print, "range": range, "ord": ord, "chr": chr}, state=state)
+ assert result is None
+
+ def test_nested_for_loop(self):
+ code = """
+all_res = []
+for i in range(10):
+ subres = []
+ for j in range(i):
+ subres.append(j)
+ all_res.append(subres)
+
+out = [i for sublist in all_res for i in sublist]
+out[:10]
+"""
+ state = {}
+ result = evaluate_python_code(code, {"print": print, "range": range}, state=state)
+ assert result == [0, 0, 1, 0, 1, 2, 0, 1, 2, 3]
+
+ def test_pandas(self):
+ code = """
+import pandas as pd
+
+df = pd.DataFrame.from_dict({'SetCount': ['5', '4', '5'], 'Quantity': [1, 0, -1]})
+
+df['SetCount'] = pd.to_numeric(df['SetCount'], errors='coerce')
+
+parts_with_5_set_count = df[df['SetCount'] == 5.0]
+parts_with_5_set_count[['Quantity', 'SetCount']].values[1]
+"""
+ state = {}
+ result = evaluate_python_code(code, {}, state=state, authorized_imports=["pandas"])
+ assert np.array_equal(result, [-1, 5])
+
+ code = """
+import pandas as pd
+
+df = pd.DataFrame.from_dict({"AtomicNumber": [111, 104, 105], "ok": [0, 1, 2]})
+print("HH0")
+
+# Filter the DataFrame to get only the rows with outdated atomic numbers
+filtered_df = df.loc[df['AtomicNumber'].isin([104])]
+"""
+ result = evaluate_python_code(code, {"print": print}, state={}, authorized_imports=["pandas"])
+ assert np.array_equal(result.values[0], [104, 1])
+
+ code = """import pandas as pd
+data = pd.DataFrame.from_dict([
+ {"Pclass": 1, "Survived": 1},
+ {"Pclass": 2, "Survived": 0},
+ {"Pclass": 2, "Survived": 1}
+])
+survival_rate_by_class = data.groupby('Pclass')['Survived'].mean()
+"""
+ result = evaluate_python_code(code, {}, state={}, authorized_imports=["pandas"])
+ assert result.values[1] == 0.5
+
+ def test_starred(self):
+ code = """
+from math import radians, sin, cos, sqrt, atan2
+
+def haversine(lat1, lon1, lat2, lon2):
+ R = 6371000 # Radius of the Earth in meters
+ lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])
+ dlat = lat2 - lat1
+ dlon = lon2 - lon1
+ a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
+ c = 2 * atan2(sqrt(a), sqrt(1 - a))
+ distance = R * c
+ return distance
+
+coords_geneva = (46.1978, 6.1342)
+coords_barcelona = (41.3869, 2.1660)
+
+distance_geneva_barcelona = haversine(*coords_geneva, *coords_barcelona)
+"""
+ result = evaluate_python_code(code, {"print": print, "map": map}, state={}, authorized_imports=["math"])
+ assert round(result, 1) == 622395.4
+
+ def test_for(self):
+ code = """
+shifts = {
+ "Worker A": ("6:45 pm", "8:00 pm"),
+ "Worker B": ("10:00 am", "11:45 am")
+}
+
+shift_intervals = {}
+for worker, (start, end) in shifts.items():
+ shift_intervals[worker] = end
+shift_intervals
+"""
+ result = evaluate_python_code(code, {"print": print, "map": map}, state={})
+ assert result == {"Worker A": "8:00 pm", "Worker B": "11:45 am"}
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_search.py b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_search.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e40e3ca2957bbc46a9ed7bec6df9cb28432cc53
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_search.py
@@ -0,0 +1,30 @@
+# coding=utf-8
+# Copyright 2024 HuggingFace Inc.
+#
+# 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 unittest
+
+from transformers import load_tool
+
+from .test_tools_common import ToolTesterMixin
+
+
+class DuckDuckGoSearchToolTester(unittest.TestCase, ToolTesterMixin):
+ def setUp(self):
+ self.tool = load_tool("web_search")
+ self.tool.setup()
+
+ def test_exact_match_arg(self):
+ result = self.tool("Agents")
+ assert isinstance(result, list) and isinstance(result[0], dict)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_speech_to_text.py b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_speech_to_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d6e9a392950d0fd11c4ade30920f83f17f890c3
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_speech_to_text.py
@@ -0,0 +1,36 @@
+# coding=utf-8
+# Copyright 2023 HuggingFace Inc.
+#
+# 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 unittest
+
+import numpy as np
+
+from transformers import load_tool
+
+from .test_tools_common import ToolTesterMixin
+
+
+class SpeechToTextToolTester(unittest.TestCase, ToolTesterMixin):
+ def setUp(self):
+ self.tool = load_tool("speech_to_text")
+ self.tool.setup()
+
+ def test_exact_match_arg(self):
+ result = self.tool(np.ones(3000))
+ self.assertEqual(result, " Thank you.")
+
+ def test_exact_match_kwarg(self):
+ result = self.tool(audio=np.ones(3000))
+ self.assertEqual(result, " Thank you.")
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_text_to_speech.py b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_text_to_speech.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8ed9afcbf8f1f3806b22f2797666b9341df88a8
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_text_to_speech.py
@@ -0,0 +1,50 @@
+# coding=utf-8
+# Copyright 2023 HuggingFace Inc.
+#
+# 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 unittest
+
+from transformers import load_tool
+from transformers.utils import is_torch_available
+
+
+if is_torch_available():
+ import torch
+
+from transformers.testing_utils import require_torch
+
+from .test_tools_common import ToolTesterMixin
+
+
+@require_torch
+class TextToSpeechToolTester(unittest.TestCase, ToolTesterMixin):
+ def setUp(self):
+ self.tool = load_tool("text_to_speech")
+ self.tool.setup()
+
+ def test_exact_match_arg(self):
+ # SpeechT5 isn't deterministic
+ torch.manual_seed(0)
+ result = self.tool("hey")
+ resulting_tensor = result.to_raw()
+ self.assertTrue(len(resulting_tensor.detach().shape) == 1)
+ self.assertTrue(resulting_tensor.detach().shape[0] > 1000)
+
+ def test_exact_match_kwarg(self):
+ # SpeechT5 isn't deterministic
+ torch.manual_seed(0)
+ result = self.tool("hey")
+ resulting_tensor = result.to_raw()
+ self.assertTrue(len(resulting_tensor.detach().shape) == 1)
+ self.assertTrue(resulting_tensor.detach().shape[0] > 1000)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_tools_common.py b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_tools_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..8226e7109884e6b913a406c92be0bb2c0d4e72ed
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_tools_common.py
@@ -0,0 +1,171 @@
+# coding=utf-8
+# Copyright 2024 HuggingFace Inc.
+#
+# 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 unittest
+from pathlib import Path
+from typing import Dict, Union
+
+import numpy as np
+import pytest
+
+from transformers import is_torch_available, is_vision_available
+from transformers.agents.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText
+from transformers.agents.tools import Tool, tool
+from transformers.testing_utils import get_tests_dir, is_agent_test
+
+
+if is_torch_available():
+ import torch
+
+if is_vision_available():
+ from PIL import Image
+
+
+AUTHORIZED_TYPES = ["string", "boolean", "integer", "number", "audio", "image", "any"]
+
+
+def create_inputs(tool_inputs: Dict[str, Dict[Union[str, type], str]]):
+ inputs = {}
+
+ for input_name, input_desc in tool_inputs.items():
+ input_type = input_desc["type"]
+
+ if input_type == "string":
+ inputs[input_name] = "Text input"
+ elif input_type == "image":
+ inputs[input_name] = Image.open(
+ Path(get_tests_dir("fixtures/tests_samples/COCO")) / "000000039769.png"
+ ).resize((512, 512))
+ elif input_type == "audio":
+ inputs[input_name] = np.ones(3000)
+ else:
+ raise ValueError(f"Invalid type requested: {input_type}")
+
+ return inputs
+
+
+def output_type(output):
+ if isinstance(output, (str, AgentText)):
+ return "string"
+ elif isinstance(output, (Image.Image, AgentImage)):
+ return "image"
+ elif isinstance(output, (torch.Tensor, AgentAudio)):
+ return "audio"
+ else:
+ raise TypeError(f"Invalid output: {output}")
+
+
+@is_agent_test
+class ToolTesterMixin:
+ def test_inputs_output(self):
+ self.assertTrue(hasattr(self.tool, "inputs"))
+ self.assertTrue(hasattr(self.tool, "output_type"))
+
+ inputs = self.tool.inputs
+ self.assertTrue(isinstance(inputs, dict))
+
+ for _, input_spec in inputs.items():
+ self.assertTrue("type" in input_spec)
+ self.assertTrue("description" in input_spec)
+ self.assertTrue(input_spec["type"] in AUTHORIZED_TYPES)
+ self.assertTrue(isinstance(input_spec["description"], str))
+
+ output_type = self.tool.output_type
+ self.assertTrue(output_type in AUTHORIZED_TYPES)
+
+ def test_common_attributes(self):
+ self.assertTrue(hasattr(self.tool, "description"))
+ self.assertTrue(hasattr(self.tool, "name"))
+ self.assertTrue(hasattr(self.tool, "inputs"))
+ self.assertTrue(hasattr(self.tool, "output_type"))
+
+ def test_agent_type_output(self):
+ inputs = create_inputs(self.tool.inputs)
+ output = self.tool(**inputs)
+ if self.tool.output_type != "any":
+ agent_type = AGENT_TYPE_MAPPING[self.tool.output_type]
+ self.assertTrue(isinstance(output, agent_type))
+
+ def test_agent_types_inputs(self):
+ inputs = create_inputs(self.tool.inputs)
+ _inputs = []
+ for _input, expected_input in zip(inputs, self.tool.inputs.values()):
+ input_type = expected_input["type"]
+ _inputs.append(AGENT_TYPE_MAPPING[input_type](_input))
+
+
+class ToolTests(unittest.TestCase):
+ def test_tool_init_with_decorator(self):
+ @tool
+ def coolfunc(a: str, b: int) -> float:
+ """Cool function
+
+ Args:
+ a: The first argument
+ b: The second one
+ """
+ return b + 2, a
+
+ assert coolfunc.output_type == "number"
+
+ def test_tool_init_vanilla(self):
+ 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": "string",
+ "description": "the task category (such as text-classification, depth-estimation, etc)",
+ }
+ }
+ output_type = "integer"
+
+ def forward(self, task):
+ return "best model"
+
+ tool = HFModelDownloadsTool()
+ assert list(tool.inputs.keys())[0] == "task"
+
+ def test_tool_init_decorator_raises_issues(self):
+ with pytest.raises(Exception) as e:
+
+ @tool
+ def coolfunc(a: str, b: int):
+ """Cool function
+
+ Args:
+ a: The first argument
+ b: The second one
+ """
+ return a + b
+
+ assert coolfunc.output_type == "number"
+ assert "Tool return type not found" in str(e)
+
+ with pytest.raises(Exception) as e:
+
+ @tool
+ def coolfunc(a: str, b: int) -> int:
+ """Cool function
+
+ Args:
+ a: The first argument
+ """
+ return b + a
+
+ assert coolfunc.output_type == "number"
+ assert "docstring has no description for the argument" in str(e)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_translation.py b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_translation.py
new file mode 100644
index 0000000000000000000000000000000000000000..9027dd1731382bab4ca62ec71e58e2552113cdde
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/agents/test_translation.py
@@ -0,0 +1,67 @@
+# coding=utf-8
+# Copyright 2024 HuggingFace Inc.
+#
+# 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 unittest
+
+from transformers import load_tool
+from transformers.agents.agent_types import AGENT_TYPE_MAPPING
+
+from .test_tools_common import ToolTesterMixin, output_type
+
+
+class TranslationToolTester(unittest.TestCase, ToolTesterMixin):
+ def setUp(self):
+ self.tool = load_tool("translation")
+ self.tool.setup()
+ self.remote_tool = load_tool("translation", remote=True)
+
+ def test_exact_match_arg(self):
+ result = self.tool("Hey, what's up?", src_lang="English", tgt_lang="French")
+ self.assertEqual(result, "- Hé, comment ça va?")
+
+ def test_exact_match_kwarg(self):
+ result = self.tool(text="Hey, what's up?", src_lang="English", tgt_lang="French")
+ self.assertEqual(result, "- Hé, comment ça va?")
+
+ def test_call(self):
+ inputs = ["Hey, what's up?", "English", "Spanish"]
+ output = self.tool(*inputs)
+
+ self.assertEqual(output_type(output), self.tool.output_type)
+
+ def test_agent_type_output(self):
+ inputs = ["Hey, what's up?", "English", "Spanish"]
+ output = self.tool(*inputs)
+ output_type = AGENT_TYPE_MAPPING[self.tool.output_type]
+ self.assertTrue(isinstance(output, output_type))
+
+ def test_agent_types_inputs(self):
+ example_inputs = {
+ "text": "Hey, what's up?",
+ "src_lang": "English",
+ "tgt_lang": "Spanish",
+ }
+
+ _inputs = []
+ for input_name in example_inputs.keys():
+ example_input = example_inputs[input_name]
+ input_description = self.tool.inputs[input_name]
+ input_type = input_description["type"]
+ _inputs.append(AGENT_TYPE_MAPPING[input_type](example_input))
+
+ # Should not raise an error
+ output = self.tool(**example_inputs)
+ output_type = AGENT_TYPE_MAPPING[self.tool.output_type]
+ self.assertTrue(isinstance(output, output_type))
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/bettertransformer/__init__.py b/tasks/tasksmith-441eeab80047/tests/source/tests/bettertransformer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/bettertransformer/test_integration.py b/tasks/tasksmith-441eeab80047/tests/source/tests/bettertransformer/test_integration.py
new file mode 100644
index 0000000000000000000000000000000000000000..b123001f10232bb8f158994163fee21b44eaf090
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/bettertransformer/test_integration.py
@@ -0,0 +1,86 @@
+# coding=utf-8
+# Copyright 2023 The HuggingFace Team Inc.
+#
+# 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 tempfile
+import unittest
+
+from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
+from transformers.testing_utils import (
+ is_torch_available,
+ require_optimum,
+ require_torch,
+ slow,
+)
+
+
+if is_torch_available():
+ import torch
+
+
+@require_torch
+@require_optimum
+@slow
+class BetterTransformerIntegrationTest(unittest.TestCase):
+ # refer to the full test suite in Optimum library:
+ # https://github.com/huggingface/optimum/tree/main/tests/bettertransformer
+
+ def test_transform_and_reverse(self):
+ r"""
+ Classic tests to simply check if the conversion has been successful.
+ """
+ model_id = "hf-internal-testing/tiny-random-t5"
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
+
+ inp = tokenizer("This is me", return_tensors="pt")
+
+ model = model.to_bettertransformer()
+
+ self.assertTrue(any("BetterTransformer" in mod.__class__.__name__ for _, mod in model.named_modules()))
+
+ output = model.generate(**inp)
+
+ model = model.reverse_bettertransformer()
+
+ self.assertFalse(any("BetterTransformer" in mod.__class__.__name__ for _, mod in model.named_modules()))
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ model.save_pretrained(tmpdirname)
+
+ model_reloaded = AutoModelForSeq2SeqLM.from_pretrained(tmpdirname)
+
+ self.assertFalse(
+ any("BetterTransformer" in mod.__class__.__name__ for _, mod in model_reloaded.named_modules())
+ )
+
+ output_from_pretrained = model_reloaded.generate(**inp)
+ torch.testing.assert_close(output, output_from_pretrained)
+
+ def test_error_save_pretrained(self):
+ r"""
+ The save_pretrained method should raise a ValueError if the model is in BetterTransformer mode.
+ All should be good if the model is reversed.
+ """
+ model_id = "hf-internal-testing/tiny-random-t5"
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
+
+ model = model.to_bettertransformer()
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ with self.assertRaises(ValueError):
+ model.save_pretrained(tmpdirname)
+
+ model = model.reverse_bettertransformer()
+ model.save_pretrained(tmpdirname)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/deepspeed/ds_config_zero2.json b/tasks/tasksmith-441eeab80047/tests/source/tests/deepspeed/ds_config_zero2.json
new file mode 100644
index 0000000000000000000000000000000000000000..6f0a546e51614dd082d9b03d06a3376dd5fb2a11
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/deepspeed/ds_config_zero2.json
@@ -0,0 +1,54 @@
+{
+ "fp16": {
+ "enabled": "auto",
+ "loss_scale": 0,
+ "loss_scale_window": 1000,
+ "initial_scale_power": 16,
+ "hysteresis": 2,
+ "min_loss_scale": 1
+ },
+
+ "bf16": {
+ "enabled": "auto"
+ },
+
+ "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": 2,
+ "offload_optimizer": {
+ "device": "cpu",
+ "pin_memory": true
+ },
+ "allgather_partitions": true,
+ "allgather_bucket_size": 2e8,
+ "overlap_comm": true,
+ "reduce_scatter": true,
+ "reduce_bucket_size": 2e8,
+ "contiguous_gradients": 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
+}
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/deepspeed/ds_config_zero3.json b/tasks/tasksmith-441eeab80047/tests/source/tests/deepspeed/ds_config_zero3.json
new file mode 100644
index 0000000000000000000000000000000000000000..dd741ac84737a039b71c16ec5aef289683010094
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/deepspeed/ds_config_zero3.json
@@ -0,0 +1,56 @@
+{
+ "fp16": {
+ "enabled": "auto",
+ "loss_scale": 0,
+ "loss_scale_window": 1000,
+ "initial_scale_power": 16,
+ "hysteresis": 2,
+ "min_loss_scale": 1
+ },
+ "bf16": {
+ "enabled": "auto"
+ },
+ "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": "none",
+ "pin_memory": true
+ },
+ "offload_param": {
+ "device": "none",
+ "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
+}
\ No newline at end of file
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/deepspeed/test_deepspeed.py b/tasks/tasksmith-441eeab80047/tests/source/tests/deepspeed/test_deepspeed.py
new file mode 100644
index 0000000000000000000000000000000000000000..003e635a10892835e315d78b95d0d63f6735e695
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/deepspeed/test_deepspeed.py
@@ -0,0 +1,1431 @@
+# 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 dataclasses
+import io
+import itertools
+import json
+import os
+import unittest
+from copy import deepcopy
+from functools import partial
+
+import datasets
+from parameterized import parameterized
+
+import tests.trainer.test_trainer
+import transformers
+from tests.trainer.test_trainer import TrainerIntegrationCommon # noqa
+from transformers import AutoModel, TrainingArguments, is_torch_available, logging
+from transformers.integrations.deepspeed import (
+ HfDeepSpeedConfig,
+ is_deepspeed_available,
+ unset_hf_deepspeed_config,
+)
+from transformers.testing_utils import (
+ CaptureLogger,
+ CaptureStd,
+ CaptureStderr,
+ LoggingLevel,
+ TestCasePlus,
+ backend_device_count,
+ execute_subprocess_async,
+ mockenv_context,
+ require_deepspeed,
+ require_optuna,
+ require_torch_accelerator,
+ require_torch_fp16,
+ require_torch_multi_accelerator,
+ run_first,
+ slow,
+ torch_device,
+)
+from transformers.trainer_utils import get_last_checkpoint, set_seed
+from transformers.utils import SAFE_WEIGHTS_NAME, is_torch_bf16_available_on_device, is_torch_fp16_available_on_device
+
+
+if is_torch_available():
+ import torch
+
+ from tests.trainer.test_trainer import ( # noqa
+ RegressionModelConfig,
+ RegressionPreTrainedModel,
+ )
+
+ # hack to restore original logging level pre #21700
+ get_regression_trainer = partial(tests.trainer.test_trainer.get_regression_trainer, log_level="info")
+
+
+set_seed(42)
+
+# default torch.distributed port
+DEFAULT_MASTER_PORT = "10999"
+
+T5_SMALL = "google-t5/t5-small"
+T5_TINY = "patrickvonplaten/t5-tiny-random"
+GPT2_TINY = "sshleifer/tiny-gpt2"
+GPTJ_TINY = "hf-internal-testing/tiny-random-gptj"
+
+
+def load_json(path):
+ with open(path) as f:
+ return json.load(f)
+
+
+def get_master_port(real_launcher=False):
+ """
+ When using a single gpu launcher emulation (i.e. not deepspeed or python -m torch.distributed)
+ the issue is that once the port is tied it can't be used anywhere else outside of this process,
+ since torch.dist doesn't free the port until the process exits. Therefore for the sake of being
+ able to run both emulated launcher and normal launcher tests we need 2 distinct ports.
+
+ This function will give the right port in the right context. For real launcher it'll give the
+ base port, for emulated launcher it'll give the base port + 1. In both cases a string is
+ returned.
+
+ Args:
+ `real_launcher`: whether a real launcher is going to be used, or the emulated one
+
+ """
+
+ master_port_base = os.environ.get("DS_TEST_PORT", DEFAULT_MASTER_PORT)
+ if not real_launcher:
+ master_port_base = str(int(master_port_base) + 1)
+ return master_port_base
+
+
+def require_deepspeed_aio(test_case):
+ """
+ Decorator marking a test that requires deepspeed aio (nvme)
+ """
+ if not is_deepspeed_available():
+ return unittest.skip(reason="test requires deepspeed")(test_case)
+
+ import deepspeed
+ from deepspeed.ops.aio import AsyncIOBuilder
+
+ if not deepspeed.ops.__compatible_ops__[AsyncIOBuilder.NAME]:
+ return unittest.skip(reason="test requires deepspeed async-io")(test_case)
+ else:
+ return test_case
+
+
+if is_deepspeed_available():
+ from deepspeed.utils import logger as deepspeed_logger # noqa
+ from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
+ from transformers.integrations.deepspeed import deepspeed_config, is_deepspeed_zero3_enabled # noqa
+
+
+def get_launcher(distributed=False):
+ # 1. explicitly set --num_nodes=1 just in case these tests end up run on a multi-node setup
+ # - it won't be able to handle that
+ # 2. for now testing with just 2 gpus max (since some quality tests may give different
+ # results with mode gpus because we use very little data)
+ num_gpus = min(2, backend_device_count(torch_device)) if distributed else 1
+ master_port = get_master_port(real_launcher=True)
+ return f"deepspeed --num_nodes 1 --num_gpus {num_gpus} --master_port {master_port}".split()
+
+
+ZERO2 = "zero2"
+ZERO3 = "zero3"
+
+FP16 = "fp16"
+BF16 = "bf16"
+
+HF_OPTIM = "hf_optim"
+HF_SCHEDULER = "hf_scheduler"
+DS_OPTIM = "ds_optim"
+DS_SCHEDULER = "ds_scheduler"
+
+optims = [HF_OPTIM, DS_OPTIM]
+schedulers = [HF_SCHEDULER, DS_SCHEDULER]
+
+stages = [ZERO2, ZERO3]
+
+dtypes = []
+if is_torch_bf16_available_on_device(torch_device):
+ dtypes.append(BF16)
+if is_torch_fp16_available_on_device(torch_device):
+ dtypes.append(FP16)
+
+
+def parameterized_custom_name_func(func, param_num, param):
+ # customize the test name generator function as we want both params to appear in the sub-test
+ # name, as by default it shows only the first param
+ param_based_name = parameterized.to_safe_name("_".join(str(x) for x in param.args))
+ return f"{func.__name__}_{param_based_name}"
+
+
+# Cartesian-product of zero stages with models to test
+params = list(itertools.product(stages, dtypes))
+
+params_with_optims_and_schedulers = list(itertools.product(stages, dtypes, optims, schedulers))
+
+
+@require_deepspeed
+class CoreIntegrationDeepSpeed(TestCasePlus, TrainerIntegrationCommon):
+ """
+ Testing non-Trainer DeepSpeed integration
+ """
+
+ def setUp(self):
+ super().setUp()
+
+ master_port = get_master_port(real_launcher=False)
+ self.dist_env_1_gpu = {
+ "MASTER_ADDR": "localhost",
+ "MASTER_PORT": master_port,
+ "RANK": "0",
+ "LOCAL_RANK": "0",
+ "WORLD_SIZE": "1",
+ }
+
+ def tearDown(self):
+ super().tearDown()
+
+ # reset the ds config global so that tests state doesn't leak
+ unset_hf_deepspeed_config()
+
+ def test_init_zero3(self):
+ # test that zero.Init() works correctly
+ ds_config = {
+ "train_batch_size": 1,
+ "zero_optimization": {
+ "stage": 3,
+ },
+ }
+
+ dschf = HfDeepSpeedConfig(ds_config)
+
+ self.assertTrue(dschf.is_zero3())
+ self.assertTrue(is_deepspeed_zero3_enabled())
+
+ with LoggingLevel(logging.INFO):
+ with mockenv_context(**self.dist_env_1_gpu):
+ logger = logging.get_logger("transformers.modeling_utils")
+ with CaptureLogger(logger) as cl:
+ AutoModel.from_pretrained(T5_TINY)
+ self.assertIn("Detected DeepSpeed ZeRO-3", cl.out)
+
+ # now remove zero optimization
+ del ds_config["zero_optimization"]
+ dschf = HfDeepSpeedConfig(ds_config)
+
+ self.assertFalse(dschf.is_zero3())
+ self.assertFalse(is_deepspeed_zero3_enabled())
+
+ with LoggingLevel(logging.INFO):
+ with mockenv_context(**self.dist_env_1_gpu):
+ logger = logging.get_logger("transformers.modeling_utils")
+ with CaptureLogger(logger) as cl:
+ AutoModel.from_pretrained(T5_TINY)
+ self.assertNotIn("Detected DeepSpeed ZeRO-3", cl.out)
+
+ @require_torch_fp16
+ @require_torch_accelerator
+ def test_init_zero3_fp16(self):
+ # test that zero.Init() works correctly under zero3/fp16
+ ds_config = {
+ "train_batch_size": 1,
+ "zero_optimization": {
+ "stage": 3,
+ },
+ "fp16": {
+ "enabled": True,
+ },
+ }
+
+ dschf = HfDeepSpeedConfig(ds_config)
+
+ self.assertTrue(dschf.is_zero3())
+ self.assertTrue(is_deepspeed_zero3_enabled())
+
+ with LoggingLevel(logging.INFO):
+ with mockenv_context(**self.dist_env_1_gpu):
+ logger = logging.get_logger("transformers.modeling_utils")
+ with CaptureLogger(logger) as cl:
+ AutoModel.from_pretrained(T5_TINY)
+ self.assertIn("Detected DeepSpeed ZeRO-3", cl.out)
+
+ # now remove zero optimization
+ del ds_config["zero_optimization"]
+ dschf = HfDeepSpeedConfig(ds_config)
+
+ self.assertFalse(dschf.is_zero3())
+ self.assertFalse(is_deepspeed_zero3_enabled())
+
+ with LoggingLevel(logging.INFO):
+ with mockenv_context(**self.dist_env_1_gpu):
+ logger = logging.get_logger("transformers.modeling_utils")
+ with CaptureLogger(logger) as cl:
+ AutoModel.from_pretrained(T5_TINY)
+ self.assertNotIn("Detected DeepSpeed ZeRO-3", cl.out)
+
+ def test_init_zero3_missing_params(self):
+ # test that zero.Init() for missing parameters works correctly under zero3
+ import deepspeed
+ import torch
+
+ from transformers.models.gpt2.modeling_gpt2 import GPT2PreTrainedModel
+
+ class TinyGPT2WithUninitializedWeights(GPT2PreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.transformer = AutoModel.from_pretrained(GPT2_TINY, config=config)
+ self.new_head = torch.nn.Linear(config.hidden_size, config.vocab_size, bias=True)
+
+ def forward(self, *args, **kwargs):
+ transformer_outputs = self.transformer(*args, **kwargs)
+ hidden_states = transformer_outputs[0]
+ return self.new_head(hidden_states).float()
+
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if module is self.new_head:
+ self.new_head.weight.data.fill_(-100.0)
+ self.new_head.bias.data.fill_(+100.0)
+
+ ds_config = {
+ "train_batch_size": 1,
+ "zero_optimization": {
+ "stage": 3,
+ },
+ }
+
+ dschf = HfDeepSpeedConfig(ds_config)
+
+ self.assertTrue(dschf.is_zero3())
+ self.assertTrue(is_deepspeed_zero3_enabled())
+
+ with LoggingLevel(logging.INFO):
+ with mockenv_context(**self.dist_env_1_gpu):
+ logger = logging.get_logger("transformers.modeling_utils")
+ with CaptureLogger(logger) as cl:
+ model = TinyGPT2WithUninitializedWeights.from_pretrained(GPT2_TINY)
+ self.assertIn("Detected DeepSpeed ZeRO-3", cl.out)
+ self.assertRegex(cl.out, r"newly initialized.*new_head\.bias.*new_head\.weight")
+ with deepspeed.zero.GatheredParameters([model.new_head.weight, model.new_head.bias]):
+ self.assertTrue(
+ torch.allclose(model.new_head.weight, torch.tensor(-100.0, device=model.new_head.weight.device)),
+ )
+ self.assertTrue(
+ torch.allclose(model.new_head.bias, torch.tensor(+100.0, device=model.new_head.bias.device)),
+ )
+
+ # now remove zero optimization
+ del ds_config["zero_optimization"]
+ dschf = HfDeepSpeedConfig(ds_config)
+
+ self.assertFalse(dschf.is_zero3())
+ self.assertFalse(is_deepspeed_zero3_enabled())
+
+ with LoggingLevel(logging.INFO):
+ with mockenv_context(**self.dist_env_1_gpu):
+ logger = logging.get_logger("transformers.modeling_utils")
+ with CaptureLogger(logger) as cl:
+ model = TinyGPT2WithUninitializedWeights.from_pretrained(GPT2_TINY)
+ self.assertNotIn("Detected DeepSpeed ZeRO-3", cl.out)
+ self.assertRegex(cl.out, r"newly initialized.*new_head\.bias.*new_head\.weight")
+ self.assertTrue(
+ torch.allclose(model.new_head.weight, torch.tensor(-100.0, device=model.new_head.weight.device)),
+ )
+ self.assertTrue(
+ torch.allclose(model.new_head.bias, torch.tensor(+100.0, device=model.new_head.bias.device)),
+ )
+
+ def test_arange_bf16(self):
+ # Tests that configuring DeepSpeed with 16 bits does not cause float `torch.arange()` tensors to be cast down.
+ # NOTE -- this assumes that the function calls have the following downcast-preventing pattern, i.e.
+ # `torch.arange(...,dtype=torch.int64)` followed by a cast like `.to(torch.float32)`. 🚨 If this pattern is
+ # NOT applied (e.g. `torch.arange(...,dtype=torch.float32)` is used), DeepSpeed can automatically cast it down
+ # at init time. See https://github.com/huggingface/transformers/issues/28685 for more info.
+
+ ds_config = {
+ "train_batch_size": 1,
+ "zero_optimization": {
+ "stage": 3,
+ },
+ "bf16": {"enabled": True},
+ }
+
+ dschf = HfDeepSpeedConfig(ds_config)
+
+ self.assertTrue(dschf.is_zero3())
+ self.assertTrue(is_deepspeed_zero3_enabled())
+
+ with LoggingLevel(logging.INFO):
+ with mockenv_context(**self.dist_env_1_gpu):
+ logger = logging.get_logger("transformers.modeling_utils")
+ with CaptureLogger(logger) as cl:
+ model = AutoModel.from_pretrained(GPTJ_TINY)
+ self.assertIn("Detected DeepSpeed ZeRO-3", cl.out)
+
+ # The model weights are in BF16 as per deepspeed config
+ self.assertTrue(str(model.h[0].attn.q_proj.weight.dtype) == "torch.bfloat16")
+ good_deepspeed_sin_cos = model.h[0].attn.embed_positions
+
+ # Monkeypatches the function that creates RoPE embeddings using the INCORRECT torch.arange() pattern, and
+ # then recreates the model
+ def bad_deepspeed_create_sinusoidal_positions(num_pos: int, dim: int) -> torch.Tensor:
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, dtype=torch.int64) / dim))
+ # Incorrect pattern here: torch.arange has dtype=torch.float32 as its argument, and it will automatically
+ # converted to BF16 by DeepSpeed
+ sinusoid_inp = torch.einsum("i , j -> i j", torch.arange(num_pos, dtype=inv_freq.dtype), inv_freq)
+ return torch.cat((torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)), dim=1)
+
+ good_deepspeed_create_sinusoidal_positions = transformers.models.gptj.modeling_gptj.create_sinusoidal_positions
+ transformers.models.gptj.modeling_gptj.create_sinusoidal_positions = bad_deepspeed_create_sinusoidal_positions
+
+ with LoggingLevel(logging.INFO):
+ with mockenv_context(**self.dist_env_1_gpu):
+ logger = logging.get_logger("transformers.modeling_utils")
+ with CaptureLogger(logger) as cl:
+ model = AutoModel.from_pretrained(GPTJ_TINY)
+ self.assertIn("Detected DeepSpeed ZeRO-3", cl.out)
+
+ self.assertTrue(str(model.h[0].attn.q_proj.weight.dtype) == "torch.bfloat16")
+ bad_deepspeed_sin_cos = model.h[0].attn.embed_positions
+
+ # Compares the two values: the two sets of values are different, and the correct one matches the torch
+ # (i.e. outside DeepSpeed) version.
+ good_torch_sin_cos = good_deepspeed_create_sinusoidal_positions(
+ model.config.max_position_embeddings, model.config.rotary_dim
+ )
+ self.assertFalse(torch.allclose(good_deepspeed_sin_cos, bad_deepspeed_sin_cos))
+ torch.testing.assert_close(good_torch_sin_cos, good_deepspeed_sin_cos.cpu())
+
+ # Finally, we can see that the incorrect pattern is okay on vanilla torch, demostrating that this issue is
+ # exclusive to DeepSpeed
+ bad_torch_sin_cos = bad_deepspeed_create_sinusoidal_positions(
+ model.config.max_position_embeddings, model.config.rotary_dim
+ )
+ torch.testing.assert_close(bad_torch_sin_cos, good_torch_sin_cos)
+
+
+class TrainerIntegrationDeepSpeedWithCustomConfig(TestCasePlus):
+ def setUp(self):
+ super().setUp()
+
+ args = TrainingArguments(".")
+ self.n_epochs = args.num_train_epochs
+ self.batch_size = args.train_batch_size
+
+ master_port = get_master_port(real_launcher=False)
+ self.dist_env_1_gpu = {
+ "MASTER_ADDR": "localhost",
+ "MASTER_PORT": master_port,
+ "RANK": "0",
+ "LOCAL_RANK": "0",
+ "WORLD_SIZE": "1",
+ }
+
+ self.ds_config_file = {
+ "zero2": f"{self.test_file_dir_str}/ds_config_zero2.json",
+ "zero3": f"{self.test_file_dir_str}/ds_config_zero3.json",
+ }
+
+ # use self.get_config_dict(stage) to use these to ensure the original is not modified
+ with io.open(self.ds_config_file[ZERO2], "r", encoding="utf-8") as f:
+ config_zero2 = json.load(f)
+ with io.open(self.ds_config_file[ZERO3], "r", encoding="utf-8") as f:
+ config_zero3 = json.load(f)
+ # The following setting slows things down, so don't enable it by default unless needed by a test.
+ # It's in the file as a demo for users since we want everything to work out of the box even if slower.
+ config_zero3["zero_optimization"]["stage3_gather_16bit_weights_on_model_save"] = False
+
+ self.ds_config_dict = {
+ "zero2": config_zero2,
+ "zero3": config_zero3,
+ }
+
+ def tearDown(self):
+ super().tearDown()
+
+ # reset the ds config global so that tests state doesn't leak
+ unset_hf_deepspeed_config()
+
+ def get_config_dict(self, stage):
+ # As some tests modify the dict, always make a copy
+ return deepcopy(self.ds_config_dict[stage])
+
+
+@require_deepspeed
+@require_torch_fp16
+@require_torch_accelerator
+class TrainerIntegrationDeepSpeed(TrainerIntegrationDeepSpeedWithCustomConfig, TrainerIntegrationCommon):
+ """
+
+ This class is for testing directly via get_regression_trainer
+
+ It mixes in `TrainerIntegrationCommon` which already has a lot of helper validation methods
+ which we can re-use here.
+
+ Important: this class' setup can only work with a single gpu because it runs within the current
+ pytest worker. For multi-gpu tests use TestDeepSpeedWithLauncher.
+
+ Note: if any of the tests of this class get run there will be at least one gpu occupied by them
+ until this pytest worker exits. This is because the gpu memory allocated by the cuda-kernels
+ won't be released until this pytest worker exits.
+
+ This may appear as some run-away tests if you watch `nvidia-smi` while other tests that fork new
+ processes are run. So there will be one or two "stale" processes reported in `nvidia-smi`. This
+ is not a bug.
+ """
+
+ # --- These tests are enough to run on one of zero stages --- #
+
+ def test_hf_ds_config_mismatch(self):
+ ds_config = self.get_config_dict(ZERO2)
+
+ # Purposefully configure these values to mismatch TrainingArguments values.
+ # This currently doesn't cover all keys (but it could)
+ per_device_train_batch_size = 2
+ ds_config["train_micro_batch_size_per_gpu"] = per_device_train_batch_size + 2
+
+ ds_config["train_batch_size"] = 1000
+
+ gradient_accumulation_steps = 2
+ ds_config["gradient_accumulation_steps"] = gradient_accumulation_steps + 2
+
+ max_grad_norm = 1.0
+ ds_config["gradient_clipping"] = max_grad_norm + 0.1
+
+ adam_beta1, adam_beta2 = 0.9, 0.99
+ ds_config["optimizer"]["params"]["betas"] = [adam_beta1 - 0.1, adam_beta2 - 0.1]
+
+ fp16 = True
+ ds_config["fp16"]["enabled"] = not fp16
+
+ keys = [
+ "per_device_train_batch_size",
+ "train_batch_size",
+ "gradient_accumulation_steps",
+ "max_grad_norm",
+ "betas",
+ "fp16",
+ ]
+
+ with mockenv_context(**self.dist_env_1_gpu):
+ trainer = get_regression_trainer(
+ local_rank=0,
+ fp16=fp16,
+ deepspeed=ds_config,
+ per_device_train_batch_size=per_device_train_batch_size,
+ gradient_accumulation_steps=gradient_accumulation_steps,
+ max_grad_norm=max_grad_norm,
+ adam_beta1=adam_beta1,
+ adam_beta2=adam_beta2,
+ output_dir=self.get_auto_remove_tmp_dir(),
+ )
+ with self.assertRaises(Exception) as context:
+ trainer.train()
+
+ for key in keys:
+ self.assertTrue(
+ key in str(context.exception),
+ f"{key} is not in the exception message:\n{context.exception}",
+ )
+
+ # Test various combos
+ # 1. DS scheduler + DS optimizer: this is already tested by most other tests
+ # 2. HF scheduler + HF optimizer:
+ # 3. DS scheduler + HF optimizer:
+ # 4. HF scheduler + DS optimizer:
+
+ def test_hf_scheduler_hf_optimizer(self):
+ a = 0
+ with mockenv_context(**self.dist_env_1_gpu):
+ ds_config_zero2_dict = self.get_config_dict(ZERO2)
+ del ds_config_zero2_dict["optimizer"] # force default HF Trainer optimizer
+ del ds_config_zero2_dict["scheduler"] # force default HF Trainer scheduler
+ ds_config_zero2_dict["zero_optimization"]["offload_optimizer"]["device"] = "none"
+ ds_config_zero2_dict["fp16"]["initial_scale_power"] = 1 # force optimizer on the first step
+ trainer = get_regression_trainer(
+ a=a, local_rank=0, fp16=True, deepspeed=ds_config_zero2_dict, output_dir=self.get_auto_remove_tmp_dir()
+ )
+ trainer.train()
+ new_a = trainer.model.a.item()
+ self.assertNotEqual(new_a, a)
+
+ def test_ds_scheduler_hf_optimizer(self):
+ a = 0
+ with mockenv_context(**self.dist_env_1_gpu):
+ ds_config_zero2_dict = self.get_config_dict(ZERO2)
+ del ds_config_zero2_dict["optimizer"] # force default HF Trainer optimizer
+ ds_config_zero2_dict["zero_optimization"]["offload_optimizer"]["device"] = "none"
+ ds_config_zero2_dict["fp16"]["initial_scale_power"] = 1 # force optimizer on the first step
+ trainer = get_regression_trainer(
+ a=a, local_rank=0, fp16=True, deepspeed=ds_config_zero2_dict, output_dir=self.get_auto_remove_tmp_dir()
+ )
+ trainer.train()
+ new_a = trainer.model.a.item()
+ self.assertNotEqual(new_a, a)
+
+ def test_hf_scheduler_ds_optimizer(self):
+ a = 0
+ with mockenv_context(**self.dist_env_1_gpu):
+ ds_config_zero2_dict = self.get_config_dict(ZERO2)
+ del ds_config_zero2_dict["scheduler"] # force default HF Trainer scheduler
+ ds_config_zero2_dict["zero_optimization"]["offload_optimizer"]["device"] = "none"
+ ds_config_zero2_dict["fp16"]["initial_scale_power"] = 1 # force optimizer on the first step
+ trainer = get_regression_trainer(
+ a=a, local_rank=0, fp16=True, deepspeed=ds_config_zero2_dict, output_dir=self.get_auto_remove_tmp_dir()
+ )
+ trainer.train()
+ new_a = trainer.model.a.item()
+ self.assertNotEqual(new_a, a)
+
+ @require_deepspeed_aio
+ def test_stage3_nvme_offload(self):
+ with mockenv_context(**self.dist_env_1_gpu):
+ # this actually doesn't have to be on NVMe, any storage will do since this test only
+ # runs a simple check that we can use some directory as if it were NVMe
+ nvme_path = self.get_auto_remove_tmp_dir()
+ nvme_config = {"device": "nvme", "nvme_path": nvme_path}
+ ds_config_zero3_dict = self.get_config_dict(ZERO3)
+ ds_config_zero3_dict["zero_optimization"]["offload_optimizer"] = nvme_config
+ ds_config_zero3_dict["zero_optimization"]["offload_param"] = nvme_config
+ ds_config_zero3_dict["zero_optimization"]["stage3_gather_16bit_weights_on_model_save"] = True
+ trainer = get_regression_trainer(
+ local_rank=0, fp16=True, deepspeed=ds_config_zero3_dict, output_dir=self.get_auto_remove_tmp_dir()
+ )
+ with CaptureLogger(deepspeed_logger) as cl:
+ trainer.train()
+ self.assertIn("DeepSpeed info", cl.out, "expected DeepSpeed logger output but got none")
+
+ @require_optuna
+ def test_hyperparameter_search(self):
+ with mockenv_context(**self.dist_env_1_gpu):
+ ds_config_zero3_dict = self.get_config_dict(ZERO3)
+
+ # hyperparameter_search requires model_init() to recreate the model for each trial
+ def model_init():
+ config = RegressionModelConfig(a=0, b=0, double_output=False)
+ model = RegressionPreTrainedModel(config)
+ return model
+
+ trainer = get_regression_trainer(
+ local_rank=0,
+ fp16=True,
+ model_init=model_init,
+ deepspeed=ds_config_zero3_dict,
+ output_dir=self.get_auto_remove_tmp_dir(),
+ )
+
+ n_trials = 3
+ with CaptureLogger(deepspeed_logger) as cl:
+ with CaptureStd() as cs:
+ trainer.hyperparameter_search(direction="maximize", n_trials=n_trials)
+ self.assertIn("DeepSpeed info", cl.out, "expected DeepSpeed logger output but got none")
+ self.assertIn(f"Trial {n_trials-1} finished with value", cs.err, "expected hyperparameter_search output")
+ self.assertIn("Best is trial", cs.err, "expected hyperparameter_search output")
+
+ # --- These tests need to run on both zero stages --- #
+
+ @parameterized.expand(params, name_func=parameterized_custom_name_func)
+ def test_hf_optimizer_with_offload(self, stage, dtype):
+ # non-DS optimizers can be used with ZERO-offload (as long as they have both CPU and GPU implementation (except LAMB))
+ ds_config_dict = self.get_config_dict(stage)
+ del ds_config_dict["optimizer"] # force default HF Trainer optimizer
+ # force cpu offload
+ ds_config_dict["zero_optimization"]["offload_optimizer"]["device"] = "cpu"
+ ds_config_dict["zero_force_ds_cpu_optimizer"] = False # offload is not efficient w/o CPUAdam
+ with mockenv_context(**self.dist_env_1_gpu):
+ kwargs = {"local_rank": 0, "deepspeed": ds_config_dict, "output_dir": self.get_auto_remove_tmp_dir()}
+ kwargs[dtype] = True
+ trainer = get_regression_trainer(**kwargs)
+ with CaptureLogger(deepspeed_logger) as cl:
+ trainer.train()
+ self.assertIn("DeepSpeed info", cl.out, "expected DeepSpeed logger output but got none")
+
+ @parameterized.expand(params, name_func=parameterized_custom_name_func)
+ def test_fake_notebook_no_launcher(self, stage, dtype):
+ # this setup emulates a notebook where a launcher needs to be emulated by hand
+
+ # note that unittest resets sys.stdout each test, so `CaptureStd` will work here to capture
+ # DeepSpeed log if this test happens to run first in this pytest worker. But it will fail if
+ # it's run not as a first test as `sys.stdout` will no longer be the same. So we either have
+ # to reset `deepspeed_logger.handlers[0].setStream(sys.stdout)` or directly capture from the deepspeed_logger.
+ with mockenv_context(**self.dist_env_1_gpu):
+ kwargs = {
+ "local_rank": 0,
+ "deepspeed": self.get_config_dict(stage),
+ "output_dir": self.get_auto_remove_tmp_dir(),
+ }
+ kwargs[dtype] = True
+ trainer = get_regression_trainer(**kwargs)
+
+ with CaptureLogger(deepspeed_logger) as cl:
+ trainer.train()
+ self.assertIn("DeepSpeed info", cl.out, "expected DeepSpeed logger output but got none")
+
+ @parameterized.expand(params, name_func=parameterized_custom_name_func)
+ def test_early_get_last_lr(self, stage, dtype):
+ # with deepspeed's fp16 and dynamic loss scale enabled the optimizer/scheduler steps may
+ # not run for the first few dozen steps while loss scale is too large, and thus during
+ # that time `get_last_lr` will fail if called during that warm up stage,
+ #
+ # setting `logging_steps=1` forces an early `trainer._maybe_log_save_evaluate()` which calls
+ # `self.lr_scheduler.get_last_lr()` and originally it'd fail on the very first step.
+ with mockenv_context(**self.dist_env_1_gpu):
+ a = b = 0.0
+ kwargs = {
+ "a": a,
+ "b": b,
+ "local_rank": 0,
+ "train_len": 8,
+ "deepspeed": self.get_config_dict(stage),
+ "per_device_train_batch_size": 8,
+ "logging_steps": 1,
+ "output_dir": self.get_auto_remove_tmp_dir(),
+ }
+ kwargs[dtype] = True
+ trainer = get_regression_trainer(**kwargs)
+
+ trainer.train()
+ post_train_a = trainer.model.a.item()
+
+ # XXX: for some reason the following check fails with zero3/fp16 and any/bf16 - not a
+ # broken but a different qualitative outcome - as if optimizer did run
+ # oddly getting 1.0 for both a and b from 0.0 - there is a bug somewhere
+ # print(trainer.model.a.item())
+ # print(trainer.model.b.item())
+ # need to investigate at some point
+ if (stage == ZERO3 and dtype == FP16) or (dtype == BF16):
+ self.skipTest(reason="When using zero3/fp16 or any/bf16 the optimizer seems run oddly")
+
+ # it's enough that train didn't fail for this test, but we must check that
+ # optimizer/scheduler didn't run (since if it did this test isn't testing the right thing)
+ self.assertEqual(post_train_a, a)
+
+ @parameterized.expand(params, name_func=parameterized_custom_name_func)
+ def test_gradient_accumulation(self, stage, dtype):
+ # this test measures that we get identical weights and similar loss with:
+ # 1. per_device_train_batch_size=8, gradient_accumulation_steps=1
+ # 2. per_device_train_batch_size=4, gradient_accumulation_steps=2
+ # since the 2nd should produce the effective batch of 1st, with the same results
+ #
+ # I can get an identical loss for a small train_len=32, plus the power of the initial
+ # dynamic loss scale value set to:
+ # "fp16.initial_scale_power": 1
+ # plus having the same WarmupLR's warmup_min_lr == warmup_max_lr in the config file
+ # but for some reason going to train_len=64, the weights start to mismatch with this setup.
+ # the culprit seems to be `initial_scale_power` - putting it back to its default 32 keeps the weights identical
+
+ train_len = 64
+ a = b = 0.0
+
+ kwargs = {
+ "a": a,
+ "b": b,
+ "local_rank": 0,
+ "train_len": train_len,
+ "deepspeed": self.get_config_dict(stage),
+ "output_dir": self.get_auto_remove_tmp_dir(),
+ }
+ kwargs[dtype] = True
+
+ with mockenv_context(**self.dist_env_1_gpu):
+ no_grad_accum_trainer = get_regression_trainer(
+ **kwargs,
+ per_device_train_batch_size=16,
+ gradient_accumulation_steps=1,
+ )
+ no_grad_accum_result = no_grad_accum_trainer.train()
+ no_grad_accum_loss = no_grad_accum_result.training_loss
+ no_grad_accum_a = no_grad_accum_trainer.model.a.item()
+ no_grad_accum_b = no_grad_accum_trainer.model.b.item()
+ # make sure the optimizer kicked in - if it hasn't changed from the original value of a then make train_len bigger
+ self.assertNotEqual(no_grad_accum_a, a)
+
+ with mockenv_context(**self.dist_env_1_gpu):
+ yes_grad_accum_trainer = get_regression_trainer(
+ **kwargs,
+ per_device_train_batch_size=4,
+ gradient_accumulation_steps=4,
+ )
+ yes_grad_accum_result = yes_grad_accum_trainer.train()
+ yes_grad_accum_loss = yes_grad_accum_result.training_loss
+ yes_grad_accum_a = yes_grad_accum_trainer.model.a.item()
+ yes_grad_accum_b = yes_grad_accum_trainer.model.b.item()
+ self.assertNotEqual(yes_grad_accum_a, a)
+
+ # training with half the batch size but accumulation steps as 2 should give the same
+ # weights, but sometimes get a slight difference still of 1e-6
+ if torch_device == "hpu":
+ self.assertAlmostEqual(no_grad_accum_a, yes_grad_accum_a, delta=1e-4)
+ self.assertAlmostEqual(no_grad_accum_b, yes_grad_accum_b, delta=1e-4)
+ else:
+ self.assertAlmostEqual(no_grad_accum_a, yes_grad_accum_a, places=5)
+ self.assertAlmostEqual(no_grad_accum_b, yes_grad_accum_b, places=5)
+
+ # Relative difference. See the note above how to get identical loss on a small bs
+ self.assertTrue((no_grad_accum_loss - yes_grad_accum_loss) / (no_grad_accum_loss + 1e-15) <= 1e-3)
+
+ # NOTE: Currently a disabled test. In the future we should re-enable it.
+ # Issue resolves around Zero-3 w/ DPO/TRL + DeepSpeed
+ # As well as Zero-3 inference
+ # Related PR: https://github.com/huggingface/transformers/pull/32299
+ # def test_missed_zero3_init(self):
+ # from transformers import Trainer # noqa
+
+ # with mockenv_context(**self.dist_env_1_gpu):
+ # model = AutoModel.from_pretrained(T5_TINY)
+ # training_args = TrainingArguments(
+ # output_dir="./test_missed_zero3_init",
+ # deepspeed=self.get_config_dict(ZERO3),
+ # )
+ # with self.assertRaises(
+ # ValueError, msg="Model was not initialized with `Zero-3` despite being configured."
+ # ):
+ # _ = Trainer(
+ # model=model,
+ # args=training_args,
+ # )
+ # # Now do it properly, triggered from our `TrainingArguments` earlier
+ # model = AutoModel.from_pretrained(T5_TINY)
+ # trainer = Trainer(
+ # model=model,
+ # args=training_args,
+ # )
+ # assert trainer.is_deepspeed_enabled
+ # assert model._transformers_zero3_init_used
+
+ def check_saved_checkpoints_deepspeed(self, output_dir, freq, total, stage, dtype):
+ # adapted from TrainerIntegrationCommon.check_saved_checkpoints
+ file_list = [SAFE_WEIGHTS_NAME, "training_args.bin", "trainer_state.json", "config.json"]
+
+ if stage == ZERO2:
+ ds_file_list = ["mp_rank_00_model_states.pt"]
+ elif stage == ZERO3:
+ ds_file_list = ["zero_pp_rank_0_mp_rank_00_model_states.pt"]
+ else:
+ raise ValueError(f"unknown stage {stage}")
+
+ if dtype == "bf16":
+ ds_file_list.append("bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt")
+
+ for step in range(freq, total, freq):
+ checkpoint = os.path.join(output_dir, f"checkpoint-{step}")
+ self.assertTrue(os.path.isdir(checkpoint), f"[{stage}] {checkpoint} dir is not found")
+ # common files
+ for filename in file_list:
+ path = os.path.join(checkpoint, filename)
+ self.assertTrue(os.path.isfile(path), f"[{stage}] {path} is not found")
+
+ # ds files
+ ds_path = os.path.join(checkpoint, f"global_step{step}")
+ for filename in ds_file_list:
+ # filename = os.path.join(path, filename)
+ # print(filename)
+ path = os.path.join(ds_path, filename)
+ self.assertTrue(os.path.isfile(path), f"[{stage}] {path} is not found")
+
+ @parameterized.expand(params, name_func=parameterized_custom_name_func)
+ def test_save_checkpoints(self, stage, dtype):
+ # adapted from TrainerIntegrationTest.test_save_checkpoints
+
+ freq = 5
+ output_dir = self.get_auto_remove_tmp_dir()
+ ds_config_dict = self.get_config_dict(stage)
+ if dtype == FP16:
+ ds_config_dict["fp16"]["initial_scale_power"] = 1 # force optimizer on the first step
+ # XXX:
+ if stage == ZERO3:
+ ds_config_dict["zero_optimization"]["stage3_gather_16bit_weights_on_model_save"] = True
+
+ # save checkpoints
+ with mockenv_context(**self.dist_env_1_gpu):
+ kwargs = {
+ "output_dir": output_dir,
+ "save_steps": freq,
+ "deepspeed": ds_config_dict,
+ }
+ kwargs[dtype] = True
+ trainer = get_regression_trainer(**kwargs)
+ trainer.train()
+
+ total = int(self.n_epochs * 64 / self.batch_size)
+ self.check_saved_checkpoints_deepspeed(output_dir, freq, total, stage, dtype)
+
+ @parameterized.expand(params, name_func=parameterized_custom_name_func)
+ def test_can_resume_training_errors(self, stage, dtype):
+ with mockenv_context(**self.dist_env_1_gpu):
+ ds_config_dict = self.get_config_dict(stage)
+ output_dir = self.get_auto_remove_tmp_dir()
+ kwargs = {"output_dir": output_dir, "deepspeed": ds_config_dict}
+ kwargs[dtype] = True
+ trainer = get_regression_trainer(**kwargs)
+
+ # 1. fail to find any checkpoint - due a fresh output_dir
+ with self.assertRaises(Exception) as context:
+ trainer.train(resume_from_checkpoint=True)
+ self.assertTrue(
+ "No valid checkpoint found in output directory" in str(context.exception),
+ f"got exception: {context.exception}",
+ )
+
+ # 2. fail to find a bogus checkpoint
+ with self.assertRaises(Exception) as context:
+ checkpoint = os.path.join(output_dir, "checkpoint-5")
+ trainer.train(resume_from_checkpoint=f"{checkpoint}-bogus")
+
+ @parameterized.expand(params_with_optims_and_schedulers, name_func=parameterized_custom_name_func)
+ def test_can_resume_training_normal(self, stage, dtype, optim, scheduler):
+ # adapted from TrainerIntegrationTest.test_can_resume_training
+ # test normal resume for each stage separately, error-handling is tested in a different test
+
+ # ToDo: Currently, hf_optim + hf_scheduler resumes with the correct states and
+ # also has same losses for few steps but then slowly diverges. Need to figure it out.
+ if optim == HF_OPTIM and scheduler == HF_SCHEDULER:
+ self.skipTest(reason="hf_optim + hf_scheduler resumes with the correct states but slowly diverges")
+
+ output_dir = self.get_auto_remove_tmp_dir("./xxx", after=False)
+ ds_config_dict = self.get_config_dict(stage)
+ if dtype == FP16:
+ ds_config_dict["fp16"]["initial_scale_power"] = 1 # force optimizer on the first step
+ # XXX:
+ if stage == ZERO3:
+ ds_config_dict["zero_optimization"]["stage3_gather_16bit_weights_on_model_save"] = True
+
+ if optim == HF_OPTIM:
+ del ds_config_dict["optimizer"]
+
+ if scheduler == HF_SCHEDULER:
+ del ds_config_dict["scheduler"]
+
+ kwargs = {
+ "output_dir": output_dir,
+ "train_len": 128,
+ "save_steps": 5,
+ "learning_rate": 0.1,
+ "deepspeed": ds_config_dict,
+ }
+ kwargs[dtype] = True
+
+ with mockenv_context(**self.dist_env_1_gpu):
+ trainer = get_regression_trainer(**kwargs)
+ trainer.train()
+ (a, b) = trainer.model.a.item(), trainer.model.b.item()
+ state = dataclasses.asdict(trainer.state)
+
+ checkpoint = os.path.join(output_dir, "checkpoint-5")
+
+ # Reinitialize trainer
+ trainer = get_regression_trainer(**kwargs)
+
+ trainer.train(resume_from_checkpoint=checkpoint)
+ (a1, b1) = trainer.model.a.item(), trainer.model.b.item()
+ state1 = dataclasses.asdict(trainer.state)
+ self.assertEqual(a, a1)
+ self.assertEqual(b, b1)
+ self.check_trainer_state_are_the_same(state, state1)
+
+ # Now check with a later checkpoint that it also works when we span over one epoch
+ checkpoint = os.path.join(output_dir, "checkpoint-15")
+
+ # Reinitialize trainer and load model
+ trainer = get_regression_trainer(**kwargs)
+
+ trainer.train(resume_from_checkpoint=checkpoint)
+ (a1, b1) = trainer.model.a.item(), trainer.model.b.item()
+ state1 = dataclasses.asdict(trainer.state)
+ self.assertEqual(a, a1)
+ self.assertEqual(b, b1)
+ self.check_trainer_state_are_the_same(state, state1)
+
+ # Finally, should be able to resume with the same trainer/same deepspeed engine instance
+ # XXX: but currently this not possible due DS bug: https://github.com/deepspeedai/DeepSpeed/issues/1612
+ # trainer.train(resume_from_checkpoint=checkpoint)
+ # a workaround needs to be used that re-creates the deepspeed engine
+
+ @parameterized.expand(params, name_func=parameterized_custom_name_func)
+ def test_load_state_dict_from_zero_checkpoint(self, stage, dtype):
+ # test that we can load fp32 weights directly from the zero checkpoint into the current model
+
+ output_dir = self.get_auto_remove_tmp_dir() # "./xxx", after=False, before=False)
+
+ ds_config_dict = self.get_config_dict(stage)
+
+ kwargs = {
+ "output_dir": output_dir,
+ "train_len": 4,
+ "per_device_train_batch_size": 4,
+ "num_train_epochs": 1,
+ "save_strategy": "steps",
+ "save_steps": 1,
+ "learning_rate": 0.1,
+ "deepspeed": ds_config_dict,
+ }
+ kwargs[dtype] = True
+
+ with mockenv_context(**self.dist_env_1_gpu):
+ trainer = get_regression_trainer(**kwargs)
+ trainer.train()
+ (a, b) = trainer.model.a.item(), trainer.model.b.item()
+ state = dataclasses.asdict(trainer.state)
+
+ checkpoint_dir = get_last_checkpoint(output_dir)
+ model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
+
+ (a1, b1) = model.a.item(), model.b.item()
+ state1 = dataclasses.asdict(trainer.state)
+ self.assertEqual(a, a1)
+ self.assertEqual(b, b1)
+ self.check_trainer_state_are_the_same(state, state1)
+
+ def test_ds_config_object(self):
+ # test that we can switch from zero2 to zero3 in the same process for example
+ # test is_zero, etc.
+ output_dir = self.get_auto_remove_tmp_dir()
+ kwargs = {"output_dir": output_dir, "train_len": 8, "fp16": True}
+
+ ds_config_zero3_dict = self.get_config_dict(ZERO3)
+ ds_config_zero2_dict = self.get_config_dict(ZERO2)
+
+ with mockenv_context(**self.dist_env_1_gpu):
+ trainer = get_regression_trainer(deepspeed=ds_config_zero3_dict, **kwargs)
+ self.assertTrue(is_deepspeed_zero3_enabled())
+
+ # test we can repeat that and with train this time
+ trainer = get_regression_trainer(deepspeed=ds_config_zero3_dict, **kwargs)
+ trainer.train()
+ self.assertTrue(is_deepspeed_zero3_enabled())
+
+ # test zero3 is disabled
+ trainer = get_regression_trainer(deepspeed=ds_config_zero2_dict, **kwargs)
+ self.assertFalse(is_deepspeed_zero3_enabled())
+
+ # check config obj
+ config = deepspeed_config()
+ self.assertTrue(bool(config), "Deepspeed config should be accessible")
+
+ # with accelerate integration below line is additionally required for this test to pass
+ trainer.accelerator.state._reset_state()
+ del trainer
+ # now weakref should gc the global and we shouldn't get anything here
+ config = deepspeed_config()
+ self.assertFalse(is_deepspeed_zero3_enabled())
+ self.assertFalse(bool(config), "Deepspeed config should not be accessible")
+
+ @parameterized.expand(params, name_func=parameterized_custom_name_func)
+ def test_load_best_model(self, stage, dtype):
+ # Test that forced deepspeed reinit doesn't break the model. the forced re-init after
+ # loading the best model in Trainer is there to workaround this bug in Deepspeed
+ # https://github.com/deepspeedai/DeepSpeed/issues/1612
+ #
+ # The test is derived from a repro script submitted in this Issue:
+ # https://github.com/huggingface/transformers/issues/17114
+ #
+ # One additional feature of this test is that we use a non-AdamW optimizer to test that
+ # deepspeed doesn't fallback to AdamW, which would prevent the optimizer states from loading
+ # correctly
+
+ from transformers import T5ForConditionalGeneration, T5Tokenizer, Trainer # noqa
+
+ output_dir = self.get_auto_remove_tmp_dir() # "./xxx", after=False, before=False)
+
+ ds_config_dict = self.get_config_dict(stage)
+ del ds_config_dict["optimizer"] # will use HF Trainer optimizer
+ del ds_config_dict["scheduler"] # will use HF Trainer scheduler
+ ds_config_dict["zero_force_ds_cpu_optimizer"] = False # offload is not efficient w/o CPUAdam
+ # must use this setting to get the reload path exercised
+ ds_config_dict["zero_optimization"]["stage3_gather_16bit_weights_on_model_save"] = True
+
+ with mockenv_context(**self.dist_env_1_gpu):
+ args_dict = {
+ "per_device_train_batch_size": 1,
+ "per_device_eval_batch_size": 1,
+ "gradient_accumulation_steps": 1,
+ "learning_rate": 1e-4,
+ "num_train_epochs": 1,
+ "do_train": True,
+ "do_eval": True,
+ "optim": "adafactor",
+ "eval_strategy": "steps",
+ "eval_steps": 1,
+ "save_strategy": "steps",
+ "save_steps": 1,
+ "load_best_model_at_end": True,
+ "max_steps": 1,
+ "deepspeed": ds_config_dict,
+ "report_to": "none",
+ }
+
+ training_args = TrainingArguments(output_dir, **args_dict)
+ tokenizer = T5Tokenizer.from_pretrained(T5_TINY)
+ model = T5ForConditionalGeneration.from_pretrained(T5_TINY)
+
+ def _add_eos_to_examples(example):
+ example["input_text"] = f"question: {example['question']} context: {example['context']}"
+ example["target_text"] = example["answers"]["text"][0] if len(example["answers"]["text"]) > 0 else ""
+ return example
+
+ def _convert_to_features(example_batch):
+ input_encodings = tokenizer.batch_encode_plus(
+ example_batch["input_text"], pad_to_max_length=True, max_length=512, truncation=True
+ )
+ target_encodings = tokenizer.batch_encode_plus(
+ example_batch["target_text"], pad_to_max_length=True, max_length=16, truncation=True
+ )
+
+ encodings = {
+ "input_ids": input_encodings["input_ids"],
+ "attention_mask": input_encodings["attention_mask"],
+ "labels": target_encodings["input_ids"],
+ }
+
+ return encodings
+
+ def get_dataset():
+ data_file = str(self.tests_dir / "fixtures/tests_samples/SQUAD/sample.json")
+ data_files = {"train": data_file, "validation": data_file}
+ raw_datasets = datasets.load_dataset("json", data_files=data_files, field="data")
+ train_dataset = raw_datasets["train"].map(_add_eos_to_examples).map(_convert_to_features, batched=True)
+ valid_dataset = deepcopy(train_dataset)
+ return train_dataset, valid_dataset
+
+ train_dataset, eval_dataset = get_dataset()
+
+ trainer = Trainer(
+ model=model,
+ processing_class=tokenizer,
+ args=training_args,
+ train_dataset=train_dataset,
+ eval_dataset=eval_dataset,
+ )
+ trainer.train() # crash 1 was here
+ trainer.evaluate() # crash 2 was here
+
+
+@slow
+@run_first
+@require_deepspeed
+@require_torch_accelerator
+class TestDeepSpeedWithLauncher(TestCasePlus):
+ """This class is for testing via an external script - can do multiple gpus"""
+
+ # Tests to devise #
+ #
+ # 1. predict_with_generate on multigpu - need to figure out how to give input sequences so that
+ # the 2 gpus will generate prediction sequences that aren't of the same length - this is because
+ # we had to code a special feature to sync the gpus when the predicted sequences aren't of the
+ # same length. In general this will tested as a side-effect through a variety of other tests -
+ # it'll simply hang trying to synchronize with other gpus if this problem is encountered. So as
+ # long as we have a few full tests running on zero3 + predict_with_generate this should be
+ # mostly covered.
+ #
+ # but there are 5 variations on beam search in `generate`- with identical code branched with `if
+ # synced_gpus`
+ #
+ # 2. most tests should probably be run on both: zero2 and zero3 configs
+ #
+
+ @parameterized.expand(params, name_func=parameterized_custom_name_func)
+ @require_torch_multi_accelerator
+ def test_basic_distributed(self, stage, dtype):
+ self.run_and_check(stage=stage, dtype=dtype, distributed=True)
+
+ @require_torch_fp16
+ def test_do_eval_no_train(self):
+ # testing only zero3 since zero2 makes no sense with inference
+ self.run_and_check(
+ stage=ZERO3,
+ dtype=FP16,
+ eval_steps=1,
+ distributed=False,
+ do_train=False,
+ do_eval=True,
+ )
+
+ @parameterized.expand(params, name_func=parameterized_custom_name_func)
+ def test_fp32_non_distributed(self, stage, dtype):
+ # real model needs too much GPU memory under stage2+fp32, so using tiny random model here -
+ # therefore no quality checks, just basic completion checks are done
+ self.run_and_check(
+ stage=stage,
+ dtype=dtype,
+ model_name=T5_TINY,
+ distributed=False,
+ do_train=True,
+ do_eval=True,
+ quality_checks=False,
+ fp32=True,
+ )
+
+ @parameterized.expand(params, name_func=parameterized_custom_name_func)
+ @require_torch_multi_accelerator
+ def test_fp32_distributed(self, stage, dtype):
+ # real model needs too much GPU memory under stage2+fp32, so using tiny random model here -
+ # therefore no quality checks, just basic completion checks are done
+ self.run_and_check(
+ stage=stage,
+ dtype=dtype,
+ model_name=T5_TINY,
+ distributed=True,
+ do_train=True,
+ do_eval=True,
+ quality_checks=False,
+ fp32=True,
+ )
+
+ @parameterized.expand(params, name_func=parameterized_custom_name_func)
+ def test_resume_train_not_from_ds_checkpoint(self, stage, dtype):
+ # do normal training and then resume not from the deepspeed checkpoint but explicitly from
+ # the saved model dir
+
+ do_train = True
+ do_eval = False
+ kwargs = {
+ "stage": stage,
+ "dtype": dtype,
+ "eval_steps": 1,
+ "distributed": True,
+ "do_train": do_train,
+ "do_eval": do_eval,
+ }
+
+ # 1. normal training
+ output_dir = self.run_and_check(**kwargs)
+
+ # 2. now resume explicitly from the saved weights, by passing --model_name_or_path output_dir
+ # - i.e. the same path the model was saved to in step 1
+ output_dir = self.run_trainer(**kwargs, model_name=output_dir)
+
+ self.do_checks(output_dir, do_train=do_train, do_eval=do_eval)
+
+ @parameterized.expand(["bf16", "fp16", "fp32"])
+ @require_torch_multi_accelerator
+ def test_inference(self, dtype):
+ if dtype == "bf16" and not is_torch_bf16_available_on_device(torch_device):
+ self.skipTest(reason="test requires bfloat16 hardware support")
+
+ if dtype == "fp16" and not is_torch_fp16_available_on_device(torch_device):
+ self.skipTest(reason="test requires fp16 hardware support")
+
+ # this is just inference, so no optimizer should be loaded
+ # it only works for z3 (makes no sense with z1-z2)
+ fp32 = True if dtype == "fp32" else False
+ self.run_and_check(
+ stage=ZERO3,
+ dtype=dtype,
+ model_name=T5_TINY,
+ distributed=True,
+ do_train=False,
+ do_eval=True,
+ quality_checks=False,
+ fp32=fp32,
+ )
+
+ def do_checks(self, output_dir, do_train=True, do_eval=True, quality_checks=True):
+ if do_train:
+ train_metrics = load_json(os.path.join(output_dir, "train_results.json"))
+ self.assertIn("train_samples_per_second", train_metrics)
+ if quality_checks:
+ self.assertGreater(train_metrics["train_samples_per_second"], 0.5)
+
+ if do_eval:
+ eval_metrics = load_json(os.path.join(output_dir, "eval_results.json"))
+ self.assertIn("eval_bleu", eval_metrics)
+ if quality_checks:
+ self.assertGreater(eval_metrics["eval_bleu"], 1)
+
+ # XXX: need to do better validation beyond just that the run was successful
+ def run_and_check(
+ self,
+ stage,
+ dtype,
+ model_name: str = T5_SMALL,
+ eval_steps: int = 10,
+ distributed: bool = True,
+ do_train: bool = True,
+ do_eval: bool = True,
+ quality_checks: bool = True,
+ fp32: bool = False,
+ extra_args_str: str = None,
+ remove_args_str: str = None,
+ ):
+ # we are doing quality testing so using a small real model
+ output_dir = self.run_trainer(
+ stage=stage,
+ dtype=dtype,
+ model_name=model_name,
+ eval_steps=eval_steps,
+ num_train_epochs=1,
+ do_train=do_train,
+ do_eval=do_eval,
+ distributed=distributed,
+ fp32=fp32,
+ extra_args_str=extra_args_str,
+ remove_args_str=remove_args_str,
+ )
+
+ self.do_checks(output_dir, do_train=do_train, do_eval=do_eval, quality_checks=quality_checks)
+
+ return output_dir
+
+ def run_trainer(
+ self,
+ stage: str,
+ dtype: str,
+ model_name: str,
+ eval_steps: int = 10,
+ num_train_epochs: int = 1,
+ do_train: bool = False,
+ do_eval: bool = True,
+ distributed: bool = True,
+ fp32: bool = False,
+ extra_args_str: str = None,
+ remove_args_str: str = None,
+ ):
+ max_len = 32
+ data_dir = self.test_file_dir / "../fixtures/tests_samples/wmt_en_ro"
+ output_dir = self.get_auto_remove_tmp_dir()
+ args = f"""
+ --model_name_or_path {model_name}
+ --train_file {data_dir}/train.json
+ --validation_file {data_dir}/val.json
+ --output_dir {output_dir}
+ --overwrite_output_dir
+ --max_source_length {max_len}
+ --max_target_length {max_len}
+ --val_max_target_length {max_len}
+ --warmup_steps 8
+ --predict_with_generate
+ --save_steps 0
+ --eval_steps {eval_steps}
+ --group_by_length
+ --label_smoothing_factor 0.1
+ --source_lang en
+ --target_lang ro
+ --report_to none
+ """.split()
+ args.extend(["--source_prefix", '"translate English to Romanian: "'])
+
+ if not fp32:
+ args.extend([f"--{dtype}"])
+
+ actions = 0
+ if do_train:
+ actions += 1
+ args.extend(
+ f"""
+ --do_train
+ --num_train_epochs {str(num_train_epochs)}
+ --max_train_samples 16
+ --per_device_train_batch_size 2
+ --learning_rate 3e-3
+ """.split()
+ )
+
+ if do_eval:
+ actions += 1
+ args.extend(
+ """
+ --do_eval
+ --max_eval_samples 16
+ --per_device_eval_batch_size 2
+ """.split()
+ )
+
+ assert actions > 0, "need at least do_train or do_eval for the test to run"
+
+ if extra_args_str is not None:
+ args.extend(extra_args_str.split())
+
+ # currently only works for bool args
+ if remove_args_str is not None:
+ remove_args = remove_args_str.split()
+ args = [x for x in args if x not in remove_args]
+
+ ds_args = f"--deepspeed {self.test_file_dir_str}/ds_config_{stage}.json".split()
+ script = [f"{self.examples_dir_str}/pytorch/translation/run_translation.py"]
+ launcher = get_launcher(distributed)
+
+ cmd = launcher + script + args + ds_args
+ # keep for quick debug
+ # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
+ execute_subprocess_async(cmd, env=self.get_env())
+
+ return output_dir
+
+ @parameterized.expand(params, name_func=parameterized_custom_name_func)
+ def test_clm(self, stage, dtype):
+ # this test exercises model.resize_token_embeddings() which requires param gathering outside
+ # of forward - it's not used by `run_translation.py`, but it is in `run_clm.py`
+
+ data_dir = self.tests_dir / "fixtures"
+ output_dir = self.get_auto_remove_tmp_dir()
+ args = f"""
+ --model_name_or_path {GPT2_TINY}
+ --train_file {data_dir}/sample_text.txt
+ --validation_file {data_dir}/sample_text.txt
+ --output_dir {output_dir}
+ --overwrite_output_dir
+ --do_train
+ --do_eval
+ --max_train_samples 16
+ --max_eval_samples 16
+ --per_device_train_batch_size 2
+ --per_device_eval_batch_size 2
+ --num_train_epochs 1
+ --warmup_steps 8
+ --block_size 64
+ --report_to none
+ """.split()
+
+ args.extend([f"--{dtype}"])
+
+ ds_args = f"--deepspeed {self.test_file_dir_str}/ds_config_{stage}.json".split()
+ script = [f"{self.examples_dir_str}/pytorch/language-modeling/run_clm.py"]
+ launcher = get_launcher(distributed=True)
+
+ cmd = launcher + script + args + ds_args
+ # keep for quick debug
+ # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
+ execute_subprocess_async(cmd, env=self.get_env())
+
+ @require_torch_fp16
+ def test_clm_from_config_zero3_fp16(self):
+ # this test exercises AutoModel.from_config(config) - to ensure zero.Init is called
+
+ data_dir = self.tests_dir / "fixtures"
+ output_dir = self.get_auto_remove_tmp_dir()
+ args = f"""
+ --model_type gpt2
+ --tokenizer_name {GPT2_TINY}
+ --train_file {data_dir}/sample_text.txt
+ --validation_file {data_dir}/sample_text.txt
+ --output_dir {output_dir}
+ --overwrite_output_dir
+ --do_train
+ --max_train_samples 4
+ --per_device_train_batch_size 2
+ --num_train_epochs 1
+ --warmup_steps 8
+ --block_size 8
+ --fp16
+ --report_to none
+ """.split()
+
+ ds_args = f"--deepspeed {self.test_file_dir_str}/ds_config_zero3.json".split()
+ script = [f"{self.examples_dir_str}/pytorch/language-modeling/run_clm.py"]
+ launcher = get_launcher(distributed=True)
+
+ cmd = launcher + script + args + ds_args
+ # keep for quick debug
+ # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
+ with CaptureStderr() as cs:
+ execute_subprocess_async(cmd, env=self.get_env())
+ self.assertIn("Detected DeepSpeed ZeRO-3", cs.err)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/deepspeed/test_model_zoo.py b/tasks/tasksmith-441eeab80047/tests/source/tests/deepspeed/test_model_zoo.py
new file mode 100644
index 0000000000000000000000000000000000000000..dba3e18abbd41bb0bcadc816cc9f45025722c97c
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/deepspeed/test_model_zoo.py
@@ -0,0 +1,372 @@
+# 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 itertools
+import os
+import subprocess
+from os.path import dirname
+
+from parameterized import parameterized
+
+from tests.trainer.test_trainer import TrainerIntegrationCommon # noqa
+from transformers import is_torch_available
+from transformers.testing_utils import (
+ TestCasePlus,
+ backend_device_count,
+ execute_subprocess_async,
+ get_tests_dir,
+ require_deepspeed,
+ require_torch_accelerator,
+ slow,
+ torch_device,
+)
+from transformers.trainer_utils import set_seed
+
+
+if is_torch_available():
+ from tests.trainer.test_trainer import ( # noqa
+ RegressionModelConfig,
+ RegressionPreTrainedModel,
+ get_regression_trainer,
+ )
+
+
+set_seed(42)
+
+FIXTURE_DIRECTORY = get_tests_dir("fixtures")
+ROOT_DIRECTORY = os.path.join(dirname(get_tests_dir()))
+DS_TESTS_DIRECTORY = dirname(os.path.abspath(__file__))
+
+# default torch.distributed port
+DEFAULT_MASTER_PORT = "10999"
+
+T5_SMALL = "google-t5/t5-small"
+
+# *** Working Models ***
+ALBERT_TINY = "hf-internal-testing/tiny-albert"
+BART_TINY = "sshleifer/bart-tiny-random"
+BERT_TINY = "hf-internal-testing/tiny-bert"
+BIGBIRD_PEGASUS_TINY = "hf-internal-testing/tiny-random-bigbird_pegasus"
+BIG_BIRD_TINY = "hf-internal-testing/tiny-random-big_bird"
+BLENDERBOT_TINY = "hf-internal-testing/tiny-random-blenderbot"
+BLOOM_TINY = "bigscience/bigscience-small-testing"
+DEBERTA_TINY = "hf-internal-testing/tiny-random-deberta"
+DEBERTA_V2_TINY = "hf-internal-testing/tiny-random-deberta-v2"
+DISTILBERT_TINY = "sshleifer/tiny-distilbert-base-cased"
+ELECTRA_TINY = "hf-internal-testing/tiny-electra"
+FLAUBERT_TINY = "hf-internal-testing/tiny-random-flaubert"
+FSMT_TINY = "stas/tiny-wmt19-en-de"
+FUNNEL_TINY = "hf-internal-testing/tiny-random-funnel"
+GPT2_TINY = "sshleifer/tiny-gpt2"
+GPTJ_TINY = "hf-internal-testing/tiny-random-gptj"
+GPT_NEO_TINY = "hf-internal-testing/tiny-random-gpt_neo"
+LAYOUTLM_TINY = "hf-internal-testing/tiny-layoutlm"
+LED_TINY = "hf-internal-testing/tiny-random-led"
+LONGFORMER_TINY = "hf-internal-testing/tiny-random-longformer"
+M2M_100_TINY = "stas/tiny-m2m_100" # hf tiny model is unsuitable
+MARIAN_TINY = "sshleifer/tiny-marian-en-de"
+MBART_TINY = "sshleifer/tiny-mbart"
+MOBILEBERT_TINY = "hf-internal-testing/tiny-random-mobilebert"
+MPNET_TINY = "hf-internal-testing/tiny-random-mpnet"
+PEGASUS_TINY = "stas/pegasus-cnn_dailymail-tiny-random"
+PROPHETNET_TINY = "hf-internal-testing/tiny-random-prophetnet"
+ROBERTA_TINY = "sshleifer/tiny-distilroberta-base"
+SQUEEZEBERT_TINY = "hf-internal-testing/tiny-random-squeezebert"
+T5_TINY = "patrickvonplaten/t5-tiny-random"
+T5_V1_TINY = "hf-internal-testing/tiny-random-t5-v1.1"
+VIT_TINY = "hf-internal-testing/tiny-random-vit"
+XLM_ROBERTA_TINY = "hf-internal-testing/tiny-xlm-roberta"
+XLNET_TINY = "sshleifer/tiny-xlnet-base-cased"
+
+
+# *** To Fix ***
+
+
+# *** tiny model issues ***
+# missing model files:
+MT5_TINY = "hf-internal-testing/tiny-random-mt5"
+CAMEMBERT_TINY = "hf-internal-testing/tiny-random-camembert"
+OPENAI_GPT_TINY = "hf-internal-testing/tiny-random-openai-gpt"
+
+# missing tokenizer files
+CONVBERT_TINY = "hf-internal-testing/tiny-random-convbert"
+LAYOUTLMV2_TINY = "hf-internal-testing/tiny-random-layoutlmv2"
+HUBERT_TINY = "hf-internal-testing/tiny-random-hubert"
+
+# issues with tokenizer
+CTRL_TINY = "hf-internal-testing/tiny-random-ctrl"
+TRANSFO_XL_TINY = "hf-internal-testing/tiny-random-transfo-xl" # same as Salesforce/ctrl
+
+# other issues with tiny models
+IBERT_TINY = "hf-internal-testing/tiny-random-ibert" # multiple issues with either mlm/qa/clas
+REFORMER_TINY = "hf-internal-testing/tiny-random-reformer" # multiple issues with either mlm/qa/clas
+
+# *** Lacking official examples to test with ***
+# or not working with examples
+DPR_TINY = "hf-internal-testing/tiny-random-dpr"
+# - "dpr" examples/research_projects/rag-end2end-retriever/
+RAG_TINY = "hf-internal-testing/tiny-random-rag"
+# - "rag" research_projects
+LUKE_TINY = ""
+# - "luke" Entities classes - no plan to make such example
+LXMERT_TINY = "hf-internal-testing/tiny-random-lxmert"
+# - "lxmert" doesn't work with run_qa.py
+CLIP_TINY = "hf-internal-testing/tiny-random-clip"
+# - "clip" nothing under pytorch examples - XXX: Suraj is working on adding some - check by end of Sep
+SPEECH_TO_TEXT_TINY = "hf-internal-testing/tiny-random-speech_to_text"
+# - "speech_to_text", nothing under pytorch examples
+
+
+# *** Reactive mode ***
+# models with low usage, unstable API, things about to change - do nothing about the following until someone runs into a problem
+TAPAS_TINY = "hf-internal-testing/tiny-random-tapas"
+# additional notes on tapas
+# 1. "Table must be of type pd.DataFrame" failure
+
+
+# TODO: new models to add:
+#
+
+
+def get_launcher(distributed=False):
+ # 1. explicitly set --num_nodes=1 just in case these tests end up run on a multi-node setup
+ # - it won't be able to handle that
+ # 2. for now testing with just 2 gpus max (since some quality tests may give different
+ # results with mode gpus because we use very little data)
+ num_gpus = min(2, backend_device_count(torch_device)) if distributed else 1
+ master_port = os.environ.get("DS_TEST_PORT", DEFAULT_MASTER_PORT)
+ return f"deepspeed --num_nodes 1 --num_gpus {num_gpus} --master_port {master_port}".split()
+
+
+def make_task_cmds():
+ data_dir_samples = f"{FIXTURE_DIRECTORY}/tests_samples"
+ data_dir_wmt = f"{data_dir_samples}/wmt_en_ro"
+ data_dir_xsum = f"{data_dir_samples}/xsum"
+ args_main = """
+ --do_train
+ --max_train_samples 4
+ --per_device_train_batch_size 2
+ --num_train_epochs 1
+ --fp16
+ --report_to none
+ --overwrite_output_dir
+ """.split()
+
+ # try to cover as many models as possible once (it's enough to run on one task per model)
+ # but need a tiny model for each
+ #
+ # should have "{model_type.upper()}_TINY" corresponding vars defined, e.g., T5_TINY, etc.
+ tasks2models = {
+ "trans": [
+ "bart",
+ "fsmt",
+ "m2m_100",
+ "marian",
+ "mbart",
+ "t5",
+ "t5_v1",
+ # "mt5", missing model files
+ ],
+ "sum": [
+ "pegasus",
+ ],
+ "clm": [
+ "big_bird",
+ "bigbird_pegasus",
+ "blenderbot",
+ "bloom",
+ "gpt2",
+ "gpt_neo",
+ "gptj",
+ "xlm-roberta",
+ "prophetnet",
+ # "camembert", missing model files
+ ],
+ "mlm": [
+ "albert",
+ "deberta",
+ "deberta-v2",
+ "distilbert",
+ "electra",
+ "flaubert",
+ "funnel",
+ "layoutlm",
+ # "reformer", # multiple issues with either mlm/qa/clas
+ ],
+ "qa": [
+ "led",
+ "longformer",
+ "mobilebert",
+ "mpnet",
+ "roberta",
+ "squeezebert",
+ # "convbert", # missing tokenizer files
+ # "layoutlmv2", missing model files
+ ],
+ "clas": [
+ "bert",
+ "xlnet",
+ # "hubert", # missing tokenizer files
+ # "ibert", # multiple issues with either mlm/qa/clas
+ # "transfo-xl", # tokenizer issues as Salesforce/ctrl
+ # "Salesforce/ctrl", # tokenizer issues
+ # "openai-community/openai-gpt", missing model files
+ # "tapas", multiple issues
+ ],
+ "img_clas": [
+ "vit",
+ ],
+ }
+
+ scripts_dir = f"{ROOT_DIRECTORY}/examples/pytorch"
+
+ tasks = {
+ "trans": f"""
+ {scripts_dir}/translation/run_translation.py
+ --train_file {data_dir_wmt}/train.json
+ --source_lang en
+ --target_lang ro
+ --max_source_length 12
+ --max_target_length 12
+ """,
+ "sum": f"""
+ {scripts_dir}/summarization/run_summarization.py
+ --train_file {data_dir_xsum}/sample.json
+ --max_source_length 12
+ --max_target_length 12
+ --lang en
+ """,
+ "clm": f"""
+ {scripts_dir}/language-modeling/run_clm.py
+ --train_file {FIXTURE_DIRECTORY}/sample_text.txt
+ --block_size 8
+ """,
+ "mlm": f"""
+ {scripts_dir}/language-modeling/run_mlm.py
+ --train_file {FIXTURE_DIRECTORY}/sample_text.txt
+ """,
+ "qa": f"""
+ {scripts_dir}/question-answering/run_qa.py
+ --train_file {data_dir_samples}/SQUAD/sample.json
+ """,
+ "clas": f"""
+ {scripts_dir}/text-classification/run_glue.py
+ --train_file {data_dir_samples}/MRPC/train.csv
+ --max_seq_length 12
+ --task_name MRPC
+ """,
+ "img_clas": f"""
+ {scripts_dir}/image-classification/run_image_classification.py
+ --dataset_name hf-internal-testing/cats_vs_dogs_sample
+ --trust_remote_code
+ --remove_unused_columns False
+ --max_steps 10
+ --image_processor_name {DS_TESTS_DIRECTORY}/vit_feature_extractor.json
+ --label_column_name labels
+ """,
+ }
+
+ launcher = get_launcher(distributed=True)
+
+ cmds = {}
+ for task, args in tasks.items():
+ args = args.split()
+ for model in tasks2models[task]:
+ model_name = globals()[f"{model.upper().replace('-', '_')}_TINY"]
+ args_model = f"--model_name_or_path {model_name}".split()
+ cmds[f"{task}_{model}"] = launcher + args + args_model + args_main
+
+ # # generation special case
+ # if task == "gen":
+ # launcher = f"deepspeed --num_nodes 1 --num_gpus 1".split()
+ # args_model += f"--model_type {model}".split()
+ # cmds[f"{task}_{model}"] = launcher + args + args_model
+ # else:
+
+ return cmds
+
+
+task_cmds = make_task_cmds()
+
+ZERO2 = "zero2"
+ZERO3 = "zero3"
+
+stages = [ZERO2, ZERO3]
+
+# future preparation:
+# for now test just fp16, as these tests are quite slow
+# FP16 = "fp16"
+# BF16 = "bf16"
+#
+# dtypes = [FP16]
+# so just hardcoding --fp16 for now
+# if is_torch_bf16_gpu_available():
+# dtypes += [BF16]
+
+
+def parameterized_custom_name_func(func, param_num, param):
+ # customize the test name generator function as we want both params to appear in the sub-test
+ # name, as by default it shows only the first param
+ param_based_name = parameterized.to_safe_name("_".join(str(x) for x in param.args))
+ return f"{func.__name__}_{param_based_name}"
+
+
+# Cartesian-product of zero stages with models to test
+params = list(itertools.product(stages, task_cmds.keys()))
+
+
+@slow
+@require_deepspeed
+@require_torch_accelerator
+class TestDeepSpeedModelZoo(TestCasePlus):
+ """This class is for testing via an external script - can do multiple gpus"""
+
+ def get_task_cmd(self, task, stage):
+ # return a ready to run train cmd
+ if task not in task_cmds:
+ raise ValueError(f"don't know of task {task}, have {task_cmds.keys()}")
+
+ cmd = task_cmds[task]
+ args_ds = f"--deepspeed {self.test_file_dir_str}/ds_config_{stage}.json".split()
+
+ output_dir = self.get_auto_remove_tmp_dir()
+ args_out = f"--output_dir {output_dir}".split()
+
+ cmd += args_ds + args_out
+
+ return cmd, output_dir
+
+ @parameterized.expand(params, name_func=parameterized_custom_name_func)
+ def test_zero_to_fp32(self, stage, task):
+ # testing the ability to do a run followed by recovery of full fp32 weights
+
+ cmd, output_dir = self.get_task_cmd(task, stage)
+
+ # 1. generate the checkpoint
+ cmd += "--save_steps 1".split()
+ # keep for quick debug
+ # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] + cmd)); die
+ execute_subprocess_async(cmd, env=self.get_env())
+
+ # 2. test that the fp32 weights get reconsolidated
+ chkpt_dir = f"{output_dir}/checkpoint-1"
+ recovered_model_path = f"{chkpt_dir}/out.bin"
+ cmd = f"{chkpt_dir}/zero_to_fp32.py {chkpt_dir} {recovered_model_path}"
+ # keep for quick debug
+ # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
+ subprocess.check_call(cmd, shell=True)
+ assert os.path.exists(recovered_model_path), f"{recovered_model_path} was not found"
+
+ # possibly could also test that the resulting saved model is usable but given that we use
+ # random models we won't know if it's any good
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/deepspeed/vit_feature_extractor.json b/tasks/tasksmith-441eeab80047/tests/source/tests/deepspeed/vit_feature_extractor.json
new file mode 100644
index 0000000000000000000000000000000000000000..bfe5a331249fa823a8189a1486209a19bfe870fc
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/deepspeed/vit_feature_extractor.json
@@ -0,0 +1,4 @@
+{
+ "feature_extractor_type": "ViTFeatureExtractor",
+ "size": 30
+}
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/extended/test_trainer_ext.py b/tasks/tasksmith-441eeab80047/tests/source/tests/extended/test_trainer_ext.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f6cf7dffa1ea3c2242871eb2254180a631fafb0
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/extended/test_trainer_ext.py
@@ -0,0 +1,363 @@
+# 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 math
+import os
+import re
+import sys
+from pathlib import Path
+from typing import Tuple
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from transformers.testing_utils import (
+ CaptureStderr,
+ ExtendSysPath,
+ TestCasePlus,
+ backend_device_count,
+ execute_subprocess_async,
+ get_torch_dist_unique_port,
+ require_apex,
+ require_bitsandbytes,
+ require_non_xpu,
+ require_torch,
+ require_torch_gpu,
+ require_torch_multi_accelerator,
+ require_torch_non_multi_accelerator,
+ slow,
+ torch_device,
+)
+from transformers.trainer_callback import TrainerState
+from transformers.trainer_utils import set_seed
+
+
+bindir = os.path.abspath(os.path.dirname(__file__))
+with ExtendSysPath(f"{bindir}/../../examples/pytorch/translation"):
+ from run_translation import main # noqa
+
+
+set_seed(42)
+MARIAN_MODEL = "sshleifer/student_marian_en_ro_6_1"
+MBART_TINY = "sshleifer/tiny-mbart"
+
+
+@require_torch
+class TestTrainerExt(TestCasePlus):
+ def run_seq2seq_quick(
+ self,
+ distributed=False,
+ extra_args_str=None,
+ predict_with_generate=True,
+ do_train=True,
+ do_eval=True,
+ do_predict=True,
+ n_gpus_to_use=None,
+ ):
+ output_dir = self.run_trainer(
+ eval_steps=1,
+ max_len=12,
+ model_name=MBART_TINY,
+ num_train_epochs=1,
+ distributed=distributed,
+ extra_args_str=extra_args_str,
+ predict_with_generate=predict_with_generate,
+ do_train=do_train,
+ do_eval=do_eval,
+ do_predict=do_predict,
+ n_gpus_to_use=n_gpus_to_use,
+ )
+ logs = TrainerState.load_from_json(os.path.join(output_dir, "trainer_state.json")).log_history
+
+ if not do_eval:
+ self.skipTest(reason="do_eval is False")
+
+ eval_metrics = [log for log in logs if "eval_loss" in log.keys()]
+
+ first_step_stats = eval_metrics[0]
+ if predict_with_generate:
+ assert "eval_bleu" in first_step_stats
+
+ last_step_stats = eval_metrics[-1]
+ assert isinstance(last_step_stats["eval_bleu"], float)
+ assert not math.isnan(float(last_step_stats["eval_loss"])), "eval_loss must not be `nan`"
+
+ @require_torch_non_multi_accelerator
+ def test_run_seq2seq_no_dist(self):
+ self.run_seq2seq_quick()
+
+ # verify that the trainer can handle non-distributed with n_gpu > 1
+ @require_torch_multi_accelerator
+ def test_run_seq2seq_dp(self):
+ self.run_seq2seq_quick(distributed=False)
+
+ # verify that the trainer can handle distributed with n_gpu > 1
+ @require_torch_multi_accelerator
+ def test_run_seq2seq_ddp(self):
+ self.run_seq2seq_quick(distributed=True)
+
+ @require_non_xpu
+ @require_apex
+ @require_torch_gpu
+ def test_run_seq2seq_apex(self):
+ # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same
+ # program and it breaks other tests that run from the same pytest worker, therefore until this is
+ # sorted out it must be run only in an external program, that is distributed=True in this
+ # test and only under one or more gpus - if we want cpu will need to make a special test
+ #
+ # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via
+ # 2nd main() call it botches the future eval.
+ #
+ self.run_seq2seq_quick(distributed=True, extra_args_str="--fp16 --fp16_backend=apex")
+ # test 2nd time - was getting eval_loss': nan'
+ # to reproduce the problem set distributed=False
+ self.run_seq2seq_quick(distributed=True, extra_args_str="--fp16 --fp16_backend=apex")
+
+ @parameterized.expand(["base", "low", "high", "mixed"])
+ @require_torch_multi_accelerator
+ def test_trainer_log_level_replica(self, experiment_id):
+ # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout
+ experiments = {
+ # test with the default log_level - should be info and thus log info once
+ "base": {"extra_args_str": "", "n_matches": 1},
+ # test with low log_level and log_level_replica - should be noisy on all processes
+ # now the info string should appear twice on 2 processes
+ "low": {"extra_args_str": "--log_level debug --log_level_replica debug", "n_matches": 2},
+ # test with high log_level and low log_level_replica
+ # now the info string should appear once only on the replica
+ "high": {"extra_args_str": "--log_level error --log_level_replica debug", "n_matches": 1},
+ # test with high log_level and log_level_replica - should be quiet on all processes
+ "mixed": {"extra_args_str": "--log_level error --log_level_replica error", "n_matches": 0},
+ }
+
+ data = experiments[experiment_id]
+ kwargs = {
+ "distributed": True,
+ "predict_with_generate": False,
+ "do_eval": False,
+ "do_predict": False,
+ "n_gpus_to_use": 2,
+ }
+ log_info_string = "Running training"
+ with CaptureStderr() as cl:
+ self.run_seq2seq_quick(**kwargs, extra_args_str=data["extra_args_str"])
+ n_matches = len(re.findall(log_info_string, cl.err))
+ self.assertEqual(n_matches, data["n_matches"])
+
+ @slow
+ def test_run_seq2seq(self):
+ output_dir = self.run_trainer(
+ eval_steps=2,
+ max_len=128,
+ model_name=MARIAN_MODEL,
+ learning_rate=3e-4,
+ num_train_epochs=10,
+ distributed=False,
+ )
+
+ # Check metrics
+ logs = TrainerState.load_from_json(os.path.join(output_dir, "trainer_state.json")).log_history
+ eval_metrics = [log for log in logs if "eval_loss" in log.keys()]
+ first_step_stats = eval_metrics[0]
+ last_step_stats = eval_metrics[-1]
+
+ assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing"
+ assert isinstance(last_step_stats["eval_bleu"], float)
+
+ # test if do_predict saves generations and metrics
+ contents = os.listdir(output_dir)
+ contents = {os.path.basename(p) for p in contents}
+ assert "generated_predictions.txt" in contents
+ assert "predict_results.json" in contents
+
+ @slow
+ @require_bitsandbytes
+ def test_run_seq2seq_bnb(self):
+ from transformers.training_args import OptimizerNames
+
+ def train_and_return_metrics(optim: str) -> Tuple[int, float]:
+ extra_args = "--skip_memory_metrics 0"
+
+ output_dir = self.run_trainer(
+ max_len=128,
+ model_name=MARIAN_MODEL,
+ learning_rate=3e-4,
+ num_train_epochs=1,
+ optim=optim,
+ distributed=True, # force run in a new process
+ extra_args_str=extra_args,
+ do_eval=False,
+ do_predict=False,
+ n_gpus_to_use=1, # to allow deterministic fixed memory usage
+ )
+
+ # Check metrics
+ logs = TrainerState.load_from_json(Path(output_dir, "trainer_state.json")).log_history
+ gpu_peak_mem_mb = int(logs[0]["train_mem_gpu_peaked_delta"] / 2**20)
+ gpu_alloc_mem_mb = int(logs[0]["train_mem_gpu_alloc_delta"] / 2**20)
+
+ loss = logs[0]["train_loss"]
+ return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss
+
+ gpu_peak_mem_orig, gpu_alloc_mem_orig, loss_orig = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value)
+ gpu_peak_mem_bnb, gpu_alloc_mem_bnb, loss_bnb = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value)
+
+ gpu_alloc_mem_diff = gpu_alloc_mem_orig - gpu_alloc_mem_bnb
+
+ gpu_total_mem_orig = gpu_peak_mem_orig + gpu_alloc_mem_orig
+ gpu_total_mem_bnb = gpu_peak_mem_bnb + gpu_alloc_mem_bnb
+ gpu_total_mem_diff = gpu_total_mem_orig - gpu_total_mem_bnb
+
+ # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which
+ # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized
+ # in 2 bytes and the diff in optim memory usage is derived as so:
+ #
+ # - normal 25*8=~200MB (8 bytes per param)
+ # - bnb 25*2= ~50MB (2 bytes per param)
+ #
+ # Thus we should expect ~150MB total memory saved.
+ #
+ # Peak memory should be the same - the total should be different by about that same margin
+ #
+ # After leaving a small margin to accommodate for differences between gpus let's check
+ # that we have at least 120MB in savings
+ expected_savings = 120
+
+ # uncomment the following if this test starts failing - requires py38 for a new print feature
+ # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb
+ # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB")
+ # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB")
+ # print(f"{gpu_alloc_mem_diff=}MB")
+ # print(f"{gpu_peak_mem_diff=}MB")
+ # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB")
+ # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB")
+
+ self.assertGreater(
+ gpu_alloc_mem_diff,
+ expected_savings,
+ "should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got"
+ f" a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and"
+ f" gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB",
+ )
+
+ self.assertGreater(
+ gpu_total_mem_diff,
+ expected_savings,
+ "should use ~150MB less total gpu memory with BNB, compared to without it for this model but got"
+ f" a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and"
+ f" gpu_total_mem_bnb={gpu_total_mem_bnb}MB",
+ )
+
+ self.assertEqual(
+ loss_orig, loss_bnb, f"loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}"
+ )
+
+ def run_trainer(
+ self,
+ max_len: int,
+ model_name: str,
+ num_train_epochs: int,
+ learning_rate: float = 3e-3,
+ optim: str = "adafactor",
+ distributed: bool = False,
+ extra_args_str: str = None,
+ eval_steps: int = 0,
+ predict_with_generate: bool = True,
+ do_train: bool = True,
+ do_eval: bool = True,
+ do_predict: bool = True,
+ n_gpus_to_use: int = None,
+ ):
+ data_dir = self.test_file_dir / "../fixtures/tests_samples/wmt_en_ro"
+ output_dir = self.get_auto_remove_tmp_dir()
+ args_train = f"""
+ --model_name_or_path {model_name}
+ --train_file {data_dir}/train.json
+ --validation_file {data_dir}/val.json
+ --test_file {data_dir}/test.json
+ --output_dir {output_dir}
+ --overwrite_output_dir
+ --max_train_samples 8
+ --max_source_length {max_len}
+ --max_target_length {max_len}
+ --do_train
+ --num_train_epochs {str(num_train_epochs)}
+ --per_device_train_batch_size 4
+ --learning_rate {learning_rate}
+ --warmup_steps 8
+ --logging_steps 0
+ --logging_strategy no
+ --save_steps {str(eval_steps)}
+ --group_by_length
+ --label_smoothing_factor 0.1
+ --target_lang ro_RO
+ --source_lang en_XX
+ --report_to none
+ """.split()
+
+ args_eval = f"""
+ --do_eval
+ --per_device_eval_batch_size 4
+ --max_eval_samples 8
+ --val_max_target_length {max_len}
+ --eval_strategy steps
+ --eval_steps {str(eval_steps)}
+ """.split()
+
+ args_predict = """
+ --do_predict
+ """.split()
+
+ args = []
+ if do_train:
+ args += args_train
+
+ if do_eval:
+ args += args_eval
+
+ if do_predict:
+ args += args_predict
+
+ if predict_with_generate:
+ args += "--predict_with_generate".split()
+
+ if do_train:
+ if optim == "adafactor":
+ args += "--adafactor".split()
+ else:
+ args += f"--optim {optim}".split()
+
+ if extra_args_str is not None:
+ args += extra_args_str.split()
+
+ if distributed:
+ if n_gpus_to_use is None:
+ n_gpus_to_use = backend_device_count(torch_device)
+ master_port = get_torch_dist_unique_port()
+ distributed_args = f"""
+ -m torch.distributed.run
+ --nproc_per_node={n_gpus_to_use}
+ --master_port={master_port}
+ {self.examples_dir_str}/pytorch/translation/run_translation.py
+ """.split()
+ cmd = [sys.executable] + distributed_args + args
+ # keep for quick debug
+ # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
+ execute_subprocess_async(cmd, env=self.get_env())
+ else:
+ testargs = ["run_translation.py"] + args
+ with patch.object(sys, "argv", testargs):
+ main()
+
+ return output_dir
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/add_distilbert_like_config.json b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/add_distilbert_like_config.json
new file mode 100644
index 0000000000000000000000000000000000000000..812d2a635ddeeb4cc1da8ed7317a9739a6e9f160
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/add_distilbert_like_config.json
@@ -0,0 +1,19 @@
+{
+ "add_copied_from": true,
+ "old_model_type": "distilbert",
+ "new_model_patterns": {
+ "model_name": "BERT New",
+ "checkpoint": "huggingface/bert-new-base",
+ "model_type": "bert-new",
+ "model_lower_cased": "bert_new",
+ "model_camel_cased": "BertNew",
+ "model_upper_cased": "BERT_NEW",
+ "config_class": "BertNewConfig",
+ "tokenizer_class": "DistilBertTokenizer"
+ },
+ "frameworks": [
+ "pt",
+ "tf",
+ "flax"
+ ]
+}
\ No newline at end of file
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/dummy-config.json b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/dummy-config.json
new file mode 100644
index 0000000000000000000000000000000000000000..e388bdf71151db7c014ae6e0174dd07c1a6acbee
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/dummy-config.json
@@ -0,0 +1,3 @@
+{
+ "model_type": "roberta"
+}
\ No newline at end of file
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/dummy_feature_extractor_config.json b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/dummy_feature_extractor_config.json
new file mode 100644
index 0000000000000000000000000000000000000000..674ef8a0b200d57b1ac38da7b4acecfa288a7ac8
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/dummy_feature_extractor_config.json
@@ -0,0 +1,4 @@
+{
+ "feature_extractor_type": "Wav2Vec2FeatureExtractor",
+ "processor_class": "Wav2Vec2Processor"
+}
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/empty.txt b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/empty.txt
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/input.txt b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/input.txt
new file mode 100644
index 0000000000000000000000000000000000000000..d1e3f410d07833e4c5c233ffd54f8d2b54ebb7cf
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/input.txt
@@ -0,0 +1 @@
+Who was Jim Henson ? ||| Jim Henson was a puppeteer
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/merges.txt b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/merges.txt
new file mode 100644
index 0000000000000000000000000000000000000000..d7c5738baaf4304ef4692f6fe8ad887b9517d047
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/merges.txt
@@ -0,0 +1,5 @@
+#version: 0.2
+Ġ l
+Ġl o
+Ġlo w
+e r
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/preprocessor_config.json b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/preprocessor_config.json
new file mode 100644
index 0000000000000000000000000000000000000000..29cd5bc5f3b4dd6794c63dcc60dc86d1a7821ef6
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/preprocessor_config.json
@@ -0,0 +1,4 @@
+{
+ "feature_extractor_type": "Wav2Vec2FeatureExtractor",
+ "processor_class": "Wav2Vec2Processor"
+}
\ No newline at end of file
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/sample_text.txt b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/sample_text.txt
new file mode 100644
index 0000000000000000000000000000000000000000..a42812060c576bae870eb29b1ac083fda0d239d3
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/sample_text.txt
@@ -0,0 +1,33 @@
+This text is included to make sure Unicode is handled properly: 力加勝北区ᴵᴺᵀᵃছজটডণত
+Text should be one-sentence-per-line, with empty lines between documents.
+This sample text is public domain and was randomly selected from Project Guttenberg.
+
+The rain had only ceased with the gray streaks of morning at Blazing Star, and the settlement awoke to a moral sense of cleanliness, and the finding of forgotten knives, tin cups, and smaller camp utensils, where the heavy showers had washed away the debris and dust heaps before the cabin doors.
+Indeed, it was recorded in Blazing Star that a fortunate early riser had once picked up on the highway a solid chunk of gold quartz which the rain had freed from its incumbering soil, and washed into immediate and glittering popularity.
+Possibly this may have been the reason why early risers in that locality, during the rainy season, adopted a thoughtful habit of body, and seldom lifted their eyes to the rifted or india-ink washed skies above them.
+"Cass" Beard had risen early that morning, but not with a view to discovery.
+A leak in his cabin roof,--quite consistent with his careless, improvident habits,--had roused him at 4 A. M., with a flooded "bunk" and wet blankets.
+The chips from his wood pile refused to kindle a fire to dry his bed-clothes, and he had recourse to a more provident neighbor's to supply the deficiency.
+This was nearly opposite.
+Mr. Cassius crossed the highway, and stopped suddenly.
+Something glittered in the nearest red pool before him.
+Gold, surely!
+But, wonderful to relate, not an irregular, shapeless fragment of crude ore, fresh from Nature's crucible, but a bit of jeweler's handicraft in the form of a plain gold ring.
+Looking at it more attentively, he saw that it bore the inscription, "May to Cass."
+Like most of his fellow gold-seekers, Cass was superstitious.
+
+The fountain of classic wisdom, Hypatia herself.
+As the ancient sage--the name is unimportant to a monk--pumped water nightly that he might study by day, so I, the guardian of cloaks and parasols, at the sacred doors of her lecture-room, imbibe celestial knowledge.
+From my youth I felt in me a soul above the matter-entangled herd.
+She revealed to me the glorious fact, that I am a spark of Divinity itself.
+A fallen star, I am, sir!' continued he, pensively, stroking his lean stomach--'a fallen star!--fallen, if the dignity of philosophy will allow of the simile, among the hogs of the lower world--indeed, even into the hog-bucket itself. Well, after all, I will show you the way to the Archbishop's.
+There is a philosophic pleasure in opening one's treasures to the modest young.
+Perhaps you will assist me by carrying this basket of fruit?' And the little man jumped up, put his basket on Philammon's head, and trotted off up a neighbouring street.
+Philammon followed, half contemptuous, half wondering at what this philosophy might be, which could feed the self-conceit of anything so abject as his ragged little apish guide;
+but the novel roar and whirl of the street, the perpetual stream of busy faces, the line of curricles, palanquins, laden asses, camels, elephants, which met and passed him, and squeezed him up steps and into doorways, as they threaded their way through the great Moon-gate into the ample street beyond, drove everything from his mind but wondering curiosity, and a vague, helpless dread of that great living wilderness, more terrible than any dead wilderness of sand which he had left behind.
+Already he longed for the repose, the silence of the Laura--for faces which knew him and smiled upon him; but it was too late to turn back now.
+His guide held on for more than a mile up the great main street, crossed in the centre of the city, at right angles, by one equally magnificent, at each end of which, miles away, appeared, dim and distant over the heads of the living stream of passengers, the yellow sand-hills of the desert;
+while at the end of the vista in front of them gleamed the blue harbour, through a network of countless masts.
+At last they reached the quay at the opposite end of the street;
+and there burst on Philammon's astonished eyes a vast semicircle of blue sea, ringed with palaces and towers.
+He stopped involuntarily; and his little guide stopped also, and looked askance at the young monk, to watch the effect which that grand panorama should produce on him.
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/sample_text_no_unicode.txt b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/sample_text_no_unicode.txt
new file mode 100644
index 0000000000000000000000000000000000000000..74646661c7c121a31af30def84a4d724a4b2d41f
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/sample_text_no_unicode.txt
@@ -0,0 +1,32 @@
+Text should be one-sentence-per-line, with empty lines between documents.
+This sample text is public domain and was randomly selected from Project Guttenberg.
+
+The rain had only ceased with the gray streaks of morning at Blazing Star, and the settlement awoke to a moral sense of cleanliness, and the finding of forgotten knives, tin cups, and smaller camp utensils, where the heavy showers had washed away the debris and dust heaps before the cabin doors.
+Indeed, it was recorded in Blazing Star that a fortunate early riser had once picked up on the highway a solid chunk of gold quartz which the rain had freed from its incumbering soil, and washed into immediate and glittering popularity.
+Possibly this may have been the reason why early risers in that locality, during the rainy season, adopted a thoughtful habit of body, and seldom lifted their eyes to the rifted or india-ink washed skies above them.
+"Cass" Beard had risen early that morning, but not with a view to discovery.
+A leak in his cabin roof,--quite consistent with his careless, improvident habits,--had roused him at 4 A. M., with a flooded "bunk" and wet blankets.
+The chips from his wood pile refused to kindle a fire to dry his bed-clothes, and he had recourse to a more provident neighbor's to supply the deficiency.
+This was nearly opposite.
+Mr. Cassius crossed the highway, and stopped suddenly.
+Something glittered in the nearest red pool before him.
+Gold, surely!
+But, wonderful to relate, not an irregular, shapeless fragment of crude ore, fresh from Nature's crucible, but a bit of jeweler's handicraft in the form of a plain gold ring.
+Looking at it more attentively, he saw that it bore the inscription, "May to Cass."
+Like most of his fellow gold-seekers, Cass was superstitious.
+
+The fountain of classic wisdom, Hypatia herself.
+As the ancient sage--the name is unimportant to a monk--pumped water nightly that he might study by day, so I, the guardian of cloaks and parasols, at the sacred doors of her lecture-room, imbibe celestial knowledge.
+From my youth I felt in me a soul above the matter-entangled herd.
+She revealed to me the glorious fact, that I am a spark of Divinity itself.
+A fallen star, I am, sir!' continued he, pensively, stroking his lean stomach--'a fallen star!--fallen, if the dignity of philosophy will allow of the simile, among the hogs of the lower world--indeed, even into the hog-bucket itself. Well, after all, I will show you the way to the Archbishop's.
+There is a philosophic pleasure in opening one's treasures to the modest young.
+Perhaps you will assist me by carrying this basket of fruit?' And the little man jumped up, put his basket on Philammon's head, and trotted off up a neighbouring street.
+Philammon followed, half contemptuous, half wondering at what this philosophy might be, which could feed the self-conceit of anything so abject as his ragged little apish guide;
+but the novel roar and whirl of the street, the perpetual stream of busy faces, the line of curricles, palanquins, laden asses, camels, elephants, which met and passed him, and squeezed him up steps and into doorways, as they threaded their way through the great Moon-gate into the ample street beyond, drove everything from his mind but wondering curiosity, and a vague, helpless dread of that great living wilderness, more terrible than any dead wilderness of sand which he had left behind.
+Already he longed for the repose, the silence of the Laura--for faces which knew him and smiled upon him; but it was too late to turn back now.
+His guide held on for more than a mile up the great main street, crossed in the centre of the city, at right angles, by one equally magnificent, at each end of which, miles away, appeared, dim and distant over the heads of the living stream of passengers, the yellow sand-hills of the desert;
+while at the end of the vista in front of them gleamed the blue harbour, through a network of countless masts.
+At last they reached the quay at the opposite end of the street;
+and there burst on Philammon's astonished eyes a vast semicircle of blue sea, ringed with palaces and towers.
+He stopped involuntarily; and his little guide stopped also, and looked askance at the young monk, to watch the effect which that grand panorama should produce on him.
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/spiece.model b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/spiece.model
new file mode 100644
index 0000000000000000000000000000000000000000..64f3146c1fe2a7b57b19725c0627bb6b66ea0da0
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/spiece.model
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:fefb02b667a6c5c2fe27602d28e5fb3428f66ab89c7d6f388e7c8d44a02d0336
+size 760289
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_entity_vocab.json b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_entity_vocab.json
new file mode 100644
index 0000000000000000000000000000000000000000..d5a63935979e7b0b0ae181e0c36b9b9e715315ac
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_entity_vocab.json
@@ -0,0 +1 @@
+{"[MASK]": 0, "[UNK]": 1, "[PAD]": 2, "DUMMY": 3, "DUMMY2": 4, "[MASK2]": 5}
\ No newline at end of file
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_sentencepiece.model b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_sentencepiece.model
new file mode 100644
index 0000000000000000000000000000000000000000..c93fabdc0d8840e28baff407ec1a048eff8abc23
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_sentencepiece.model
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8dfd1eae4522281b1b839eab877a791befec7a1663a41c814c77d9c89c748f2d
+size 253154
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_sentencepiece_bpe.model b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_sentencepiece_bpe.model
new file mode 100644
index 0000000000000000000000000000000000000000..4f7197401c9d0863e92f645dfe04b4447c4b431f
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_sentencepiece_bpe.model
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c4de78f5d11ee09141165d31da7dad97e809dd6ee7b52a0cbc6d76a973028286
+size 251527
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_sentencepiece_bpe_char.model b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_sentencepiece_bpe_char.model
new file mode 100644
index 0000000000000000000000000000000000000000..8fb73691942626fa75df80b61aab0e9b9340d8e2
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_sentencepiece_bpe_char.model
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:7fcc48f3e225f627b1641db410ceb0c8649bd2b0c982e150b03f8be3728ab560
+size 238473
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_sentencepiece_no_bos.model b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_sentencepiece_no_bos.model
new file mode 100644
index 0000000000000000000000000000000000000000..3821900071a060c06044cc43c30519faedcd1b38
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_sentencepiece_no_bos.model
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6f3af97c2e7bc51d781e7440aa33deee7f482eac819d23fd24af80e7b4ce2646
+size 253134
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_sentencepiece_with_bytefallback.model b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_sentencepiece_with_bytefallback.model
new file mode 100644
index 0000000000000000000000000000000000000000..fbf70ee25f893394e33498e3c8969288cc29d5cd
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/test_sentencepiece_with_bytefallback.model
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c61ecce43369fc3bab9566464f0e71f3ad75dc2319a5aadc2a561e3e312502e3
+size 270096
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/.gitignore b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..1d7141c43dcf8f422e18fe3c13eb8f9e0bb9a964
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/.gitignore
@@ -0,0 +1,6 @@
+cache*
+temp*
+!*.txt
+!*.tsv
+!*.json
+!.gitignore
\ No newline at end of file
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/COCO/000000004016.png b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/COCO/000000004016.png
new file mode 100644
index 0000000000000000000000000000000000000000..698ce0e1b88f5d7675c33185d7c1a698e0ec3a18
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/COCO/000000004016.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:88bb5c2a7f00292db072f7d95638c6f5a46c7d824fff6412327e636eedc1fc24
+size 636411
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/COCO/000000039769.png b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/COCO/000000039769.png
new file mode 100644
index 0000000000000000000000000000000000000000..92f01f8b50fc6d714cd42d1441a637f7aa864127
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/COCO/000000039769.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:cf6f3c4befa148732c7453e0de5afab00f682427435fead2d88b07a9615cdac2
+size 694498
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/COCO/coco_annotations.txt b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/COCO/coco_annotations.txt
new file mode 100644
index 0000000000000000000000000000000000000000..bd8c86a9bc3cbbc2f12e5efc58a805c7e9346d37
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/COCO/coco_annotations.txt
@@ -0,0 +1 @@
+[{"segmentation": [[333.96, 175.14, 338.26, 134.33, 342.55, 95.67, 348.99, 79.57, 368.32, 80.64, 371.54, 91.38, 364.03, 106.41, 356.51, 145.07, 351.14, 166.55, 350.07, 184.8, 345.77, 185.88, 332.89, 178.36, 332.89, 172.99]], "area": 2120.991099999999, "iscrowd": 0, "image_id": 39769, "bbox": [332.89, 79.57, 38.65, 106.31], "category_id": 75, "id": 1108446}, {"segmentation": [[44.03, 86.01, 112.75, 74.2, 173.96, 77.42, 175.03, 89.23, 170.74, 98.9, 147.11, 102.12, 54.77, 119.3, 53.69, 119.3, 44.03, 113.93, 41.88, 94.6, 41.88, 94.6]], "area": 4052.607, "iscrowd": 0, "image_id": 39769, "bbox": [41.88, 74.2, 133.15, 45.1], "category_id": 75, "id": 1110067}, {"segmentation": [[1.08, 473.53, 633.17, 473.53, 557.66, 376.45, 535.01, 366.74, 489.71, 305.26, 470.29, 318.2, 456.27, 351.64, 413.12, 363.51, 376.45, 358.11, 348.4, 350.56, 363.51, 331.15, 357.03, 288.0, 353.8, 257.8, 344.09, 190.92, 333.3, 177.98, 345.17, 79.82, 284.76, 130.52, 265.35, 151.01, 308.49, 189.84, 317.12, 215.73, 293.39, 243.78, 269.66, 212.49, 235.15, 199.55, 214.65, 193.08, 187.69, 217.89, 159.64, 278.29, 135.91, 313.89, 169.35, 292.31, 203.87, 281.53, 220.04, 292.31, 220.04, 307.42, 175.82, 345.17, 155.33, 360.27, 105.71, 363.51, 85.21, 374.29, 74.43, 366.74, 70.11, 465.98, 42.07, 471.37, 33.44, 457.35, 34.52, 414.2, 29.12, 368.9, 9.71, 291.24, 46.38, 209.26, 99.24, 128.36, 131.6, 107.87, 50.7, 117.57, 40.99, 103.55, 40.99, 85.21, 60.4, 77.66, 141.3, 70.11, 173.66, 72.27, 174.74, 92.76, 204.94, 72.27, 225.44, 62.56, 262.11, 56.09, 292.31, 53.93, 282.61, 81.98, 298.79, 96.0, 310.65, 102.47, 348.4, 74.43, 373.21, 81.98, 430.38, 35.6, 484.31, 23.73, 540.4, 46.38, 593.26, 66.88, 638.56, 80.9, 632.09, 145.62, 581.39, 118.65, 543.64, 130.52, 533.93, 167.19, 512.36, 197.39, 498.34, 218.97, 529.62, 253.48, 549.03, 273.98, 584.63, 276.13, 587.87, 293.39, 566.29, 305.26, 531.78, 298.79, 549.03, 319.28, 576.0, 358.11, 560.9, 376.45, 639.64, 471.37, 639.64, 2.16, 1.08, 0.0]], "area": 176277.55269999994, "iscrowd": 0, "image_id": 39769, "bbox": [1.08, 0.0, 638.56, 473.53], "category_id": 63, "id": 1605237}, {"segmentation": [[1.07, 1.18, 640.0, 3.33, 638.93, 472.59, 4.3, 479.03]], "area": 301552.6694999999, "iscrowd": 0, "image_id": 39769, "bbox": [1.07, 1.18, 638.93, 477.85], "category_id": 65, "id": 1612051}, {"segmentation": [[138.75, 319.38, 148.75, 294.38, 165.0, 246.87, 197.5, 205.63, 247.5, 203.13, 268.75, 216.88, 280.0, 239.38, 293.75, 244.38, 303.75, 241.88, 307.5, 228.13, 318.75, 220.63, 315.0, 200.63, 291.25, 171.88, 265.0, 156.88, 258.75, 148.13, 262.5, 135.63, 282.5, 123.13, 292.5, 115.63, 311.25, 108.13, 313.75, 106.88, 296.25, 93.13, 282.5, 84.38, 292.5, 64.38, 288.75, 60.63, 266.25, 54.38, 232.5, 63.12, 206.25, 70.63, 170.0, 100.63, 136.25, 114.38, 101.25, 138.13, 56.25, 194.38, 27.5, 259.38, 17.5, 299.38, 32.5, 378.13, 31.25, 448.13, 41.25, 469.38, 66.25, 466.88, 70.0, 419.38, 71.25, 391.88, 77.5, 365.63, 113.75, 364.38, 145.0, 360.63, 168.75, 349.38, 191.25, 330.63, 212.5, 319.38, 223.75, 305.63, 206.25, 286.88, 172.5, 288.13]], "area": 53301.618749999994, "iscrowd": 0, "image_id": 39769, "bbox": [17.5, 54.38, 301.25, 415.0], "category_id": 17, "id": 2190839}, {"segmentation": [[543.75, 136.88, 570.0, 114.38, 591.25, 123.13, 616.25, 140.63, 640.0, 143.13, 636.25, 124.37, 605.0, 103.13, 640.0, 103.13, 633.75, 86.88, 587.5, 73.13, 548.75, 49.38, 505.0, 35.63, 462.5, 25.63, 405.0, 48.13, 362.5, 111.88, 347.5, 179.38, 355.0, 220.63, 356.25, 230.63, 365.0, 264.38, 358.75, 266.88, 358.75, 270.63, 356.25, 291.88, 356.25, 325.63, 355.0, 338.13, 350.0, 348.13, 365.0, 354.38, 396.25, 351.88, 423.75, 355.63, 446.25, 350.63, 460.0, 345.63, 462.5, 321.88, 468.75, 306.88, 481.25, 299.38, 516.25, 341.88, 536.25, 368.13, 570.0, 369.38, 578.75, 359.38, 555.0, 330.63, 532.5, 298.13, 563.75, 299.38, 582.5, 298.13, 586.25, 286.88, 578.75, 278.13, 548.75, 269.38, 525.0, 256.88, 505.0, 206.88, 536.25, 161.88, 540.0, 149.38]], "area": 59700.95625, "iscrowd": 0, "image_id": 39769, "bbox": [347.5, 25.63, 292.5, 343.75], "category_id": 17, "id": 2190842}]
\ No newline at end of file
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/COCO/coco_panoptic/000000039769.png b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/COCO/coco_panoptic/000000039769.png
new file mode 100644
index 0000000000000000000000000000000000000000..598c2dad54ed9bb2186403d4b135b8448e492103
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/COCO/coco_panoptic/000000039769.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:1fe90f86fba742ce84e94710a3c1095380544bee55bc82463452d5f5745c4c4d
+size 8269
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt
new file mode 100644
index 0000000000000000000000000000000000000000..90a9798be2a2abbc359b698799795c918d4a787b
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt
@@ -0,0 +1 @@
+[{"id": 8222595, "category_id": 17, "iscrowd": 0, "bbox": [18, 54, 301, 415], "area": 53306}, {"id": 8225432, "category_id": 17, "iscrowd": 0, "bbox": [349, 26, 291, 343], "area": 59627}, {"id": 8798150, "category_id": 63, "iscrowd": 0, "bbox": [1, 0, 639, 474], "area": 174579}, {"id": 14466198, "category_id": 75, "iscrowd": 0, "bbox": [42, 74, 133, 45], "area": 4068}, {"id": 12821912, "category_id": 75, "iscrowd": 0, "bbox": [333, 80, 38, 106], "area": 2118}, {"id": 10898909, "category_id": 93, "iscrowd": 0, "bbox": [0, 0, 640, 480], "area": 2750}]
\ No newline at end of file
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/GermEval/dev.txt b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/GermEval/dev.txt
new file mode 100644
index 0000000000000000000000000000000000000000..de001582302780954c8f00af5531372df290a43b
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/GermEval/dev.txt
@@ -0,0 +1,202 @@
+Gleich O
+darauf O
+entwirft O
+er O
+seine O
+Selbstdarstellung O
+" O
+Ecce B-OTH
+homo I-OTH
+" O
+in O
+enger O
+Auseinandersetzung O
+mit O
+diesem O
+Bild O
+Jesu B-PER
+. O
+
+1980 O
+kam O
+der O
+Crown B-OTH
+als O
+Versuch O
+von O
+Toyota B-ORG
+, O
+sich O
+in O
+der O
+Oberen O
+Mittelklasse O
+zu O
+etablieren O
+, O
+auch O
+nach O
+Deutschland B-LOC
+. O
+
+– O
+4:26 O
+# O
+Sometime B-OTH
+Ago/La I-OTH
+Fiesta I-OTH
+– O
+23:18 O
+Alle O
+Stücke O
+wurden O
+von O
+Corea B-PER
+komponiert O
+mit O
+Ausnahme O
+der O
+einleitenden O
+Improvisation O
+zu O
+Sometime B-OTH
+Ago I-OTH
+. O
+
+Bis O
+2013 O
+steigen O
+die O
+Mittel O
+aus O
+dem O
+EU-Budget B-ORGpart
+auf O
+rund O
+120 O
+Millionen O
+Euro B-OTH
+. O
+
+Daraus O
+entwickelte O
+sich O
+im O
+Rokoko B-OTH
+die O
+Sitte O
+des O
+gemeinsamen O
+Weinens O
+im O
+Theater O
+, O
+das O
+die O
+Standesgrenzen O
+innerhalb O
+des O
+Publikums O
+überbrücken O
+sollte O
+. O
+
+Die O
+Spinne O
+hatte O
+sie O
+mit O
+Seidenfäden O
+an O
+ihrem O
+Schwanz O
+gefesselt O
+und O
+nach O
+oben O
+gezogen O
+. O
+
+In O
+Deutschland B-LOC
+ist O
+nach O
+StGB O
+eine O
+Anwerbung O
+für O
+die O
+Fremdenlegion O
+strafbar O
+. O
+
+Am O
+Donnerstag O
+wird O
+sich O
+zeigen O
+, O
+ob O
+die O
+Idee O
+der O
+DLR-Forscher B-ORGpart
+funktioniert O
+. O
+
+Der O
+sechste O
+Lauf O
+der O
+ADAC B-ORG
+GT I-ORG
+Mastersstand O
+ganz O
+klar O
+im O
+Mittelpunkt O
+des O
+Motorsport-Wochenendes O
+auf O
+dem O
+Eurospeedway B-ORG
+Lausitz I-ORG
+. O
+
+Nach O
+den O
+schwächeren O
+Vorgaben O
+der O
+Wall B-ORG
+Street I-ORG
+vom O
+Vortag O
+setzten O
+die O
+deutschen B-LOCderiv
+Standardwerte O
+ihren O
+Konsolidierungskurs O
+fort O
+. O
+
+Kolb B-PER
+war O
+seit O
+1986 O
+im O
+Turnverein O
+als O
+Leiter O
+tätig O
+, O
+darunter O
+elf O
+Jahre O
+als O
+Hauptleiter O
+in O
+der O
+Männerriege O
+. O
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/GermEval/labels.txt b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/GermEval/labels.txt
new file mode 100644
index 0000000000000000000000000000000000000000..a781cbd47ee29d10dc1b8cf823c4ec9600ba0355
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/GermEval/labels.txt
@@ -0,0 +1,25 @@
+B-LOC
+B-LOCderiv
+B-LOCpart
+B-ORG
+B-ORGderiv
+B-ORGpart
+B-OTH
+B-OTHderiv
+B-OTHpart
+B-PER
+B-PERderiv
+B-PERpart
+I-LOC
+I-LOCderiv
+I-LOCpart
+I-ORG
+I-ORGderiv
+I-ORGpart
+I-OTH
+I-OTHderiv
+I-OTHpart
+I-PER
+I-PERderiv
+I-PERpart
+O
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/GermEval/train.txt b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/GermEval/train.txt
new file mode 100644
index 0000000000000000000000000000000000000000..3d613ae1ee9b07901f14bf9107b042fa071c3525
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/GermEval/train.txt
@@ -0,0 +1,200 @@
+Schartau B-PER
+sagte O
+dem O
+" O
+Tagesspiegel B-ORG
+" O
+vom O
+Freitag O
+, O
+Fischer B-PER
+sei O
+" O
+in O
+einer O
+Weise O
+aufgetreten O
+, O
+die O
+alles O
+andere O
+als O
+überzeugend O
+war O
+" O
+. O
+
+Firmengründer O
+Wolf B-PER
+Peter I-PER
+Bree I-PER
+arbeitete O
+Anfang O
+der O
+siebziger O
+Jahre O
+als O
+Möbelvertreter O
+, O
+als O
+er O
+einen O
+fliegenden O
+Händler O
+aus O
+dem O
+Libanon B-LOC
+traf O
+. O
+
+Ob O
+sie O
+dabei O
+nach O
+dem O
+Runden O
+Tisch O
+am O
+23. O
+April O
+in O
+Berlin B-LOC
+durch O
+ein O
+pädagogisches O
+Konzept O
+unterstützt O
+wird O
+, O
+ist O
+allerdings O
+zu O
+bezweifeln O
+. O
+
+Bayern B-ORG
+München I-ORG
+ist O
+wieder O
+alleiniger O
+Top- O
+Favorit O
+auf O
+den O
+Gewinn O
+der O
+deutschen B-LOCderiv
+Fußball-Meisterschaft O
+. O
+
+Dabei O
+hätte O
+der O
+tapfere O
+Schlussmann O
+allen O
+Grund O
+gehabt O
+, O
+sich O
+viel O
+früher O
+aufzuregen O
+. O
+
+ARD-Programmchef B-ORGpart
+Günter B-PER
+Struve I-PER
+war O
+wegen O
+eines O
+vierwöchigen O
+Urlaubs O
+für O
+eine O
+Stellungnahme O
+nicht O
+erreichbar O
+. O
+
+Alternativ O
+sollten O
+sich O
+die O
+Restaurantbetreiber O
+aus O
+Sicht O
+der O
+Solingerin B-LOCderiv
+zu O
+längeren O
+Öffnungszeiten O
+verpflichten O
+, O
+um O
+wartende O
+Kunden O
+aufzunehmen O
+. O
+
+Die O
+Deutsche B-ORG
+Flugsicherung I-ORG
+( O
+DFS B-ORG
+) O
+beschloss O
+ein O
+Flugverbot O
+für O
+alle O
+internationalen O
+Flughäfen O
+mit O
+Ausnahme O
+der O
+beiden O
+Berliner B-LOCderiv
+Flughäfen O
+bis O
+2.00 O
+Uhr O
+nachts O
+. O
+
+New O
+Small O
+Family O
+mit O
+E-Motor O
+: O
+Studie O
+E-Up O
+! O
+
+Eine O
+Schwachstelle O
+war O
+beispielsweise O
+der O
+Spiegelkasten O
+. O
+
+Denn O
+durch O
+den O
+Einsatz O
+moderner O
+Fahrzeugtechnik O
+( O
+Dieseltriebwagen O
+) O
+und O
+schalldämmender O
+Fenster O
+entsteht O
+keine O
+Einschränkung O
+der O
+Wohnqualität O
+. O
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/MRPC/dev.csv b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/MRPC/dev.csv
new file mode 100644
index 0000000000000000000000000000000000000000..96beccda96d7e164e4484e037a52fb338cc22180
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/MRPC/dev.csv
@@ -0,0 +1,7 @@
+label,sentence1,sentence2
+equivalent,He said the foodservice pie business doesn 't fit the company 's long-term growth strategy .,""" The foodservice pie business does not fit our long-term growth strategy ."
+not_equivalent,Magnarelli said Racicot hated the Iraqi regime and looked forward to using his long years of training in the war .,"His wife said he was "" 100 percent behind George Bush "" and looked forward to using his years of training in the war ."
+not_equivalent,"The dollar was at 116.92 yen against the yen , flat on the session , and at 1.2891 against the Swiss franc , also flat .","The dollar was at 116.78 yen JPY = , virtually flat on the session , and at 1.2871 against the Swiss franc CHF = , down 0.1 percent ."
+equivalent,The AFL-CIO is waiting until October to decide if it will endorse a candidate .,The AFL-CIO announced Wednesday that it will decide in October whether to endorse a candidate before the primaries .
+not_equivalent,No dates have been set for the civil or the criminal trial .,"No dates have been set for the criminal or civil cases , but Shanley has pleaded not guilty ."
+equivalent,Wal-Mart said it would check all of its million-plus domestic workers to ensure they were legally employed .,It has also said it would review all of its domestic employees more than 1 million to ensure they have legal status .
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/MRPC/dev.tsv b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/MRPC/dev.tsv
new file mode 100644
index 0000000000000000000000000000000000000000..5b814856c63f44ef8c082726ae19285a4faec26c
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/MRPC/dev.tsv
@@ -0,0 +1,7 @@
+Quality #1 ID #2 ID #1 String #2 String
+1 1355540 1355592 He said the foodservice pie business doesn 't fit the company 's long-term growth strategy . " The foodservice pie business does not fit our long-term growth strategy .
+0 2029631 2029565 Magnarelli said Racicot hated the Iraqi regime and looked forward to using his long years of training in the war . His wife said he was " 100 percent behind George Bush " and looked forward to using his years of training in the war .
+0 487993 487952 The dollar was at 116.92 yen against the yen , flat on the session , and at 1.2891 against the Swiss franc , also flat . The dollar was at 116.78 yen JPY = , virtually flat on the session , and at 1.2871 against the Swiss franc CHF = , down 0.1 percent .
+1 1989515 1989458 The AFL-CIO is waiting until October to decide if it will endorse a candidate . The AFL-CIO announced Wednesday that it will decide in October whether to endorse a candidate before the primaries .
+0 1783137 1782659 No dates have been set for the civil or the criminal trial . No dates have been set for the criminal or civil cases , but Shanley has pleaded not guilty .
+1 3039165 3039036 Wal-Mart said it would check all of its million-plus domestic workers to ensure they were legally employed . It has also said it would review all of its domestic employees more than 1 million to ensure they have legal status .
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/MRPC/train.csv b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/MRPC/train.csv
new file mode 100644
index 0000000000000000000000000000000000000000..96beccda96d7e164e4484e037a52fb338cc22180
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/MRPC/train.csv
@@ -0,0 +1,7 @@
+label,sentence1,sentence2
+equivalent,He said the foodservice pie business doesn 't fit the company 's long-term growth strategy .,""" The foodservice pie business does not fit our long-term growth strategy ."
+not_equivalent,Magnarelli said Racicot hated the Iraqi regime and looked forward to using his long years of training in the war .,"His wife said he was "" 100 percent behind George Bush "" and looked forward to using his years of training in the war ."
+not_equivalent,"The dollar was at 116.92 yen against the yen , flat on the session , and at 1.2891 against the Swiss franc , also flat .","The dollar was at 116.78 yen JPY = , virtually flat on the session , and at 1.2871 against the Swiss franc CHF = , down 0.1 percent ."
+equivalent,The AFL-CIO is waiting until October to decide if it will endorse a candidate .,The AFL-CIO announced Wednesday that it will decide in October whether to endorse a candidate before the primaries .
+not_equivalent,No dates have been set for the civil or the criminal trial .,"No dates have been set for the criminal or civil cases , but Shanley has pleaded not guilty ."
+equivalent,Wal-Mart said it would check all of its million-plus domestic workers to ensure they were legally employed .,It has also said it would review all of its domestic employees more than 1 million to ensure they have legal status .
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/MRPC/train.tsv b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/MRPC/train.tsv
new file mode 100644
index 0000000000000000000000000000000000000000..5b814856c63f44ef8c082726ae19285a4faec26c
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/MRPC/train.tsv
@@ -0,0 +1,7 @@
+Quality #1 ID #2 ID #1 String #2 String
+1 1355540 1355592 He said the foodservice pie business doesn 't fit the company 's long-term growth strategy . " The foodservice pie business does not fit our long-term growth strategy .
+0 2029631 2029565 Magnarelli said Racicot hated the Iraqi regime and looked forward to using his long years of training in the war . His wife said he was " 100 percent behind George Bush " and looked forward to using his years of training in the war .
+0 487993 487952 The dollar was at 116.92 yen against the yen , flat on the session , and at 1.2891 against the Swiss franc , also flat . The dollar was at 116.78 yen JPY = , virtually flat on the session , and at 1.2871 against the Swiss franc CHF = , down 0.1 percent .
+1 1989515 1989458 The AFL-CIO is waiting until October to decide if it will endorse a candidate . The AFL-CIO announced Wednesday that it will decide in October whether to endorse a candidate before the primaries .
+0 1783137 1782659 No dates have been set for the civil or the criminal trial . No dates have been set for the criminal or civil cases , but Shanley has pleaded not guilty .
+1 3039165 3039036 Wal-Mart said it would check all of its million-plus domestic workers to ensure they were legally employed . It has also said it would review all of its domestic employees more than 1 million to ensure they have legal status .
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/SQUAD/sample.json b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/SQUAD/sample.json
new file mode 100644
index 0000000000000000000000000000000000000000..ed3dcc27d721f4a09ac3f23fee07f6e64441535d
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/SQUAD/sample.json
@@ -0,0 +1,201 @@
+{
+ "version": 2.0,
+ "data": [
+ {
+ "id": "56ddde6b9a695914005b9628",
+ "question": "In what country is Normandy located?",
+ "context": "The Normans (Norman: Nourmands; French: Normands; Latin: Normanni) were the people who in the 10th and 11th centuries gave their name to Normandy, a region in France. They were descended from Norse (\"Norman\" comes from \"Norseman\") raiders and pirates from Denmark, Iceland and Norway who, under their leader Rollo, agreed to swear fealty to King Charles III of West Francia. Through generations of assimilation and mixing with the native Frankish and Roman-Gaulish populations, their descendants would gradually merge with the Carolingian-based cultures of West Francia. The distinct cultural and ethnic identity of the Normans emerged initially in the first half of the 10th century, and it continued to evolve over the succeeding centuries.",
+ "answers": {
+ "answer_start": [
+ 159,
+ 159,
+ 159,
+ 159
+ ],
+ "text": [
+ "France",
+ "France",
+ "France",
+ "France"
+ ]
+ }
+ },
+ {
+ "id": "56ddde6b9a695914005b9629",
+ "question": "When were the Normans in Normandy?",
+ "context": "The Normans (Norman: Nourmands; French: Normands; Latin: Normanni) were the people who in the 10th and 11th centuries gave their name to Normandy, a region in France. They were descended from Norse (\"Norman\" comes from \"Norseman\") raiders and pirates from Denmark, Iceland and Norway who, under their leader Rollo, agreed to swear fealty to King Charles III of West Francia. Through generations of assimilation and mixing with the native Frankish and Roman-Gaulish populations, their descendants would gradually merge with the Carolingian-based cultures of West Francia. The distinct cultural and ethnic identity of the Normans emerged initially in the first half of the 10th century, and it continued to evolve over the succeeding centuries.",
+ "answers": {
+ "answer_start": [
+ 94,
+ 87,
+ 94,
+ 94
+ ],
+ "text": [
+ "10th and 11th centuries",
+ "in the 10th and 11th centuries",
+ "10th and 11th centuries",
+ "10th and 11th centuries"
+ ]
+ }
+ },
+ {
+ "id": "56ddde6b9a695914005b962a",
+ "question": "From which countries did the Norse originate?",
+ "context": "The Normans (Norman: Nourmands; French: Normands; Latin: Normanni) were the people who in the 10th and 11th centuries gave their name to Normandy, a region in France. They were descended from Norse (\"Norman\" comes from \"Norseman\") raiders and pirates from Denmark, Iceland and Norway who, under their leader Rollo, agreed to swear fealty to King Charles III of West Francia. Through generations of assimilation and mixing with the native Frankish and Roman-Gaulish populations, their descendants would gradually merge with the Carolingian-based cultures of West Francia. The distinct cultural and ethnic identity of the Normans emerged initially in the first half of the 10th century, and it continued to evolve over the succeeding centuries.",
+ "answers": {
+ "answer_start": [
+ 256,
+ 256,
+ 256,
+ 256
+ ],
+ "text": [
+ "Denmark, Iceland and Norway",
+ "Denmark, Iceland and Norway",
+ "Denmark, Iceland and Norway",
+ "Denmark, Iceland and Norway"
+ ]
+ }
+ },
+ {
+ "id": "5ad39d53604f3c001a3fe8d3",
+ "question": "Who did King Charles III swear fealty to?",
+ "context": "The Normans (Norman: Nourmands; French: Normands; Latin: Normanni) were the people who in the 10th and 11th centuries gave their name to Normandy, a region in France. They were descended from Norse (\"Norman\" comes from \"Norseman\") raiders and pirates from Denmark, Iceland and Norway who, under their leader Rollo, agreed to swear fealty to King Charles III of West Francia. Through generations of assimilation and mixing with the native Frankish and Roman-Gaulish populations, their descendants would gradually merge with the Carolingian-based cultures of West Francia. The distinct cultural and ethnic identity of the Normans emerged initially in the first half of the 10th century, and it continued to evolve over the succeeding centuries.",
+ "answers": {
+ "answer_start": [],
+ "text": []
+ }
+ },
+ {
+ "id": "5ad39d53604f3c001a3fe8d4",
+ "question": "When did the Frankish identity emerge?",
+ "context": "The Normans (Norman: Nourmands; French: Normands; Latin: Normanni) were the people who in the 10th and 11th centuries gave their name to Normandy, a region in France. They were descended from Norse (\"Norman\" comes from \"Norseman\") raiders and pirates from Denmark, Iceland and Norway who, under their leader Rollo, agreed to swear fealty to King Charles III of West Francia. Through generations of assimilation and mixing with the native Frankish and Roman-Gaulish populations, their descendants would gradually merge with the Carolingian-based cultures of West Francia. The distinct cultural and ethnic identity of the Normans emerged initially in the first half of the 10th century, and it continued to evolve over the succeeding centuries.",
+ "answers": {
+ "answer_start": [],
+ "text": []
+ }
+ },
+ {
+ "id": "56dddf4066d3e219004dad5f",
+ "question": "Who was the duke in the battle of Hastings?",
+ "context": "The Norman dynasty had a major political, cultural and military impact on medieval Europe and even the Near East. The Normans were famed for their martial spirit and eventually for their Christian piety, becoming exponents of the Catholic orthodoxy into which they assimilated. They adopted the Gallo-Romance language of the Frankish land they settled, their dialect becoming known as Norman, Normaund or Norman French, an important literary language. The Duchy of Normandy, which they formed by treaty with the French crown, was a great fief of medieval France, and under Richard I of Normandy was forged into a cohesive and formidable principality in feudal tenure. The Normans are noted both for their culture, such as their unique Romanesque architecture and musical traditions, and for their significant military accomplishments and innovations. Norman adventurers founded the Kingdom of Sicily under Roger II after conquering southern Italy on the Saracens and Byzantines, and an expedition on behalf of their duke, William the Conqueror, led to the Norman conquest of England at the Battle of Hastings in 1066. Norman cultural and military influence spread from these new European centres to the Crusader states of the Near East, where their prince Bohemond I founded the Principality of Antioch in the Levant, to Scotland and Wales in Great Britain, to Ireland, and to the coasts of north Africa and the Canary Islands.",
+ "answers": {
+ "answer_start": [
+ 1022,
+ 1022,
+ 1022
+ ],
+ "text": [
+ "William the Conqueror",
+ "William the Conqueror",
+ "William the Conqueror"
+ ]
+ }
+ },
+ {
+ "id": "5ad3a266604f3c001a3fea2b",
+ "question": "What principality did William the conquerer found?",
+ "context": "The Norman dynasty had a major political, cultural and military impact on medieval Europe and even the Near East. The Normans were famed for their martial spirit and eventually for their Christian piety, becoming exponents of the Catholic orthodoxy into which they assimilated. They adopted the Gallo-Romance language of the Frankish land they settled, their dialect becoming known as Norman, Normaund or Norman French, an important literary language. The Duchy of Normandy, which they formed by treaty with the French crown, was a great fief of medieval France, and under Richard I of Normandy was forged into a cohesive and formidable principality in feudal tenure. The Normans are noted both for their culture, such as their unique Romanesque architecture and musical traditions, and for their significant military accomplishments and innovations. Norman adventurers founded the Kingdom of Sicily under Roger II after conquering southern Italy on the Saracens and Byzantines, and an expedition on behalf of their duke, William the Conqueror, led to the Norman conquest of England at the Battle of Hastings in 1066. Norman cultural and military influence spread from these new European centres to the Crusader states of the Near East, where their prince Bohemond I founded the Principality of Antioch in the Levant, to Scotland and Wales in Great Britain, to Ireland, and to the coasts of north Africa and the Canary Islands.",
+ "answers": {
+ "answer_start": [],
+ "text": []
+ }
+ },
+ {
+ "id": "56e16182e3433e1400422e28",
+ "question": "What branch of theoretical computer science deals with broadly classifying computational problems by difficulty and class of relationship?",
+ "context": "Computational complexity theory is a branch of the theory of computation in theoretical computer science that focuses on classifying computational problems according to their inherent difficulty, and relating those classes to each other. A computational problem is understood to be a task that is in principle amenable to being solved by a computer, which is equivalent to stating that the problem may be solved by mechanical application of mathematical steps, such as an algorithm.",
+ "answers": {
+ "answer_start": [
+ 0,
+ 0,
+ 0
+ ],
+ "text": [
+ "Computational complexity theory",
+ "Computational complexity theory",
+ "Computational complexity theory"
+ ]
+ }
+ },
+ {
+ "id": "5ad5316b5b96ef001a10ab76",
+ "question": "What is a manual application of mathematical steps?",
+ "context": "Computational complexity theory is a branch of the theory of computation in theoretical computer science that focuses on classifying computational problems according to their inherent difficulty, and relating those classes to each other. A computational problem is understood to be a task that is in principle amenable to being solved by a computer, which is equivalent to stating that the problem may be solved by mechanical application of mathematical steps, such as an algorithm.",
+ "answers": {
+ "answer_start": [],
+ "text": []
+ }
+ },
+ {
+ "id": "56e16839cd28a01900c67887",
+ "question": "What measure of a computational problem broadly defines the inherent difficulty of the solution?",
+ "context": "A problem is regarded as inherently difficult if its solution requires significant resources, whatever the algorithm used. The theory formalizes this intuition, by introducing mathematical models of computation to study these problems and quantifying the amount of resources needed to solve them, such as time and storage. Other complexity measures are also used, such as the amount of communication (used in communication complexity), the number of gates in a circuit (used in circuit complexity) and the number of processors (used in parallel computing). One of the roles of computational complexity theory is to determine the practical limits on what computers can and cannot do.",
+ "answers": {
+ "answer_start": [
+ 46,
+ 49,
+ 46
+ ],
+ "text": [
+ "if its solution requires significant resources",
+ "its solution requires significant resources",
+ "if its solution requires significant resources"
+ ]
+ }
+ },
+ {
+ "id": "56e16839cd28a01900c67888",
+ "question": "What method is used to intuitively assess or quantify the amount of resources required to solve a computational problem?",
+ "context": "A problem is regarded as inherently difficult if its solution requires significant resources, whatever the algorithm used. The theory formalizes this intuition, by introducing mathematical models of computation to study these problems and quantifying the amount of resources needed to solve them, such as time and storage. Other complexity measures are also used, such as the amount of communication (used in communication complexity), the number of gates in a circuit (used in circuit complexity) and the number of processors (used in parallel computing). One of the roles of computational complexity theory is to determine the practical limits on what computers can and cannot do.",
+ "answers": {
+ "answer_start": [
+ 176,
+ 176,
+ 176
+ ],
+ "text": [
+ "mathematical models of computation",
+ "mathematical models of computation",
+ "mathematical models of computation"
+ ]
+ }
+ },
+ {
+ "id": "56e16839cd28a01900c67889",
+ "question": "What are two basic primary resources used to guage complexity?",
+ "context": "A problem is regarded as inherently difficult if its solution requires significant resources, whatever the algorithm used. The theory formalizes this intuition, by introducing mathematical models of computation to study these problems and quantifying the amount of resources needed to solve them, such as time and storage. Other complexity measures are also used, such as the amount of communication (used in communication complexity), the number of gates in a circuit (used in circuit complexity) and the number of processors (used in parallel computing). One of the roles of computational complexity theory is to determine the practical limits on what computers can and cannot do.",
+ "answers": {
+ "answer_start": [
+ 305,
+ 305,
+ 305
+ ],
+ "text": [
+ "time and storage",
+ "time and storage",
+ "time and storage"
+ ]
+ }
+ },
+ {
+ "id": "5ad532575b96ef001a10ab7f",
+ "question": "What unit is measured to determine circuit simplicity?",
+ "context": "A problem is regarded as inherently difficult if its solution requires significant resources, whatever the algorithm used. The theory formalizes this intuition, by introducing mathematical models of computation to study these problems and quantifying the amount of resources needed to solve them, such as time and storage. Other complexity measures are also used, such as the amount of communication (used in communication complexity), the number of gates in a circuit (used in circuit complexity) and the number of processors (used in parallel computing). One of the roles of computational complexity theory is to determine the practical limits on what computers can and cannot do.",
+ "answers": {
+ "answer_start": [],
+ "text": []
+ }
+ },
+ {
+ "id": "5ad532575b96ef001a10ab80",
+ "question": "What number is used in perpendicular computing?",
+ "context": "A problem is regarded as inherently difficult if its solution requires significant resources, whatever the algorithm used. The theory formalizes this intuition, by introducing mathematical models of computation to study these problems and quantifying the amount of resources needed to solve them, such as time and storage. Other complexity measures are also used, such as the amount of communication (used in communication complexity), the number of gates in a circuit (used in circuit complexity) and the number of processors (used in parallel computing). One of the roles of computational complexity theory is to determine the practical limits on what computers can and cannot do.",
+ "answers": {
+ "answer_start": [],
+ "text": []
+ }
+ }
+ ]
+}
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/STS-B/dev.tsv b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/STS-B/dev.tsv
new file mode 100644
index 0000000000000000000000000000000000000000..8d689c2ccc67dc4cd533562da00e1731f80902f3
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/STS-B/dev.tsv
@@ -0,0 +1,10 @@
+index genre filename year old_index source1 source2 sentence1 sentence2 score
+0 main-captions MSRvid 2012test 0000 none none A man with a hard hat is dancing. A man wearing a hard hat is dancing. 5.000
+1 main-captions MSRvid 2012test 0002 none none A young child is riding a horse. A child is riding a horse. 4.750
+2 main-captions MSRvid 2012test 0003 none none A man is feeding a mouse to a snake. The man is feeding a mouse to the snake. 5.000
+3 main-captions MSRvid 2012test 0007 none none A woman is playing the guitar. A man is playing guitar. 2.400
+4 main-captions MSRvid 2012test 0008 none none A woman is playing the flute. A man is playing a flute. 2.750
+5 main-captions MSRvid 2012test 0010 none none A woman is cutting an onion. A man is cutting onions. 2.615
+6 main-captions MSRvid 2012test 0015 none none A man is erasing a chalk board. The man is erasing the chalk board. 5.000
+7 main-captions MSRvid 2012test 0023 none none A woman is carrying a boy. A woman is carrying her baby. 2.333
+8 main-captions MSRvid 2012test 0027 none none Three men are playing guitars. Three men are on stage playing guitars. 3.750
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/STS-B/train.tsv b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/STS-B/train.tsv
new file mode 100644
index 0000000000000000000000000000000000000000..a38be956d6020fff987ad2cd73bc576f2986d36b
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/STS-B/train.tsv
@@ -0,0 +1,10 @@
+index genre filename year old_index source1 source2 sentence1 sentence2 score
+0 main-captions MSRvid 2012test 0001 none none A plane is taking off. An air plane is taking off. 5.000
+1 main-captions MSRvid 2012test 0004 none none A man is playing a large flute. A man is playing a flute. 3.800
+2 main-captions MSRvid 2012test 0005 none none A man is spreading shreded cheese on a pizza. A man is spreading shredded cheese on an uncooked pizza. 3.800
+3 main-captions MSRvid 2012test 0006 none none Three men are playing chess. Two men are playing chess. 2.600
+4 main-captions MSRvid 2012test 0009 none none A man is playing the cello. A man seated is playing the cello. 4.250
+5 main-captions MSRvid 2012test 0011 none none Some men are fighting. Two men are fighting. 4.250
+6 main-captions MSRvid 2012test 0012 none none A man is smoking. A man is skating. 0.500
+7 main-captions MSRvid 2012test 0013 none none The man is playing the piano. The man is playing the guitar. 1.600
+8 main-captions MSRvid 2012test 0014 none none A man is playing on a guitar and singing. A woman is playing an acoustic guitar and singing. 2.200
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/conll/sample.json b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/conll/sample.json
new file mode 100644
index 0000000000000000000000000000000000000000..0bc42a92fe8c934850df8967a293eb8df7cd3c88
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/conll/sample.json
@@ -0,0 +1,10 @@
+{"words": ["He", "was", "the", "27th", "pitcher", "used", "by", "the", "Angels", "this", "season", ",", "tying", "a", "major-league", "record", "."], "ner": ["O", "O", "O", "O", "O", "O", "O", "O", "B-ORG", "O", "O", "O", "O", "O", "O", "O", "O"]}
+{"words": ["CHICAGO", "AT", "ATLANTA"], "ner": ["B-ORG", "O", "B-LOC"]}
+{"words": ["President", "Bill", "Clinton", "earlier", "this", "month", "invoked", "special", "powers", "to", "appoint", "Fowler", "during", "the", "congressional", "recess", "because", "the", "Senate", "delayed", "confirming", "his", "nomination", "."], "ner": ["O", "B-PER", "I-PER", "O", "O", "O", "O", "O", "O", "O", "O", "B-PER", "O", "O", "O", "O", "O", "O", "B-ORG", "O", "O", "O", "O", "O"]}
+{"words": ["goals", "for", ",", "goals", "against", ",", "points", ")", "."], "ner": ["O", "O", "O", "O", "O", "O", "O", "O", "O"]}
+{"words": ["\"", "It", "is", "one", "step", "short", "of", "an", "emergency", "situation", ",", "\"", "a", "police", "spokesman", "said", "via", "telephone", "from", "a", "command", "post", "in", "the", "bush", "."], "ner": ["O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O"]}
+{"words": ["U.S.", "Ambassador", "Myles", "Frechette", "applauded", "the", "move", ",", "saying", "it", "could", "prompt", "the", "Clinton", "administration", "to", "remove", "Colombia", "from", "a", "list", "of", "outcast", "nations", "that", "have", "failed", "to", "cooperate", "in", "U.S.", "counternarcotics", "efforts", "."], "ner": ["B-LOC", "O", "B-PER", "I-PER", "O", "O", "O", "O", "O", "O", "O", "O", "O", "B-PER", "O", "O", "O", "B-LOC", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "B-LOC", "O", "O", "O"]}
+{"words": ["Halftime"], "ner": ["O"]}
+{"words": ["It", "has", "manufacturing", "plants", "in", "San", "Diego", ";", "Creedmoor", ",", "N.C.", ";", "Hampshire", ",", "England", ";", "and", "Tijuana", ",", "Mexico", ",", "and", "distributes", "its", "prodcuts", "in", "more", "than", "120", "countries", "."], "ner": ["O", "O", "O", "O", "O", "B-LOC", "I-LOC", "O", "B-LOC", "O", "B-LOC", "O", "B-LOC", "O", "B-LOC", "O", "O", "B-LOC", "O", "B-LOC", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O"]}
+{"words": ["Scotland", "manager", "Craig", "Brown", "said", "on", "Thursday", ":", "\"", "I", "'ve", "watched", "Duncan", "Ferguson", "in", "action", "twice", "recently", "and", "he", "'s", "bang", "in", "form", "."], "ner": ["B-LOC", "O", "B-PER", "I-PER", "O", "O", "O", "O", "O", "O", "O", "O", "B-PER", "I-PER", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O"]}
+{"words": ["Clinton", "flew", "in", "by", "helicopter", "from", "Michigan", "City", ",", "Indiana", ",", "after", "ending", "a", "four-day", ",", "559-mile", "trip", "aboard", "a", "campaign", "train", "from", "Washington", "."], "ner": ["B-PER", "O", "O", "O", "O", "O", "B-LOC", "I-LOC", "O", "B-LOC", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "B-LOC", "O"]}
\ No newline at end of file
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/swag/sample.json b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/swag/sample.json
new file mode 100644
index 0000000000000000000000000000000000000000..d00ad8d184e380570c05836c3c1e167f46256cbb
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/swag/sample.json
@@ -0,0 +1,10 @@
+{"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.", "label": 0, "sent1": "Members of the procession walk down the street holding small horn brass instruments.", "sent2": "A drum line"}
+{"ending0": "are playing ping pong and celebrating one left each in quick.", "ending1": "wait slowly towards the cadets.", "ending2": "continues to play as well along the crowd along with the band being interviewed.", "ending3": "continue to play marching, interspersed.", "label": 3, "sent1": "A drum line passes by walking down the street playing their instruments.", "sent2": "Members of the procession"}
+{"ending0": "pay the other coaches to cheer as people this chatter dips in lawn sheets.", "ending1": "walk down the street holding small horn brass instruments.", "ending2": "is seen in the background.", "ending3": "are talking a couple of people playing a game of tug of war.", "label": 1, "sent1": "A group of members in green uniforms walks waving flags.", "sent2": "Members of the procession"}
+{"ending0": "are playing ping pong and celebrating one left each in quick.", "ending1": "wait slowly towards the cadets.", "ending2": "makes a square call and ends by jumping down into snowy streets where fans begin to take their positions.", "ending3": "play and go back and forth hitting the drums while the audience claps for them.", "label": 3, "sent1": "A drum line passes by walking down the street playing their instruments.", "sent2": "Members of the procession"}
+{"ending0": "finishes the song and lowers the instrument.", "ending1": "hits the saxophone and demonstrates how to properly use the racquet.", "ending2": "finishes massage the instrument again and continues.", "ending3": "continues dancing while the man gore the music outside while drums.", "label": 0, "sent1": "The person plays a song on the violin.", "sent2": "The man"}
+{"ending0": "finishes playing then marches their tenderly.", "ending1": "walks in frame and rubs on his hands, and then walks into a room.", "ending2": "continues playing guitar while moving from the camera.", "ending3": "plays a song on the violin.", "label": 3, "sent1": "The person holds up the violin to his chin and gets ready.", "sent2": "The person"}
+{"ending0": "examines the instrument in his hand.", "ending1": "stops playing the drums and waves over the other boys.", "ending2": "lights the cigarette and sticks his head in.", "ending3": "drags off the vacuum.", "label": 0, "sent1": "A person retrieves an instrument from a closet.", "sent2": "The man"}
+{"ending0": "studies a picture of the man playing the violin.", "ending1": "holds up the violin to his chin and gets ready.", "ending2": "stops to speak to the camera again.", "ending3": "puts his arm around the man and backs away.", "label": 1, "sent1": "The man examines the instrument in his hand.", "sent2": "The person"}
+{"ending0": "hands her another phone.", "ending1": "takes the drink, then holds it.", "ending2": "looks off then looks at someone.", "ending3": "stares blearily down at the floor.", "label": 3, "sent1": "Someone walks over to the radio.", "sent2": "Someone"}
+{"ending0": "looks off then looks at someone.", "ending1": "hands her another phone.", "ending2": "takes the drink, then holds it.", "ending3": "turns on a monitor.", "label": 3, "sent1": "Someone walks over to the radio.", "sent2": "Someone"}
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/wiki_text/wiki_00 b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/wiki_text/wiki_00
new file mode 100644
index 0000000000000000000000000000000000000000..773074910b487eed863883642ea192b972bfc84b
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/wiki_text/wiki_00
@@ -0,0 +1,251 @@
+
+Anarchism
+
+Anarchism is a political philosophy and movement that rejects all involuntary, coercive forms of hierarchy. It radically calls for the abolition of the state which it holds to be undesirable, unnecessary, and harmful.
+
+The history of anarchism stretches back to prehistory, when humans lived in anarchistic societies long before the establishment of formal states, realms or empires. With the rise of organised hierarchical bodies, skepticism toward authority also rose, but it was not until the 19th century that a self-conscious political movement emerged. During the latter half of the 19th and the first decades of the 20th century, the anarchist movement flourished in most parts of the world and had a significant role in worker's struggles for emancipation. Various anarchist schools of thought formed during this period.
+
+Anarchists took part in several revolutions, most notably in the Spanish Civil War, where they were crushed along with the alliance to restore the Second Republic by the fascist forces of the Nationalist faction and its foreign allies in Nazi Germany, Fascist Italy, Portuguese Dictatorship and the Catholic Church in 1939, marking the end of the classical era of anarchism. In the last decades of the 20th century and into the 21st century, the anarchist movement has been resurgent once more.
+
+Anarchism employs various tactics in order to meet its ideal ends; these can be broadly separated into revolutionary and evolutionary tactics. There is significant overlap between the two, which are merely descriptive. Revolutionary tactics aim to bring down authority and state, and have taken a violent turn in the past. Evolutionary tactics aim to prefigure what an anarchist society would be like. Anarchist thought, criticism, and praxis has played a part in diverse areas of human society.
+
+The etymological origin of "anarchism" is from the Ancient Greek "anarkhia", meaning "without a ruler", composed of the prefix "an-" (i.e. "without") and the word "arkhos" (i.e. "leader" or "ruler"). The suffix "-ism" denotes the ideological current that favours anarchy. "Anarchism" appears in English from 1642 as "anarchisme" and "anarchy" from 1539. Various factions within the French Revolution labelled their opponents as "anarchists", although few such accused shared many views with later anarchists. Many revolutionaries of the 19th century such as William Godwin (1756–1836) and Wilhelm Weitling (1808–1871) would contribute to the anarchist doctrines of the next generation, but they did not use "anarchist" or "anarchism" in describing themselves or their beliefs.
+
+The first political philosopher to call himself an "anarchist" () was Pierre-Joseph Proudhon (1809–1865), marking the formal birth of anarchism in the mid-19th century. Since the 1890s and beginning in France, "libertarianism" has often been used as a synonym for anarchism and its use as a synonym is still common outside the United States. On the other hand, some use "libertarianism" to refer to individualistic free-market philosophy only, referring to free-market anarchism as "libertarian anarchism".
+
+While opposition to the state is central to anarchist thought, defining anarchism is not an easy task as there is a lot of discussion among scholars and anarchists on the matter and various currents perceive anarchism slightly differently. Hence, it might be true to say that anarchism is a cluster of political philosophies opposing authority and hierarchical organization (including the state, capitalism, nationalism and all associated institutions) in the conduct of all human relations in favour of a society based on voluntary association, on freedom and on decentralisation, but this definition has the same shortcomings as the definition based on etymology (which is simply a negation of a ruler), or based on anti-statism (anarchism is much more than that) or even the anti-authoritarian (which is an "a posteriori" conclusion). Nonetheless, major elements of the definition of anarchism include the following:
+
+During the prehistoric era of mankind, an established authority did not exist. It was after the creation of towns and cities that institutions of authority were established and anarchistic ideas espoused as a reaction. Most notable precursors to anarchism in the ancient world were in China and Greece. In China, philosophical anarchism (i.e. the discussion on the legitimacy of the state) was delineated by Taoist philosophers Zhuang Zhou and Laozi.
+
+Likewise, anarchic attitudes were articulated by tragedians and philosophers in Greece. Aeschylus and Sophocles used the myth of Antigone to illustrate the conflict between rules set by the state and personal autonomy. Socrates questioned Athenian authorities constantly and insisted to the right of individual freedom of consciousness. Cynics dismissed human law ("nomos") and associated authorities while trying to live according to nature ("physis"). Stoics were supportive of a society based on unofficial and friendly relations among its citizens without the presence of a state.
+
+During the Middle Ages, there was no anarchistic activity except some ascetic religious movements in the Muslim world or in Christian Europe. This kind of tradition later gave birth to religious anarchism. In the Sasanian Empire, Mazdak called for an egalitarian society and the abolition of monarchy, only to be soon executed by Emperor Kavad I.
+
+In Basra, religious sects preached against the state. In Europe, various sects developed anti-state and libertarian tendencies. Libertarian ideas further emerged during the Renaissance with the spread of reasoning and humanism through Europe. Novelists fictionalised ideal societies that were based not on coercion but voluntarism. The Enlightenment further pushed towards anarchism with the optimism for social progress.
+
+During the French Revolution, partisan groups such as the Enragés and the saw a turning point in the fermentation of anti-state and federalist sentiments. The first anarchist currents developed throughout the 18th century—William Godwin espoused philosophical anarchism in England, morally delegitimizing the state, Max Stirner's thinking paved the way to individualism, and Pierre-Joseph Proudhon's theory of mutualism found fertile soil in France. This era of classical anarchism lasted until the end of the Spanish Civil War of 1936 and is considered the golden age of anarchism.
+Drawing from mutualism, Mikhail Bakunin founded collectivist anarchism and entered the International Workingmen's Association, a class worker union later known as the First International that formed in 1864 to unite diverse revolutionary currents. The International became a significant political force, with Karl Marx being a leading figure and a member of its General Council. Bakunin's faction (the Jura Federation) and Proudhon's followers (the mutualists) opposed Marxist state socialism, advocating political abstentionism and small property holdings. After bitter disputes, the Bakuninists were expelled from the International by the Marxists at the 1872 Hague Congress. Bakunin famously predicted that if revolutionaries gained power by Marx's terms, they would end up the new tyrants of workers. After being expelled, anarchists formed the St. Imier International. Under the influence of Peter Kropotkin, a Russian philosopher and scientist, anarcho-communism overlapped with collectivism. Anarcho-communists, who drew inspiration from the 1871 Paris Commune, advocated for free federation and for the distribution of goods according to one's needs.
+
+At the turn of the century, anarchism had spread all over the world. In China, small groups of students imported the humanistic pro-science version of anarcho-communism. Tokyo was a hotspot for rebellious youth from countries of the far east, travelling to the Japanese capital to study. In Latin America, Argentina was a stronghold for anarcho-syndicalism, where it became the most prominent left-wing ideology. During this time, a minority of anarchists adopted tactics of revolutionary political violence. This strategy became known as propaganda of the deed. The dismemberment of the French socialist movement into many groups, and the execution and exile of many Communards to penal colonies following the suppression of the Paris Commune, favoured individualist political expression and acts. Even though many anarchists distanced themselves from these terrorist acts, infamy came upon the movement. Illegalism was another strategy which some anarchists adopted during this period.
+Anarchists enthusiastically participated in the Russian Revolution—despite concerns—in opposition to the Whites. However, they met harsh suppression after the Bolshevik government was stabilized. Several anarchists from Petrograd and Moscow fled to Ukraine, notably leading to the Kronstadt rebellion and Nestor Makhno's struggle in the Free Territory. With the anarchists being crushed in Russia, two new antithetical currents emerged, namely platformism and synthesis anarchism. The former sought to create a coherent group that would push for revolution while the latter were against anything that would resemble a political party. Seeing the victories of the Bolsheviks in the October Revolution and the resulting Russian Civil War, many workers and activists turned to communist parties, which grew at the expense of anarchism and other socialist movements. In France and the United States, members of major syndicalist movements, the General Confederation of Labour and Industrial Workers of the World, left their organisations and joined the Communist International.
+
+In the Spanish Civil War, anarchists and syndicalists (CNT and FAI) once again allied themselves with various currents of leftists. A long tradition of Spanish anarchism led to anarchists playing a pivotal role in the war. In response to the army rebellion, an anarchist-inspired movement of peasants and workers, supported by armed militias, took control of Barcelona and of large areas of rural Spain, where they collectivised the land. The Soviet Union provided some limited assistance at the beginning of the war, but the result was a bitter fight among communists and anarchists at a series of events named May Days as Joseph Stalin tried to seize control of the Republicans.
+
+At the end of World War II, the anarchist movement was severely weakened. However, the 1960s witnessed a revival of anarchism likely caused by a perceived failure of Marxism–Leninism and tensions built by the Cold War. During this time, anarchism took root in other movements critical towards both the state and capitalism, such as the anti-nuclear, environmental and pacifist movements, the New Left, and the counterculture of the 1960s. Anarchism became associated with punk subculture, as exemplified by bands such as Crass and the Sex Pistols, and the established feminist tendencies of anarcha-feminism returned with vigour during the second wave of feminism.
+
+Around the turn of the 21st century, anarchism grew in popularity and influence within anti-war, anti-capitalist, and anti-globalisation movements. Anarchists became known for their involvement in protests against the World Trade Organization, the Group of Eight and the World Economic Forum. During the protests, "ad hoc" leaderless anonymous cadres known as black blocs engaged in rioting, property destruction, and violent confrontations with the police. Other organisational tactics pioneered in this time include security culture, affinity groups, and the use of decentralised technologies such as the internet. A significant event of this period was the confrontations at the WTO conference in Seattle in 1999. Anarchist ideas have been influential in the development of the Zapatistas in Mexico and the Democratic Federation of Northern Syria, more commonly known as Rojava, a "de facto" autonomous region in northern Syria.
+
+Anarchist schools of thought have been generally grouped into two main historical traditions, social anarchism and individualist anarchism, owing to their different origins, values and evolution. The individualist current emphasises negative liberty in opposing restraints upon the free individual, while the social current emphasises positive liberty in aiming to achieve the free potential of society through equality and social ownership. In a chronological sense, anarchism can be segmented by the classical currents of the late 19th century, and the post-classical currents (such as anarcha-feminism, green anarchism and post-anarchism) developed thereafter.
+
+Beyond the specific factions of anarchist movements which constitute political anarchism lies philosophical anarchism, which holds that the state lacks moral legitimacy, without necessarily accepting the imperative of revolution to eliminate it. A component especially of individualist anarchism, philosophical anarchism may tolerate the existence of a minimal state, but argues that citizens have no moral obligation to obey government when it conflicts with individual autonomy. Anarchism pays significant attention to moral arguments since ethics have a central role in anarchist philosophy.
+
+One reaction against sectarianism within the anarchist milieu was anarchism without adjectives, a call for toleration and unity among anarchists first adopted by Fernando Tarrida del Mármol in 1889 in response to the bitter debates of anarchist theory at the time. Despite separation, the various anarchist schools of thought are not seen as distinct entities, but as tendencies that intermingle.
+
+Anarchism is usually placed on the far-left of the political spectrum. Much of its economics and legal philosophy reflect anti-authoritarian, anti-statist, and libertarian interpretations of the radical left-wing and socialist politics of collectivism, communism, individualism, mutualism, and syndicalism, among other libertarian socialist economic theories. As anarchism does not offer a fixed body of doctrine from a single particular worldview, many anarchist types and traditions exist, and varieties of anarchy diverge widely.
+
+Inceptive currents among classical anarchist currents were mutualism and individualism. They were followed by the major currents of social anarchism (collectivist, communist, and syndicalist). They differ on organizational and economic aspects of their ideal society.
+
+Mutualism is an 18th-century economic theory that was developed into anarchist theory by Pierre-Joseph Proudhon. Its aims include reciprocity, free association, voluntary contract, federation, and credit and currency reform that would be regulated by a bank of the people. Mutualism has been retrospectively characterised as ideologically situated between individualist and collectivist forms of anarchism. Proudhon first characterised his goal as a "third form of society, the synthesis of communism and property".
+
+Collectivist anarchism, also known as anarchist collectivism or anarcho-collectivism, is a revolutionary socialist form of anarchism commonly associated with Mikhail Bakunin. Collectivist anarchists advocate collective ownership of the means of production, theorised to be achieved through violent revolution, and that workers be paid according to time worked, rather than goods being distributed according to need as in communism. Collectivist anarchism arose alongside Marxism, but rejected the dictatorship of the proletariat despite the stated Marxist goal of a collectivist stateless society. Anarcho-communism, also known as anarchist-communism, communist anarchism, and libertarian communism, is a theory of anarchism that advocates a communist society with common ownership of the means of production, direct democracy, and a horizontal network of voluntary associations and workers' councils with production and consumption based on the guiding principle: "From each according to his ability, to each according to his need". Anarcho-communism developed from radical socialist currents after the French Revolution, but it was first formulated as such in the Italian section of the First International. It was later expanded upon in the theoretical work of Peter Kropotkin.
+
+Anarcho-syndicalism, also referred to as revolutionary syndicalism, is a branch of anarchism that views labour syndicates as a potential force for revolutionary social change, replacing capitalism and the state with a new society democratically self-managed by workers. The basic principles of anarcho-syndicalism are workers' solidarity, direct action, and workers' self-management.
+
+Individualist anarchism refers to several traditions of thought within the anarchist movement that emphasise the individual and their will over any kinds of external determinants. Early influences on individualist forms of anarchism include William Godwin, Max Stirner and Henry David Thoreau. Through many countries, individualist anarchism attracted a small yet diverse following of Bohemian artists and intellectuals as well as young anarchist outlaws in what became known as illegalism and individual reclamation.
+
+Anarchist principles undergird contemporary radical social movements of the left. Interest in the anarchist movement developed alongside momentum in the anti-globalization movement, whose leading activist networks were anarchist in orientation. As the movement shaped 21st century radicalism, wider embrace of anarchist principles signaled a revival of interest. Contemporary news coverage which emphasizes black bloc demonstrations has reinforced anarchism's historical association with chaos and violence, although its publicity has also led more scholars to engage with the anarchist movement. Anarchism has continued to generate many philosophies and movements—at times eclectic, drawing upon various sources, and syncretic, combining disparate concepts to create new philosophical approaches. The anti-capitalist tradition of classical anarchism has remained prominent within contemporary currents.
+
+Various anarchist groups, tendencies, and schools of thought exist today, making it difficult to describe contemporary anarchist movement. While theorists and activists have established "relatively stable constellations of anarchist principles", there is no consensus on which principles are core. As a result, commentators describe multiple "anarchisms" (rather than a singular "anarchism") in which common principles are shared between schools of anarchism while each group prioritizes those principles differently. For example, gender equality can be a common principle but ranks as a higher priority to anarcha-feminists than anarchist communists. Anarchists are generally committed against coercive authority in all forms, namely "all centralized and hierarchical forms of government (e.g., monarchy, representative democracy, state socialism, etc.), economic class systems (e.g., capitalism, Bolshevism, feudalism, slavery, etc.), autocratic religions (e.g., fundamentalist Islam, Roman Catholicism, etc.), patriarchy, heterosexism, white supremacy, and imperialism". However, anarchist schools disagree on the methods by which these forms should be opposed.
+
+Anarchists' tactics take various forms but in general serve two major goals—first, to oppose the Establishment; and second, to promote anarchist ethics and reflect an anarchist vision of society, illustrating the unity of means and ends. A broad categorization can be made between aims to destroy oppressive states and institutions by revolutionary means, and aims to change society through evolutionary means. Evolutionary tactics reject violence and take a gradual approach to anarchist aims, though there is significant overlap between the two.
+
+Anarchist tactics have shifted during the course of the last century. Anarchists during the early 20th century focused more on strikes and militancy, while contemporary anarchists use a broader array of approaches.
+
+During the classical era, anarchists had a militant tendency. Not only did they confront state armed forces (as in Spain and Ukraine) but some of them also employed terrorism as propaganda of the deed. Assassination attempts were carried out against heads of state, some of which were successful. Anarchists also took part in revolutions. Anarchist perspectives towards violence have always been perplexing and controversial. On one hand, anarcho-pacifists point out the unity of means and ends. On the other hand, other anarchist groups advocate direct action, a tactic which can include acts of sabotage or even acts of terrorism. This attitude was quite prominent a century ago; seeing the state as a tyrant, some anarchists believed that they had every right to oppose its oppression by any means possible. Emma Goldman and Errico Malatesta, who were proponents of limited use of violence, argued that violence is merely a reaction to state violence as a necessary evil.
+
+Anarchists took an active role in strikes, although they tended to be antipathetic to formal syndicalism, seeing it as reformist. They saw it as a part of the movement which sought to overthrow the state and capitalism. Anarchists also reinforced their propaganda within the arts, some of whom practiced nudism. They also built communities which were based on friendship. They were also involved in the press.
+
+In the current era, Italian anarchist Alfredo Bonanno, a proponent of insurrectionary anarchism, has reinstated the debate on violence by rejecting the nonviolence tactic adopted since the late 19th century by Kropotkin and other prominent anarchists afterwards. Both Bonanno and the French group The Invisible Committee advocate for small, informal affiliation groups, where each member is responsible for their own actions but works together to bring down oppression utilizing sabotage and other violent means against state, capitalism and other enemies. Members of The Invisible Committee were arrested in 2008 on various charges, terrorism included.
+
+Overall, today's anarchists are much less violent and militant than their ideological ancestors. They mostly engage in confronting the police during demonstrations and riots, especially in countries like Canada, Mexico or Greece. Μilitant black bloc protest groups are known for clashing with the police. However, anarchists not only clash with state operators; they also engage in the struggle against fascists and racists, taking anti-fascist action and mobilizing to prevent hate rallies from happening.
+
+Anarchists commonly employ direct action. This can take the form of disrupting and protesting against unjust hierarchy, or the form of self-managing their lives through the creation of counter-institutions such as communes and non-hierarchical collectives. Often, decision-making is handled in an anti-authoritarian way, with everyone having equal say in each decision, an approach known as horizontalism. Contemporary-era anarchists have been engaging with various grassroots movements that are not explicitly anarchist but are more or less based on horizontalism, respecting personal autonomy, and participating in mass activism such as strikes and demonstrations. The newly coined term "small-a anarchism", in contrast with the "big-A anarchism" of the classical era, signals their tendency not to base their thoughts and actions on classical-era anarchism or to refer to Kropotkin or Proudhon to justify their opinions. They would rather base their thought and praxis on their own experience, which they will later theorize.
+
+The decision-making process of small affinity anarchist groups play a significant tactical role. Anarchists have employed various methods in order to build a rough consensus among members of their group, without the need of a leader or a leading group. One way is for an individual from the group to play the role of facilitator to help achieve a consensus without taking part in the discussion themselves or promoting a specific point. Minorities usually accept rough consensus, except when they feel the proposal contradicts anarchist goals, values, or ethics. Anarchists usually form small groups (5–20 individuals) to enhance autonomy and friendships among their members. These kind of groups more often than not interconnect with each other, forming larger networks. Anarchists still support and participate in strikes, especially wildcat strikes; these are leaderless strikes not organised centrally by a syndicate.
+
+Anarchists have gone online to spread their message. As in the past, newspapers and journals are used; however, because of distributional and other difficulties, anarchists have found it easier to create websites, hosting electronic libraries and other portals. Anarchists were also involved in developing various software that are available for free. The way these hacktivists work to develop and distribute resembles the anarchist ideals, especially when it comes to preserving user's privacy from state surveillance.
+
+Anarchists organize themselves to squat and reclaim public spaces. During important events such as protests and when spaces are being occupied, they are often called Temporary Autonomous Zones (TAZ), spaces where surrealism, poetry and art are blended to display the anarchist ideal. As seen by anarchists, squatting is a way to regain urban space from the capitalist market, serving pragmatical needs, and is also seen an exemplary direct action. Acquiring space enables anarchists to experiment with their ideas and build social bonds. Adding up these tactics, and having in mind that not all anarchists share the same attitudes towards them, along with various forms of protesting at highly symbolic events, make up a carnivalesque atmosphere that is part of contemporary anarchist vividity.
+
+As anarchism is a philosophy that embodies many diverse attitudes, tendencies, and schools of thought, and disagreement over questions of values, ideology, and tactics is common, its diversity has led to widely different uses of identical terms among different anarchist traditions, which has created a number of definitional concerns in anarchist theory. For instance, the compatibility of capitalism, nationalism and religion with anarchism is widely disputed. Similarly, anarchism enjoys complex relationships with ideologies such as Marxism, communism, collectivism and trade unionism. Anarchists may be motivated by humanism, divine authority, enlightened self-interest, veganism, or any number of alternative ethical doctrines. Phenomena such as civilisation, technology (e.g. within anarcho-primitivism) and the democratic process may be sharply criticised within some anarchist tendencies and simultaneously lauded in others.
+
+Gender and sexuality carry along them dynamics of hierarchy; anarchism is obliged to address, analyse and oppose the suppression of one's autonomy because of the dynamics that gender roles traditionally impose.
+
+A historical current that arose and flourished during 1890 and 1920 within anarchism was free love; in contemporary anarchism, this current survives as a tendency to support polyamory and queer anarchism. Free love advocates were against marriage, which they saw as a way of men imposing authority over women, largely because marriage law greatly favoured the power of men. The notion of free love, though, was much broader; it included critique of the established order that limited women's sexual freedom and pleasure. Such free love movements contributed to the establishment of communal houses, where large groups of travelers, anarchists, and other activists slept in beds together. Free love had roots both in Europe and the United States. Some anarchists, however, struggled with the jealousy that arose from free love. Anarchist feminists were advocates of free love, against marriage, were pro-choice (utilizing a contemporary term) and had a likewise agenda. Anarchist and non-anarchist feminists differed on suffrage, but were nonetheless supportive of one another.
+
+During the second half of the 20th century, anarchism intermingled with the second wave of feminism, radicalizing some currents of the feminist movement (and being influenced as well). By the latest decades of the 20th century, anarchists and feminists were advocating for the rights and autonomy of women, gays, queers and other marginalized groups, with some feminist thinkers suggesting a fusion of the two currents. With the third wave of feminism, sexual identity and compulsory heterosexuality became a subject of study for anarchists, which yielded a post-structuralist critique of sexual normality. However, some anarchists distanced themselves from this line of thinking, suggesting that it leaned towards individualism and was, therefore, dropping the cause of social liberation.
+
+The interest of anarchists in education stretches back to the first emergence of classical anarchism. Anarchists consider 'proper' education, which sets the foundations of the future autonomy of the individual and the society, to be an act of mutual aid. Anarchist writers such as Willian Godwin and Max Stirner attacked both state education and private education as another means by which the ruling class replicate their privileges.
+
+In 1901, Catalan anarchist and free thinker Francisco Ferrer established the Escuela Moderna in Barcelona as an opposition to the established education system, which was dictated largely by the Catholic Church. Ferrer's approach was secular, rejecting both state and church involvement in the educational process, and gave pupils large amounts of autonomy in planning their work and attendance. Ferrer aimed to educate the working class and explicitly sought to foster class consciousness among students. The school closed after constant harassment by the state and Ferrer was later arrested. His ideas, however, formed the inspiration for a series of modern schools around the world. Christian anarchist Leo Tolstoy also established a similar school, with its founding principle, according to Tolstoy, being that "for education to be effective it had to be free". In a similar token, A. S. Neill founding what became Summerhill School in 1921, also declaring being free from coercion.
+
+Anarchist education is based largely on the idea that a child's right to develop freely, without manipulation, ought to be respected, and that rationality will lead children to morally good conclusions. However, there has been little consensus among anarchist figures as to what constitutes manipulation; Ferrer, for example, believed that moral indoctrination was necessary and explicitly taught pupils that equality, liberty, and social justice were not possible under capitalism (along with other critiques of nationalism and government).
+
+Late 20th century and contemporary anarchist writers (such as Colin Ward, Herbert Read and Paul Goodman) intensified and expanded the anarchist critique of state education, largely focusing on the need for a system that focuses on children's creativity rather than on their ability to attain a career or participate in consumer society. Contemporary anarchists, such as Colin Ward, have further argued that state education serves to perpetuate socio-economic inequality.
+
+While few anarchist education institutions have survived to the modern day, major tenets of anarchist schools, such as respect for child autonomy and relying on reasoning rather than indoctrination as a teaching method, have spread among mainstream educational institutions.
+
+Objection to the state and its institutions is a "sine qua non" of anarchism. Anarchists consider the state as a tool of domination and believe it to be illegitimate regardless of its political tendencies. Instead of people being able to control the aspects of their life, major decisions are taken by a small elite. Authority ultimately rests solely on power, regardless of whether that power is open or transparent, as it still has the ability to coerce people. Another anarchist argument against states is that the people constituting a government, even the most altruistic among officials, will unavoidably seek to gain more power, leading to corruption. Anarchists consider the idea that the state is the collective will of the people to be an unachievable fiction, due to the fact that the ruling class is distinct from the rest of society.
+
+The connection between anarchism and art was quite profound during the classical era of anarchism, especially among artistic currents that were developing during that era, such as futurists, surrealists, and others, while in literature anarchism was mostly associated with the New Apocalyptics and the Neo-romanticism movement. In music, anarchism has been associated with music scenes such as Punk. Anarchists such as Leo Tolstoy and Herbert Read argued that the border between the artist and the non-artist, what separates art from a daily act, is a construct produced by the alienation caused by capitalism, and it prevents humans from living a joyful life.
+
+Other anarchists advocated for or used art as a means to achieve anarchist ends. In his book Breaking the Spell: A History of Anarchist Filmmakers, Videotape Guerrillas, and Digital Ninjas Chris Robé claims that "anarchist-inflected practices have increasingly structured movement-based video activism."
+
+Three overlapping properties made art useful to anarchists: It could depict a critique of existing society and hierarchies; it could serve as a prefigurative tool to reflect the anarchist ideal society, and also it could turn into a means of direct action, in protests for example. As it appeals to both emotion and reason, art could appeal to the "whole human" and have a powerful effect.
+
+Philosophy lecturer Andrew G. Fiala has listed five main arguments against anarchism. Firstly, he notes that anarchism is related to violence and destruction, not only in the pragmatic world (i.e. at protests) but in the world of ethics as well. The second argument is that it is impossible for a society to function without a state or something like a state, acting to protect citizens from criminality. Fiala takes "Leviathan" from Thomas Hobbes and the night-watchman state from philosopher Robert Nozick as examples. Thirdly, anarchism is evaluated as unfeasible or utopian since the state can not be defeated practically; this line of arguments most often calls for political action within the system to reform it. The fourth argument is that anarchism is self-contradictory since while it advocates for no-one to "archiei", if accepted by the many, then anarchism will turn into the ruling political theory. In this line of criticism also comes the self contradiction that anarchist calls for collective action while anarchism endorses the autonomy of the individual and hence no collective action can be taken. Lastly, Fiala mentions a critique towards philosophical anarchism, of being ineffective (all talk and thoughts) and in the meantime capitalism and bourgeois class remains strong.
+
+Philosophical anarchism has met the criticism of members of academia, following the release of pro-anarchist books such as A. John Simmons' "Moral Principles and Political Obligations" (1979). Law professor William A. Edmundson authored an essay arguing against three major philosophical anarchist principles, which he finds fallacious; Edmundson claims that while the individual does not owe a normal state a duty of obedience, this does not imply that anarchism is the inevitable conclusion, and the state is still morally legitimate.
+
+
+
+
+
+
+
+
+
+Autism
+
+Autism is a developmental disorder characterized by difficulties with social interaction and communication, and by restricted and repetitive behavior. Parents often notice signs during the first three years of their child's life. These signs often develop gradually, though some children with autism experience worsening in their communication and social skills after reaching developmental milestones at a normal pace.
+Autism is associated with a combination of genetic and environmental factors. Risk factors during pregnancy include certain infections, such as rubella, toxins including valproic acid, alcohol, cocaine, pesticides, lead, and air pollution, fetal growth restriction, and autoimmune diseases. Controversies surround other proposed environmental causes; for example, the vaccine hypothesis, which has been disproven. Autism affects information processing in the brain and how nerve cells and their synapses connect and organize; how this occurs is not well understood. The Diagnostic and Statistical Manual of Mental Disorders (DSM-5), combines autism and less severe forms of the condition, including Asperger syndrome and pervasive developmental disorder not otherwise specified (PDD-NOS) into the diagnosis of autism spectrum disorder (ASD).
+Early behavioral interventions or speech therapy can help children with autism gain self-care, social, and communication skills. Although there is no known cure, there have been cases of children who recovered. Some autistic adults are unable to live independently. An autistic culture has developed, with some individuals seeking a cure and others believing autism should be accepted as a difference to be accommodated instead of cured.
+Globally, autism is estimated to affect 24.8 million people . In the 2000s, the number of people affected was estimated at 1–2 per 1,000 people worldwide. In the developed countries, about 1.5% of children are diagnosed with ASD , from 0.7% in 2000 in the United States. It occurs four-to-five times more often in males than females. The number of people diagnosed has increased dramatically since the 1960s, which may be partly due to changes in diagnostic practice. The question of whether actual rates have increased is unresolved.
+Autism is a highly variable, neurodevelopmental disorder whose symptoms first appears during infancy or childhood, and generally follows a steady course without remission. People with autism may be severely impaired in some respects but average, or even superior, in others. Overt symptoms gradually begin after the age of six months, become established by age two or three years and tend to continue through adulthood, although often in more muted form. It is distinguished by a characteristic triad of symptoms: impairments in social interaction, impairments in communication, and repetitive behavior. Other aspects, such as atypical eating, are also common but are not essential for diagnosis. Individual symptoms of autism occur in the general population and appear not to associate highly, without a sharp line separating pathologically severe from common traits.
+
+Social deficits distinguish autism and the related autism spectrum disorders (ASD; see Classification) from other developmental disorders. People with autism have social impairments and often lack the intuition about others that many people take for granted. Noted autistic Temple Grandin described her inability to understand the social communication of neurotypicals, or people with typical neural development, as leaving her feeling "like an anthropologist on Mars".
+
+Unusual social development becomes apparent early in childhood. Autistic infants show less attention to social stimuli, smile and look at others less often, and respond less to their own name. Autistic toddlers differ more strikingly from social norms; for example, they have less eye contact and turn-taking, and do not have the ability to use simple movements to express themselves, such as pointing at things. Three- to five-year-old children with autism are less likely to exhibit social understanding, approach others spontaneously, imitate and respond to emotions, communicate nonverbally, and take turns with others. However, they do form attachments to their primary caregivers. Most children with autism display moderately less attachment security than neurotypical children, although this difference disappears in children with higher mental development or less pronounced autistic traits. Older children and adults with ASD perform worse on tests of face and emotion recognition although this may be partly due to a lower ability to define a person's own emotions.
+
+Children with high-functioning autism have more intense and frequent loneliness compared to non-autistic peers, despite the common belief that children with autism prefer to be alone. Making and maintaining friendships often proves to be difficult for those with autism. For them, the quality of friendships, not the number of friends, predicts how lonely they feel. Functional friendships, such as those resulting in invitations to parties, may affect the quality of life more deeply.
+There are many anecdotal reports, but few systematic studies, of aggression and violence in individuals with ASD. The limited data suggest that, in children with intellectual disability, autism is associated with aggression, destruction of property, and meltdowns.
+
+About a third to a half of individuals with autism do not develop enough natural speech to meet their daily communication needs. Differences in communication may be present from the first year of life, and may include delayed onset of babbling, unusual gestures, diminished responsiveness, and vocal patterns that are not synchronized with the caregiver. In the second and third years, children with autism have less frequent and less diverse babbling, consonants, words, and word combinations; their gestures are less often integrated with words. Children with autism are less likely to make requests or share experiences, and are more likely to simply repeat others' words (echolalia) or reverse pronouns. Joint attention seems to be necessary for functional speech, and deficits in joint attention seem to distinguish infants with ASD. For example, they may look at a pointing hand instead of the pointed-at object, and they consistently fail to point at objects in order to comment on or share an experience. Children with autism may have difficulty with imaginative play and with developing symbols into language.
+
+In a pair of studies, high-functioning children with autism aged 8–15 performed equally well as, and as adults better than, individually matched controls at basic language tasks involving vocabulary and spelling. Both autistic groups performed worse than controls at complex language tasks such as figurative language, comprehension and inference. As people are often sized up initially from their basic language skills, these studies suggest that people speaking to autistic individuals are more likely to overestimate what their audience comprehends.
+
+Autistic individuals can display many forms of repetitive or restricted behavior, which the Repetitive Behavior Scale-Revised (RBS-R) categorizes as follows.
+
+
+No single repetitive or self-injurious behavior seems to be specific to autism, but autism appears to have an elevated pattern of occurrence and severity of these behaviors.
+
+Autistic individuals may have symptoms that are independent of the diagnosis, but that can affect the individual or the family.
+An estimated 0.5% to 10% of individuals with ASD show unusual abilities, ranging from splinter skills such as the memorization of trivia to the extraordinarily rare talents of prodigious autistic savants. Many individuals with ASD show superior skills in perception and attention, relative to the general population. Sensory abnormalities are found in over 90% of those with autism, and are considered core features by some, although there is no good evidence that sensory symptoms differentiate autism from other developmental disorders. Differences are greater for under-responsivity (for example, walking into things) than for over-responsivity (for example, distress from loud noises) or for sensation seeking (for example, rhythmic movements). An estimated 60–80% of autistic people have motor signs that include poor muscle tone, poor motor planning, and toe walking; deficits in motor coordination are pervasive across ASD and are greater in autism proper. Unusual eating behavior occurs in about three-quarters of children with ASD, to the extent that it was formerly a diagnostic indicator. Selectivity is the most common problem, although eating rituals and food refusal also occur.
+
+There is tentative evidence that autism occurs more frequently in people with gender dysphoria.
+
+Gastrointestinal problems are one of the most commonly associated medical disorders in people with autism. These are linked to greater social impairment, irritability, behavior and sleep problems, language impairments and mood changes.
+
+Parents of children with ASD have higher levels of stress. Siblings of children with ASD report greater admiration of and less conflict with the affected sibling than siblings of unaffected children and were similar to siblings of children with Down syndrome in these aspects of the sibling relationship. However, they reported lower levels of closeness and intimacy than siblings of children with Down syndrome; siblings of individuals with ASD have greater risk of negative well-being and poorer sibling relationships as adults.
+
+It has long been presumed that there is a common cause at the genetic, cognitive, and neural levels for autism's characteristic triad of symptoms. However, there is increasing suspicion that autism is instead a complex disorder whose core aspects have distinct causes that often co-occur.
+Autism has a strong genetic basis, although the genetics of autism are complex and it is unclear whether ASD is explained more by rare mutations with major effects, or by rare multigene interactions of common genetic variants. Complexity arises due to interactions among multiple genes, the environment, and epigenetic factors which do not change DNA sequencing but are heritable and influence gene expression. Many genes have been associated with autism through sequencing the genomes of affected individuals and their parents. Studies of twins suggest that heritability is 0.7 for autism and as high as 0.9 for ASD, and siblings of those with autism are about 25 times more likely to be autistic than the general population. However, most of the mutations that increase autism risk have not been identified. Typically, autism cannot be traced to a Mendelian (single-gene) mutation or to a single chromosome abnormality, and none of the genetic syndromes associated with ASDs have been shown to selectively cause ASD. Numerous candidate genes have been located, with only small effects attributable to any particular gene. Most loci individually explain less than 1% of cases of autism. The large number of autistic individuals with unaffected family members may result from spontaneous structural variation—such as deletions, duplications or inversions in genetic material during meiosis. Hence, a substantial fraction of autism cases may be traceable to genetic causes that are highly heritable but not inherited: that is, the mutation that causes the autism is not present in the parental genome. Autism may be underdiagnosed in women and girls due to an assumption that it is primarily a male condition, but genetic phenomena such as imprinting and X linkage have the ability to raise the frequency and severity of conditions in males, and theories have been put forward for a genetic reason why males are diagnosed more often, such as the imprinted brain theory and the extreme male brain theory.
+
+Maternal nutrition and inflammation during preconception and pregnancy influences fetal neurodevelopment. Intrauterine growth restriction is associated with ASD, in both term and preterm infants. Maternal inflammatory and autoimmune diseases may damage fetal tissues, aggravating a genetic problem or damaging the nervous system.
+
+Exposure to air pollution during pregnancy, especially heavy metals and particulates, may increase the risk of autism. Environmental factors that have been claimed without evidence to contribute to or exacerbate autism include certain foods, infectious diseases, solvents, PCBs, phthalates and phenols used in plastic products, pesticides, brominated flame retardants, alcohol, smoking, illicit drugs, vaccines, and prenatal stress. Some, such as the MMR vaccine, have been completely disproven.
+
+Parents may first become aware of autistic symptoms in their child around the time of a routine vaccination. This has led to unsupported theories blaming vaccine "overload", a vaccine preservative, or the MMR vaccine for causing autism. The latter theory was supported by a litigation-funded study that has since been shown to have been "an elaborate fraud". Although these theories lack convincing scientific evidence and are biologically implausible, parental concern about a potential vaccine link with autism has led to lower rates of childhood immunizations, outbreaks of previously controlled childhood diseases in some countries, and the preventable deaths of several children.
+
+Autism's symptoms result from maturation-related changes in various systems of the brain. How autism occurs is not well understood. Its mechanism can be divided into two areas: the pathophysiology of brain structures and processes associated with autism, and the neuropsychological linkages between brain structures and behaviors. The behaviors appear to have multiple pathophysiologies.
+
+There is evidence that gut–brain axis abnormalities may be involved. A 2015 review proposed that immune dysregulation, gastrointestinal inflammation, malfunction of the autonomic nervous system, gut flora alterations, and food metabolites may cause brain neuroinflammation and dysfunction. A 2016 review concludes that enteric nervous system abnormalities might play a role in neurological disorders such as autism. Neural connections and the immune system are a pathway that may allow diseases originated in the intestine to spread to the brain.
+
+Several lines of evidence point to synaptic dysfunction as a cause of autism. Some rare mutations may lead to autism by disrupting some synaptic pathways, such as those involved with cell adhesion. Gene replacement studies in mice suggest that autistic symptoms are closely related to later developmental steps that depend on activity in synapses and on activity-dependent changes. All known teratogens (agents that cause birth defects) related to the risk of autism appear to act during the first eight weeks from conception, and though this does not exclude the possibility that autism can be initiated or affected later, there is strong evidence that autism arises very early in development.
+
+Diagnosis is based on behavior, not cause or mechanism. Under the DSM-5, autism is characterized by persistent deficits in social communication and interaction across multiple contexts, as well as restricted, repetitive patterns of behavior, interests, or activities. These deficits are present in early childhood, typically before age three, and lead to clinically significant functional impairment. Sample symptoms include lack of social or emotional reciprocity, stereotyped and repetitive use of language or idiosyncratic language, and persistent preoccupation with unusual objects. The disturbance must not be better accounted for by Rett syndrome, intellectual disability or global developmental delay. ICD-10 uses essentially the same definition.
+
+Several diagnostic instruments are available. Two are commonly used in autism research: the Autism Diagnostic Interview-Revised (ADI-R) is a semistructured parent interview, and the Autism Diagnostic Observation Schedule (ADOS) uses observation and interaction with the child. The Childhood Autism Rating Scale (CARS) is used widely in clinical environments to assess severity of autism based on observation of children. The Diagnostic interview for social and communication disorders (DISCO) may also be used.
+
+A pediatrician commonly performs a preliminary investigation by taking developmental history and physically examining the child. If warranted, diagnosis and evaluations are conducted with help from ASD specialists, observing and assessing cognitive, communication, family, and other factors using standardized tools, and taking into account any associated medical conditions. A pediatric neuropsychologist is often asked to assess behavior and cognitive skills, both to aid diagnosis and to help recommend educational interventions. A differential diagnosis for ASD at this stage might also consider intellectual disability, hearing impairment, and a specific language impairment such as Landau–Kleffner syndrome. The presence of autism can make it harder to diagnose coexisting psychiatric disorders such as depression.
+
+Clinical genetics evaluations are often done once ASD is diagnosed, particularly when other symptoms already suggest a genetic cause. Although genetic technology allows clinical geneticists to link an estimated 40% of cases to genetic causes, consensus guidelines in the US and UK are limited to high-resolution chromosome and fragile X testing. A genotype-first model of diagnosis has been proposed, which would routinely assess the genome's copy number variations. As new genetic tests are developed several ethical, legal, and social issues will emerge. Commercial availability of tests may precede adequate understanding of how to use test results, given the complexity of autism's genetics. Metabolic and neuroimaging tests are sometimes helpful, but are not routine.
+
+ASD can sometimes be diagnosed by age 14 months, although diagnosis becomes increasingly stable over the first three years of life: for example, a one-year-old who meets diagnostic criteria for ASD is less likely than a three-year-old to continue to do so a few years later. In the UK the National Autism Plan for Children recommends at most 30 weeks from first concern to completed diagnosis and assessment, though few cases are handled that quickly in practice. Although the symptoms of autism and ASD begin early in childhood, they are sometimes missed; years later, adults may seek diagnoses to help them or their friends and family understand themselves, to help their employers make adjustments, or in some locations to claim disability living allowances or other benefits. Girls are often diagnosed later than boys.
+
+Underdiagnosis and overdiagnosis are problems in marginal cases, and much of the recent increase in the number of reported ASD cases is likely due to changes in diagnostic practices. The increasing popularity of drug treatment options and the expansion of benefits has given providers incentives to diagnose ASD, resulting in some overdiagnosis of children with uncertain symptoms. Conversely, the cost of screening and diagnosis and the challenge of obtaining payment can inhibit or delay diagnosis. It is particularly hard to diagnose autism among the visually impaired, partly because some of its diagnostic criteria depend on vision, and partly because autistic symptoms overlap with those of common blindness syndromes or blindisms.
+
+Autism is one of the five pervasive developmental disorders (PDD), which are characterized by widespread abnormalities of social interactions and communication, and severely restricted interests and highly repetitive behavior. These symptoms do not imply sickness, fragility, or emotional disturbance.
+
+Of the five PDD forms, Asperger syndrome is closest to autism in signs and likely causes; Rett syndrome and childhood disintegrative disorder share several signs with autism, but may have unrelated causes; PDD not otherwise specified (PDD-NOS; also called "atypical autism") is diagnosed when the criteria are not met for a more specific disorder. Unlike with autism, people with Asperger syndrome have no substantial delay in language development. The terminology of autism can be bewildering, with autism, Asperger syndrome and PDD-NOS often called the "autism spectrum disorders" (ASD) or sometimes the "autistic disorders", whereas autism itself is often called "autistic disorder", "childhood autism", or "infantile autism". In this article, "autism" refers to the classic autistic disorder; in clinical practice, though, "autism", "ASD", and "PDD" are often used interchangeably. ASD, in turn, is a subset of the broader autism phenotype, which describes individuals who may not have ASD but do have autistic-like traits, such as avoiding eye contact.
+
+Autism can also be divided into syndromal and non-syndromal autism; the syndromal autism is associated with severe or profound intellectual disability or a congenital syndrome with physical symptoms, such as tuberous sclerosis. Although individuals with Asperger syndrome tend to perform better cognitively than those with autism, the extent of the overlap between Asperger syndrome, HFA, and non-syndromal autism is unclear.
+
+Some studies have reported diagnoses of autism in children due to a loss of language or social skills, as opposed to a failure to make progress, typically from 15 to 30 months of age. The validity of this distinction remains controversial; it is possible that regressive autism is a specific subtype, or that there is a continuum of behaviors between autism with and without regression.
+
+Research into causes has been hampered by the inability to identify biologically meaningful subgroups within the autistic population and by the traditional boundaries between the disciplines of psychiatry, psychology, neurology and pediatrics. Newer technologies such as fMRI and diffusion tensor imaging can help identify biologically relevant phenotypes (observable traits) that can be viewed on brain scans, to help further neurogenetic studies of autism; one example is lowered activity in the fusiform face area of the brain, which is associated with impaired perception of people versus objects. It has been proposed to classify autism using genetics as well as behavior.
+
+Autism has long been thought to cover a wide spectrum, ranging from individuals with severe impairments—who may be silent, developmentally disabled, and prone to frequent repetitive behavior such as hand flapping and rocking—to high functioning individuals who may have active but distinctly odd social approaches, narrowly focused interests, and verbose, pedantic communication. Because the behavior spectrum is continuous, boundaries between diagnostic categories are necessarily somewhat arbitrary. Sometimes the syndrome is divided into low-, medium- or high-functioning autism (LFA, MFA, and HFA), based on IQ thresholds. Some people have called for an end to the terms "high-functioning" and "low-functioning" due to lack of nuance and the potential for a person's needs or abilities to be overlooked.
+
+About half of parents of children with ASD notice their child's unusual behaviors by age 18 months, and about four-fifths notice by age 24 months. According to an article, failure to meet any of the following milestones "is an absolute indication to proceed with further evaluations. Delay in referral for such testing may delay early diagnosis and treatment and affect the long-term outcome".
+
+The United States Preventive Services Task Force in 2016 found it was unclear if screening was beneficial or harmful among children in whom there is no concerns. The Japanese practice is to screen all children for ASD at 18 and 24 months, using autism-specific formal screening tests. In contrast, in the UK, children whose families or doctors recognize possible signs of autism are screened. It is not known which approach is more effective. Screening tools include the Modified Checklist for Autism in Toddlers (M-CHAT), the Early Screening of Autistic Traits Questionnaire, and the First Year Inventory; initial data on M-CHAT and its predecessor, the Checklist for Autism in Toddlers (CHAT), on children aged 18–30 months suggests that it is best used in a clinical setting and that it has low sensitivity (many false-negatives) but good specificity (few false-positives). It may be more accurate to precede these tests with a broadband screener that does not distinguish ASD from other developmental disorders. Screening tools designed for one culture's norms for behaviors like eye contact may be inappropriate for a different culture. Although genetic screening for autism is generally still impractical, it can be considered in some cases, such as children with neurological symptoms and dysmorphic features.
+
+While infection with rubella during pregnancy causes fewer than 1% of cases of autism, vaccination against rubella can prevent many of those cases.
+
+The main goals when treating children with autism are to lessen associated deficits and family distress, and to increase quality of life and functional independence. In general, higher IQs are correlated with greater responsiveness to treatment and improved treatment outcomes. No single treatment is best and treatment is typically tailored to the child's needs. Families and the educational system are the main resources for treatment. Services should be carried out by behavior analysts, special education teachers, speech pathologists, and licensed psychologists. Studies of interventions have methodological problems that prevent definitive conclusions about efficacy. However, the development of evidence-based interventions has advanced in recent years. Although many psychosocial interventions have some positive evidence, suggesting that some form of treatment is preferable to no treatment, the methodological quality of systematic reviews of these studies has generally been poor, their clinical results are mostly tentative, and there is little evidence for the relative effectiveness of treatment options. Intensive, sustained special education programs and behavior therapy early in life can help children acquire self-care, communication, and job skills, and often improve functioning and decrease symptom severity and maladaptive behaviors; claims that intervention by around age three years is crucial are not substantiated. While medications have not been found to help with core symptoms, they may be used for associated symptoms, such as irritability, inattention, or repetitive behavior patterns.
+
+Educational interventions often used include applied behavior analysis (ABA), developmental models, structured teaching, speech and language therapy, social skills therapy, and occupational therapy. Among these approaches, interventions either treat autistic features comprehensively, or focalize treatment on a specific area of deficit. The quality of research for early intensive behavioral intervention (EIBI)—a treatment procedure incorporating over thirty hours per week of the structured type of ABA that is carried out with very young children—is currently low, and more vigorous research designs with larger sample sizes are needed. Two theoretical frameworks outlined for early childhood intervention include structured and naturalistic ABA interventions, and developmental social pragmatic models (DSP). One interventional strategy utilizes a parent training model, which teaches parents how to implement various ABA and DSP techniques, allowing for parents to disseminate interventions themselves. Various DSP programs have been developed to explicitly deliver intervention systems through at-home parent implementation. Despite the recent development of parent training models, these interventions have demonstrated effectiveness in numerous studies, being evaluated as a probable efficacious mode of treatment.
+
+Early, intensive ABA therapy has demonstrated effectiveness in enhancing communication and adaptive functioning in preschool children; it is also well-established for improving the intellectual performance of that age group. Similarly, a teacher-implemented intervention that utilizes a more naturalistic form of ABA combined with a developmental social pragmatic approach has been found to be beneficial in improving social-communication skills in young children, although there is less evidence in its treatment of global symptoms. Neuropsychological reports are often poorly communicated to educators, resulting in a gap between what a report recommends and what education is provided. It is not known whether treatment programs for children lead to significant improvements after the children grow up, and the limited research on the effectiveness of adult residential programs shows mixed results. The appropriateness of including children with varying severity of autism spectrum disorders in the general education population is a subject of current debate among educators and researchers.
+
+Medications may be used to treat ASD symptoms that interfere with integrating a child into home or school when behavioral treatment fails. They may also be used for associated health problems, such as ADHD or anxiety. More than half of US children diagnosed with ASD are prescribed psychoactive drugs or anticonvulsants, with the most common drug classes being antidepressants, stimulants, and antipsychotics. The atypical antipsychotic drugs risperidone and aripiprazole are FDA-approved for treating associated aggressive and self-injurious behaviors. However, their side effects must be weighed against their potential benefits, and people with autism may respond atypically. Side effects, for example, may include weight gain, tiredness, drooling, and aggression. SSRI antidepressants, such as fluoxetine and fluvoxamine, have been shown to be effective in reducing repetitive and ritualistic behaviors, while the stimulant medication methylphenidate is beneficial for some children with co-morbid inattentiveness or hyperactivity. There is scant reliable research about the effectiveness or safety of drug treatments for adolescents and adults with ASD. No known medication relieves autism's core symptoms of social and communication impairments. Experiments in mice have reversed or reduced some symptoms related to autism by replacing or modulating gene function, suggesting the possibility of targeting therapies to specific rare mutations known to cause autism.
+
+Although many alternative therapies and interventions are available, few are supported by scientific studies. Treatment approaches have little empirical support in quality-of-life contexts, and many programs focus on success measures that lack predictive validity and real-world relevance. Some alternative treatments may place the child at risk. The preference that children with autism have for unconventional foods can lead to reduction in bone cortical thickness with this being greater in those on casein-free diets, as a consequence of the low intake of calcium and vitamin D; however, suboptimal bone development in ASD has also been associated with lack of exercise and gastrointestinal disorders. In 2005, botched chelation therapy killed a five-year-old child with autism. Chelation is not recommended for people with ASD since the associated risks outweigh any potential benefits. Another alternative medicine practice with no evidence is CEASE therapy, a mixture of homeopathy, supplements, and 'vaccine detoxing'.
+
+Although popularly used as an alternative treatment for people with autism, as of 2018 there is no good evidence to recommend a gluten- and casein-free diet as a standard treatment. A 2018 review concluded that it may be a therapeutic option for specific groups of children with autism, such as those with known food intolerances or allergies, or with food intolerance markers. The authors analyzed the prospective trials conducted to date that studied the efficacy of the gluten- and casein-free diet in children with ASD (4 in total). All of them compared gluten- and casein-free diet versus normal diet with a control group (2 double-blind randomized controlled trials, 1 double-blind crossover trial, 1 single-blind trial). In two of the studies, whose duration was 12 and 24 months, a significant improvement in ASD symptoms (efficacy rate 50%) was identified. In the other two studies, whose duration was 3 months, no significant effect was observed. The authors concluded that a longer duration of the diet may be necessary to achieve the improvement of the ASD symptoms. Other problems documented in the trials carried out include transgressions of the diet, small sample size, the heterogeneity of the participants and the possibility of a placebo effect.
+
+In the subset of people who have gluten sensitivity there is limited evidence that suggests that a gluten-free diet may improve some autistic behaviors.
+
+There is tentative evidence that music therapy may improve social interactions, verbal communication, and non-verbal communication skills. There has been early research looking at hyperbaric treatments in children with autism. Studies on pet therapy have shown positive effects.
+
+There is no known cure. The degree of symptoms can decrease, occasionally to the extent that people lose their diagnosis of ASD; this occurs sometimes after intensive treatment and sometimes not. It is not known how often recovery happens; reported rates in unselected samples have ranged from 3% to 25%. Most children with autism acquire language by age five or younger, though a few have developed communication skills in later years. Many children with autism lack social support, future employment opportunities or self-determination. Although core difficulties tend to persist, symptoms often become less severe with age.
+
+Few high-quality studies address long-term prognosis. Some adults show modest improvement in communication skills, but a few decline; no study has focused on autism after midlife. Acquiring language before age six, having an IQ above 50, and having a marketable skill all predict better outcomes; independent living is unlikely with severe autism.
+
+Many individuals with autism face significant obstacles in transitioning to adulthood. Compared to the general population individuals with autism are more likely to be unemployed and to have never had a job. About half of people in their 20s with autism are not employed.
+
+Most recent reviews tend to estimate a prevalence of 1–2 per 1,000 for autism and close to 6 per 1,000 for ASD as of 2007. A 2016 survey in the United States reported a rate of 25 per 1,000 children for ASD. Globally, autism affects an estimated 24.8 million people , while Asperger syndrome affects a further 37.2 million. In 2012, the NHS estimated that the overall prevalence of autism among adults aged 18 years and over in the UK was 1.1%. Rates of PDD-NOS's has been estimated at 3.7 per 1,000, Asperger syndrome at roughly 0.6 per 1,000, and childhood disintegrative disorder at 0.02 per 1,000. CDC estimates about 1 out of 59 (1.7%) for 2014, an increase from 1 out of every 68 children (1.5%) for 2010.
+
+The number of reported cases of autism increased dramatically in the 1990s and early 2000s. This increase is largely attributable to changes in diagnostic practices, referral patterns, availability of services, age at diagnosis, and public awareness, though unidentified environmental risk factors cannot be ruled out. The available evidence does not rule out the possibility that autism's true prevalence has increased; a real increase would suggest directing more attention and funding toward changing environmental factors instead of continuing to focus on genetics.
+
+Boys are at higher risk for ASD than girls. The sex ratio averages 4.3:1 and is greatly modified by cognitive impairment: it may be close to 2:1 with intellectual disability and more than 5.5:1 without. Several theories about the higher prevalence in males have been investigated, but the cause of the difference is unconfirmed; one theory is that females are underdiagnosed.
+
+Although the evidence does not implicate any single pregnancy-related risk factor as a cause of autism, the risk of autism is associated with advanced age in either parent, and with diabetes, bleeding, and use of psychiatric drugs in the mother during pregnancy. The risk is greater with older fathers than with older mothers; two potential explanations are the known increase in mutation burden in older sperm, and the hypothesis that men marry later if they carry genetic liability and show some signs of autism. Most professionals believe that race, ethnicity, and socioeconomic background do not affect the occurrence of autism.
+
+Several other conditions are common in children with autism. They include:
+
+A few examples of autistic symptoms and treatments were described long before autism was named. The "Table Talk" of Martin Luther, compiled by his notetaker, Mathesius, contains the story of a 12-year-old boy who may have been severely autistic. Luther reportedly thought the boy was a soulless mass of flesh possessed by the devil, and suggested that he be suffocated, although a later critic has cast doubt on the veracity of this report. The earliest well-documented case of autism is that of Hugh Blair of Borgue, as detailed in a 1747 court case in which his brother successfully petitioned to annul Blair's marriage to gain Blair's inheritance. The Wild Boy of Aveyron, a feral child caught in 1798, showed several signs of autism; the medical student Jean Itard treated him with a behavioral program designed to help him form social attachments and to induce speech via imitation.
+
+The New Latin word "autismus" (English translation "autism") was coined by the Swiss psychiatrist Eugen Bleuler in 1910 as he was defining symptoms of schizophrenia. He derived it from the Greek word "autós" (αὐτός, meaning "self"), and used it to mean morbid self-admiration, referring to "autistic withdrawal of the patient to his fantasies, against which any influence from outside becomes an intolerable disturbance". A Soviet child psychiatrist, Grunya Sukhareva, described a similar syndrome that was published in Russian in 1925, and in German in 1926.
+
+The word "autism" first took its modern sense in 1938 when Hans Asperger of the Vienna University Hospital adopted Bleuler's terminology "autistic psychopaths" in a lecture in German about child psychology. Asperger was investigating an ASD now known as Asperger syndrome, though for various reasons it was not widely recognized as a separate diagnosis until 1981. Leo Kanner of the Johns Hopkins Hospital first used "autism" in its modern sense in English when he introduced the label "early infantile autism" in a 1943 report of 11 children with striking behavioral similarities. Almost all the characteristics described in Kanner's first paper on the subject, notably "autistic aloneness" and "insistence on sameness", are still regarded as typical of the autistic spectrum of disorders. It is not known whether Kanner derived the term independently of Asperger.
+
+Donald Triplett was the first person diagnosed with autism. He was diagnosed by Kanner after being first examined in 1938, and was labeled as "case 1". Triplett was noted for his savant abilities, particularly being able to name musical notes played on a piano and to mentally multiply numbers. His father, Oliver, described him as socially withdrawn but interested in number patterns, music notes, letters of the alphabet, and U.S. president pictures. By the age of 2, he had the ability to recite the 23rd Psalm and memorized 25 questions and answers from the Presbyterian catechism. He was also interested in creating musical chords.
+
+Kanner's reuse of "autism" led to decades of confused terminology like "infantile schizophrenia", and child psychiatry's focus on maternal deprivation led to misconceptions of autism as an infant's response to "refrigerator mothers". Starting in the late 1960s autism was established as a separate syndrome.
+
+As late as the mid-1970s there was little evidence of a genetic role in autism; while in 2007 it was believed to be one of the most heritable psychiatric conditions. Although the rise of parent organizations and the destigmatization of childhood ASD have affected how ASD is viewed, parents continue to feel social stigma in situations where their child's autistic behavior is perceived negatively, and many primary care physicians and medical specialists express some beliefs consistent with outdated autism research.
+
+It took until 1980 for the DSM-III to differentiate autism from childhood schizophrenia. In 1987, the DSM-III-R provided a checklist for diagnosing autism. In May 2013, the DSM-5 was released, updating the classification for pervasive developmental disorders. The grouping of disorders, including PDD-NOS, autism, Asperger syndrome, Rett syndrome, and CDD, has been removed and replaced with the general term of Autism Spectrum Disorders. The two categories that exist are impaired social communication and/or interaction, and restricted and/or repetitive behaviors.
+
+The Internet has helped autistic individuals bypass nonverbal cues and emotional sharing that they find difficult to deal with, and has given them a way to form online communities and work remotely. Societal and cultural aspects of autism have developed: some in the community seek a cure, while others believe that autism is simply another way of being.
+
+An autistic culture has emerged, accompanied by the autistic rights and neurodiversity movements. Events include World Autism Awareness Day, Autism Sunday, Autistic Pride Day, Autreat, and others. Organizations dedicated to promoting awareness of autism include Autistic Self Advocacy Network, Aspies For Freedom, Autism National Committee, and Autism Society of America. At the same time, some organizations, including Autism Speaks, have been condemned by disability rights organizations for failing to support autistic people. Social-science scholars study those with autism in hopes to learn more about "autism as a culture, transcultural comparisons... and research on social movements." While most autistic individuals do not have savant skills, many have been successful in their fields.
+
+The autism rights movement is a social movement within the context of disability rights that emphasizes the concept of neurodiversity, viewing the autism spectrum as a result of natural variations in the human brain rather than a disorder to be cured. The autism rights movement advocates for including greater acceptance of autistic behaviors; therapies that focus on coping skills rather than on imitating the behaviors of those without autism, and the recognition of the autistic community as a minority group. Autism rights or neurodiversity advocates believe that the autism spectrum is genetic and should be accepted as a natural expression of the human genome. This perspective is distinct from two other likewise distinct views: the medical perspective, that autism is caused by a genetic defect and should be addressed by targeting the autism gene(s), and fringe theories that autism is caused by environmental factors such as vaccines. A common criticism against autistic activists is that the majority of them are "high-functioning" or have Asperger syndrome and do not represent the views of "low-functioning" autistic people.
+
+About half of autistics are unemployed, and one third of those with graduate degrees may be unemployed. Among autistics who find work, most are employed in sheltered settings working for wages below the national minimum. While employers state hiring concerns about productivity and supervision, experienced employers of autistics give positive reports of above average memory and detail orientation as well as a high regard for rules and procedure in autistic employees. A majority of the economic burden of autism is caused by decreased earnings in the job market. Some studies also find decreased earning among parents who care for autistic children.
+
+
+
\ No newline at end of file
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/wmt16/sample.json b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/wmt16/sample.json
new file mode 100644
index 0000000000000000000000000000000000000000..8c0e47b0648a2817d3f08d498f011e98d31f8e46
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/wmt16/sample.json
@@ -0,0 +1,10 @@
+{"translation": {"en": "Membership of Parliament: see Minutes", "ro": "Componenţa Parlamentului: a se vedea procesul-verbal"}}
+{"translation": {"en": "Approval of Minutes of previous sitting: see Minutes", "ro": "Aprobarea procesului-verbal al şedinţei precedente: a se vedea procesul-verbal"}}
+{"translation": {"en": "Membership of Parliament: see Minutes", "ro": "Componenţa Parlamentului: a se vedea procesul-verbal"}}
+{"translation": {"en": "Verification of credentials: see Minutes", "ro": "Verificarea prerogativelor: a se vedea procesul-verbal"}}
+{"translation": {"en": "Documents received: see Minutes", "ro": "Depunere de documente: a se vedea procesul-verbal"}}
+{"translation": {"en": "Written statements and oral questions (tabling): see Minutes", "ro": "Declaraţii scrise şi întrebări orale (depunere): consultaţi procesul-verbal"}}
+{"translation": {"en": "Petitions: see Minutes", "ro": "Petiţii: a se vedea procesul-verbal"}}
+{"translation": {"en": "Texts of agreements forwarded by the Council: see Minutes", "ro": "Transmiterea de către Consiliu a textelor acordurilor: a se vedea procesul-verbal"}}
+{"translation": {"en": "Action taken on Parliament's resolutions: see Minutes", "ro": "Cursul dat rezoluţiilor Parlamentului: a se vedea procesul-verbal"}}
+{"translation": {"en": "Agenda for next sitting: see Minutes", "ro": "Ordinea de zi a următoarei şedinţe: a se vedea procesul-verbal"}}
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/wmt_en_ro/test.json b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/wmt_en_ro/test.json
new file mode 100644
index 0000000000000000000000000000000000000000..2841b1b6aab9ed5ef54bfa4d60c82e9c1b676a09
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/wmt_en_ro/test.json
@@ -0,0 +1,20 @@
+{ "translation": { "en": "UN Chief Says There Is No Military Solution in Syria Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people. The U.N. chief again urged all parties, including the divided U.N. Security Council, to unite and support inclusive negotiations to find a political solution. Ban told a news conference Wednesday that he plans to meet with foreign ministers of the five permanent council nations - the U.S., Russia, China, Britain and France - on the sidelines of the General Assembly's ministerial session later this month to discuss Syria.", "ro": "Șeful ONU declară că nu există soluții militare în Siria Secretarul General Ban Ki-moon afirmă că răspunsul său la suportul militar al Rusiei pentru Siria este că „nu există o soluție militară” la conflictul care durează de aproape cinci ani iar mai multe arme nu ar face decât să agraveze violența și suferința a milioane de oameni. Șeful ONU a solicitat din nou tuturor părților, inclusiv Consiliului de securitate ONU divizat să se unifice și să susțină negocierile pentru a găsi o soluție politică. Ban a declarat miercuri în cadrul unei conferințe că intenționează să se întâlnească luna aceasta cu miniștrii de externe din cinci țări permanent prezente în consiliu - SUA, Rusia, China, Anglia și Franța - pe marginea sesiunii ministeriale a Adunării Generale pentru a discuta despre Siria." } }
+{ "translation": { "en": "He expressed regret that divisions in the council and among the Syrian people and regional powers \"made this situation unsolvable.\" Ban urged the five permanent members to show the solidarity and unity they did in achieving an Iran nuclear deal in addressing the Syria crisis. 8 Poll Numbers That Show Donald Trump Is For Real Some have tried to label him a flip-flopper. Others have dismissed him as a joke. And some are holding out for an implosion. But no matter how some Republicans are trying to drag Donald Trump down from atop the polls, it hasn't worked (yet).", "ro": "Ban și-a exprimat regretul că divizările în consiliu și între poporul sirian și puterile regionale „au făcut această situație de nerezolvat”. Ban le-a cerut celor cinci membri permanenți să dea dovadă de solidaritatea și unitatea arătate atunci când au reușit să încheie un acord referitor la armele nucleare ale Iranului, abordând astfel criza din Siria. 8 cifre din sondaje care arată că Donald Trump are șanse reale Unii au încercat să îl eticheteze ca politician „flip-flop”. Alții l-au numit o glumă. Iar alții așteaptă implozia. Însă indiferent de modul în care unii republicani încearcă să îl dărâme pe Donald Trump din vârful sondajelor, nu a funcționat (încă)." } }
+{ "translation": { "en": "Ten of the last 11 national polls have shown Donald Trump's lead at double digits, and some are starting to ask seriously what it means for the real estate mogul's nomination chances. Of course, it's still early in the election cycle. None of this is to say that Trump is likely to win the Republican nomination. Pundits point out that at this time in 2011, Rick Perry's lead was giving way to a rising Herman Cain, neither of whom won even one state in the nomination process. And there are many reasons he would struggle in a general election. But outside groups like Jeb Bush's Super PAC and the economic conservative group Club for Growth are recognizing Trump's staying power and beginning to unload their dollars to topple him.", "ro": "Zece din ultimele 11 sondaje naționale au arătat că Donald Trump conduce cu un procent din două cifre iar unele voci încep să se întrebe serios ce înseamnă acest lucru pentru șansele de numire ale mogulului imobiliar. Desigur, este încă prematur. Nimic din toate acestea nu spune că Trump va câștiga cursa pentru nominalizarea republicanilor. Pundits arată că, în aceeași perioadă a anului 2011, avansul lui Rick Perry îi făcea loc lui Herman Cain în sondaje, dar niciunul dintre ei nu a câștigat în vreun stat în cursa de nominalizare. Iar motivele pentru care s-ar lupta din greu la alegerile generale sunt numeroase. Însă grupurile din exterior precum Super PAC al lui Jeb Bush și grupul conservator economic Club for Growth admit puterea lui Trump și încep să îl susțină cu bani." } }
+{ "translation": { "en": "Here are some recent poll numbers that suggest that the real estate mogul isn't just a passing phase: Trump's favorability ratings have turned 180 degrees. Right before Donald Trump announced his candidacy in mid-June, a Monmouth University poll showed only two in 10 Republicans had a positive view of the real estate mogul. By mid-July, it was 40 percent. In early August, it was 52 percent. Now, six in 10 Republicans have a favorable view of Donald Trump. Roughly three in 10 say they have a negative view. And these numbers hold up in early states. A Quinnipiac poll in Iowa last week found that 60 percent of Republicans there had a favorable view of Trump.", "ro": "În continuare vă prezentăm câteva cifre din sondaje recente care sugerează că mogulul imobiliar nu este doar ceva trecător: Cifrele care indică susținerea față de Trump s-au întors la 180 grade. Chiar înainte ca Donald Trump să își anunțe candidatura, la mijlocul lui iunie, un sondaj realizat de Universitatea din Monmouth arăta că doar doi din 10 republicani aveau o părere pozitivă despre mogulul imobiliar. Până la mijlocul lui iulie, procentul a urcat la 40%. La începutul lui august, era 52%. În prezent, șase din 10 republicani au o părere favorabilă despre Donald Trump. Aproximativ trei din 10 declară că au o părere negativă. Aceste cifre se mențin. Un sondaj realizat săptămâna trecută de Quinnipiac în Iowa a concluzionat că 60% dintre republicanii din regiune au o părere favorabilă despre Trump." } }
+{ "translation": { "en": "Two-thirds of GOP voters would be happy with Trump as the nominee. In a CNN/ORC poll last week, 67 percent of Republicans said they would be either \"enthusiastic\" or \"satisfied\" if Trump were the nominee. Only two in 10 say they would be \"upset\" if he were the nominee. Only Ben Carson generates roughly the same level of enthusiasm as Trump (43 percent say they would be \"enthusiastic\" vs. 40 percent who say the same of Trump). The next closest in enthusiasm? Marco Rubio with only 21 percent.", "ro": "Două treimi dintre alegătorii GOP ar fi fericiți dacă Trump ar câștiga cursa pentru nominalizare. Într-un sondaj realizat săptămâna trecută de CNN/ORC, 67% dintre republicani au declarat că ar fi „entuziasmați” sau „mulțumiți” dacă Trump ar câștiga cursa pentru nominalizare. Doar doi din 10 declară că ar fi „supărați” dacă Trump ar câștiga cursa pentru nominalizare. Doar Ben Carson generează aproximativ același nivel de entuziasm ca Trump (43% declară că ar fi „entuziasmați” față de 40% care declară același lucru despre Trump). Cel mai aproape în ceea ce privește entuziasmul? Marco Rubio, cu doar 21%." } }
+{ "translation": { "en": "On the flip side, 47 percent of Republican voters say they would be \"dissatisfied\" or \"upset\" if establishment favorite Jeb Bush becomes the nominee. A majority of Republicans don't see Trump's temperament as a problem. While Donald Trump has been widely criticized for his bombast and insults, 52 percent of leaned Republican voters nationwide think that the real estate mogul has the right temperament to be president, according to Monday's ABC News/Washington Post poll. The same number holds in the first-in-the-nation caucus state of Iowa, where the same 52 percent of Republicans think he has the personality to be commander in chief, according to Quinnipiac last week.", "ro": "De partea cealaltă, 47% dintre alegătorii republicani afirmă că ar fi „nemulțumiți” sau „supărați” dacă favoritul Jeb Bush câștigă cursa pentru nominalizare. Majoritatea republicanilor nu consideră temperamentul lui Trump o problemă. Deși Donald Trump a fost puternic criticat pentru insultele aduse și stilul său bombastic, 52% dintre alegătorii republicani la nivel național consideră că mogulul imobiliar are temperamentul potrivit pentru a fi președinte, conform sondajului realizat luni de ABC News/Washington Post. Regăsim aceleași cifre în statul Iowa, unde tot 52% dintre republicani cred că Trump are personalitatea potrivită pentru a fi conducător, conform sondajului realizat săptămâna trecută de Quinnipiac." } }
+{ "translation": { "en": "Still, 44 percent think he doesn't have the personality to serve effectively, and almost six in 10 independents say his temperament does not belong in the White House, according to ABC/Post. Republican voters are getting used to the idea. When they put on their pundit hats, Republican voters think Trump is for real. When asked who is most likely to win the GOP nomination, four in 10 said Trump was the best bet, according to a CNN/ORC poll out last week. That's a change from when four in 10 placed their money on Jeb Bush in late July. Full disclosure: GOP voters haven't had the clearest crystal ball in the past.", "ro": "Totuși, 44% sunt de părere că nu are personalitatea necesară pentru a acționa eficient și aproape șase din 10 independenți afirmă că temperamentul său nu are ce căuta la Casa Albă, conform ABC/Post. Alegătorii republicani se obișnuiesc cu ideea. Atunci când iau atitudinea de intelectuali, alegătorii republicani consideră că Trump este autentic. Conform unui sondaj realizat săptămâna trecută de CNN/ORC, la întrebarea cine are cele mai multe șanse să câștige cursa pentru nominalizare GOP, patru din 10 au declarat că Trump. Situația s-a schimbat față de finalul lui iulie, când patru din 10 ar fi pariat pe Jeb Bush. Informare completă: în trecut, alegătorii GOP nu au citit foarte bine viitorul." } }
+{ "translation": { "en": "At this time last cycle, four in 10 Republicans picked Rick Perry to win the nomination, vs. only 28 percent for eventual nominee Mitt Romney. Still, it shows that a plurality of GOP voters see Trump's campaign as plausible. Even if Republicans rallied around another candidate, Trump still beats almost everyone. Some pundits point out that the splintered field is likely contributing to Trump's lead, while anti-Trump support is be spread diffusely among more than a dozen other candidates. But a Monmouth University poll in early September shows that, in a hypothetical head-to-head matchup between Trump and most other Republican candidates, Trump almost always garners majority support.", "ro": "În aceeași perioadă a ultimelor alegeri, patru din 10 republicani l-au ales pe Rick Perry în cursa pentru nominalizare, față de doar 28% pentru Mitt Romney. Însă, aceste cifre arată că majoritatea alegătorilor GOP consideră plauzibilă campania lui Trump. Chiar dacă republicanii sau repliat spre un alt candidat. Trump încă se află în fruntea tuturor. Unele voci spun că situația divizată va contribui probabil la victoria lui Trump, în timp ce susținerea contra lui Trump se va împărți la mai mult de doisprezece candidați. Însă un sondaj derulat la începutul lui septembrie de Universitatea din Monmouth arată că, în situația ipotetică a unei colaborări între Trump și majoritatea celorlalți candidați republicani, aproape întotdeauna Trump va beneficia de susținerea majoritară." } }
+{ "translation": { "en": "He leads Carly Fiorina by 13 points, Marco Rubio by 14 points, Walker by 15 points, Jeb Bush by 19 points, and, finally, Rand Paul, John Kasich and Chris Christie by 33 points each. He's in a dead heat with Ted Cruz. The only candidate who beats him? Ben Carson would lead the businessman by a wide 19 points in a hypothetical head-to-head. A bare majority of Donald Trump's supporters say they've made up their minds. A new CBS/NYT poll out on Tuesday shows that just more than half of voters who support Trump say they have locked in their votes. Obviously, a lot can happen to change that, and no one can really say they would never change their mind.", "ro": "Trump se află la distanță de 13 puncte de Carly Fiorina, la 14 puncte de Marco Rubio, la 15 puncte de Walker, la 19 puncte de Jeb Bush și, în cele din urmă, la câte 33 de puncte față de Rand Paul, John Kasich și Chris Christie. Este aproape la egalitate cu Ted Cruz. Singurul candidat care îl învinge? Ben Carson l-ar învinge pe omul de afaceri cu 19 puncte într-o confruntare ipotetică de unu la unu. Majoritatea susținătorilor lui Donald Trump declară că s-au decis. Un nou sondaj realizat marți de CBS/NYT arată că peste jumătate dintre alegătorii care îl susțin pe Trump declară că nu își schimbă opțiunea de vot. Evident, se pot întâmpla multe în acest sens și nimeni nu poate spune că aceștia nu se vor răzgândi niciodată." } }
+{ "translation": { "en": "46 percent said they are leaving the door open to switching candidates. Still, Trump's strongest competition at the moment is from fellow outsider neurosurgeon Ben Carson, but voters who say they have made up their minds are twice as likely to go for Trump. Six in 10 Republicans say they agree with Trump on immigration. Even since Donald Trump called immigrants from Mexico \"rapists\" in his campaign announcement speech two months ago, immigration has been front and center in the 2016 conversation. Some are worried that Trump's bombast will drive crucial Hispanic voters away from the Republican Party and damage rebranding efforts.", "ro": "46% afirmă că lasă portița deschisă posibilității de a-și schimba opțiunea. Cu toate acestea, cel mai important adversar al lui Trump este în prezent neurochirurgul Ben Carson, însă este de două ori mai probabil ca alegătorii care declară că s-au decis să voteze cu Trump. Șase din 10 republicani afirmă că sunt de acord cu Trump în problema imigrării. De când Donald Trump i-a numit pe imigranții din Mexic „violatori” în discursul de deschidere a campaniei sale, în urmă cu două luni, imigrarea a fost subiectul central în campania pentru 2016. Unii sunt îngrijorați că stilul bombastic al lui Trump va duce la o scindare între alegătorii hispanici importanți și Partidul Republican și va prejudicia eforturile de rebranding." } }
+{ "translation": { "en": "But according to Monday's new ABC/Post poll, six in 10 Republicans say they agree with Trump on immigration issues. So as long as immigration remains in the spotlight, it seems Donald Trump will remain too. Frustration with government is climbing to new highs. Donald Trump and Ben Carson now account for roughly half of the support from Republican voters, largely due to their outsider status. Six in 10 Republicans in Monday's new ABC/Post poll say they want a political outsider over someone with government experience. And they are angry at Washington, too.", "ro": "Însă, conform sondajului realizat luni de ABC/Post, șase din 10 republicani afirmă că sunt de acord cu Trump în problema imigrării. Așa că, se pare că atâta timp cât problema imigrării rămâne în lumina reflectoarelor, la fel va rămâne și Doland Trump. Frustrarea față de autorități atinge noi culmi. Donald Trump și Ben Carson sunt acum susținuți de aproape jumătate dintre alegătorii republicani, în mare parte datorită statutului lor de outsideri. Conform sondajului realizat luni de ABC/Post, șase din 10 republicani afirmă că preferă un outsider politic în detrimentul cuiva cu experiență în guvernare. Oamenii sunt de asemenea supărați pe autoritățile de la Washington." } }
+{ "translation": { "en": "A Des Moines Register/Bloomberg poll in Iowa from two weeks ago shows that three in four Iowa Republicans are frustrated with Republicans in Congress, with 54 percent \"unsatisfied\" and 21 percent \"mad as hell.\" Jeremy Corbyn to make debut at Prime Minister's Questions Since his election, Mr Corbyn's debut at PMQs has been keenly awaited New Labour leader Jeremy Corbyn is to make his debut at Prime Minister's Questions later, taking on David Cameron for the first time.", "ro": "Un sondaj derulat în urmă cu două săptămâni în Iowa de către Des Moines Register/Bloomberg arată că trei din patru republicani din Iowa sunt frustrați de prestația republicanilor din COngres, 54% declarându-se „nemulțumiți” iar 21% „nervoși la culme”. Jeremy Corbyn își face debutul la Prime Minister's Questions Încă de la alegerea sa, debutul domnului Corbyn la PMQs a fost îndelung așteptat Noul lider al Partidului Laburist, Jeremy Corbyn, își va face mai târziu debutul la Prime Minister's Questions, confruntându-se pentru prima dată cu David Cameron." } }
+{ "translation": { "en": "Mr Corbyn will rise to ask the first of his six allotted questions shortly after midday, with his performance likely to be closely scrutinised by the media and Labour MPs. He has called for \"less theatre and more facts\" at the weekly showpiece. He has also said he could skip some sessions, leaving them to colleagues. The encounter will be the first parliamentary test of Mr Corbyn's leadership, coming after his appointment of a shadow cabinet and his speech to the TUC annual congress on Tuesday.", "ro": "Dl Corbyn va adresa primele dintre cele șase întrebări la care are dreptul la scurt timp după prânz; prestația sa va fi probabil analizată îndeaproape de mass-media și parlamentarii laburiști. În cadrul aparițiilor săptămânale, el a cerut „mai puțin teatru și mai multe fapte”. A declarat de asemenea că poate renunța la câteva participări și că le cedează colegilor săi. Confruntarea va fi primul test parlamentar al Dl Corbyn în poziție de lider, venind după ce a numit un „cabinet fantomă” și după discursul pe care l-a ținut marți la congresul anual TUC." } }
+{ "translation": { "en": "Meanwhile, the Labour leader's decision to stand in silence during the singing of the national anthem at a service on Tuesday to mark the 75th anniversary of the Battle of Britain has attracted criticism from a number of Tory MPs and is the focus of several front page stories in the newspapers. Mr Corbyn's decision not to sing the national anthem has attracted attention A spokesman for Mr Corbyn said he had \"stood in respectful silence\" and did recognise the \"heroism of the Royal Air Force in the Battle of Britain.\"", "ro": "Între timp, decizia liderului Partidului laburist de a păstra tăcerea la rostirea imnului național în cadrul unei slujbe ținute marți cu ocazia aniversării a 75 de ani de la Bătălia Angliei a atras critici din partea unor parlamentari conservatori și a ținut prima pagină a ziarelor. Decizia domnului Corbyn de a nu cânta imnul național a atras atenția Un purtător de cuvânt al Dl Corbyn a declarat că acesta „a păstrat tăcerea în mod respectuos” și a recunoscut „eroismul Forțelor aeriene britanice în Bătălia Angliei.”" } }
+{ "translation": { "en": "But a member of Mr Corbyn's shadow cabinet, Owen Smith, told BBC Two's Newsnight programme he would have advised the Labour leader to sing the national anthem \"irrespective\" of his belief that the monarchy should be abolished. Nearly a dozen shadow ministers have refused to serve in Mr Corbyn's top team, citing differences over the economy, defence and foreign affairs, while less than a sixth of the parliamentary party originally backed him as leader. BBC political correspondent Robin Brant says policy differences are also \"stacking up\" within Labour following Mr Corbyn's appointment over its position on the European Union and the government's cap on benefits.", "ro": "Însă un membru al cabinetului fantomă al Dl Corbyn, Owen Smith, a declarat pentru emisiunea Two's Newsnight transmisă de BBC că i-ar fi recomandat liderului laburist să cânte imnul național „indiferent” de credința sa că monarhia ar trebui abolită. În jur de doisprezece miniștri din cabinetul fantomă au refuzat să facă parte din echipa de frunte a Dl Corbyn, argumentând prin diferențe de opinie legate de economie, apărare și externe, în timp ce mai puțin de o șesime din partidul parlamentar l-a susținut ca lider. Corespondentul politic al BBC, Robin Brant, declară că diferențele de politică „se cumulează” în Partidul Laburist după numirea domnului Corbyn referitor la poziția sa față de Uniunea Europeană și limita de beneficii." } }
+{ "translation": { "en": "Mr Corbyn told the TUC conference Labour was putting forward amendments to remove the whole idea of a cap altogether. Hours later Mr Smith, the shadow work and pensions secretary, said the party was \"very clear\" that it was only opposing government plans to reduce the level of cap from £26,000 to £23,000. Mr Corbyn will be the fifth Labour leader that David Cameron has faced across the despatch box over the past decade since he became Tory leader. The Labour leader, who has promised a different approach to politics, says he has \"crowd sourced\" ideas for questions to ask Mr Cameron and has been given more than 30,000 suggestions.", "ro": "Dl Corbyn a declarat la conferința TUC că Partidul Laburist va aduce modificări prin care se va elimina integral ideea limitării. Câteva ore mai târziu, Dl Smith, Ministrul Muncii și Pensiilor, a declarat că partidul „este foarte clar” în opoziția exclusivă față de planurile guvernului de a reduce nivelul „cap” de la 26.000 lire la 23.000 lire. Dl Corbyn va fi al cincilea lider laburist cu care se confruntă David Cameron la tribună în ultimul deceniu, de când a preluat conducerea Partidului Conservator. Liderul laburist, care a promis o abordare diferită a politicii, spune că are idei „din surse externe” pentru întrebări pe care să i le adreseze Domnului Cameron și că a primit peste 30.000 de sugestii." } }
+{ "translation": { "en": "The Islington North MP has said PMQs is too confrontational and that he will refrain from both \"repartee\" and trading barbs, instead vowing to focus on serious issues such as poverty, inequality and the challenges facing young people. Mr Corbyn has said that Angela Eagle, the shadow business secretary, will deputise for him at PMQs when he does not attend - for instance when Mr Cameron is travelling abroad. He has also floated the idea of allowing other colleagues to take the floor on occasion, saying he had approached the Commons Speaker John Bercow to discuss the issue.", "ro": "Parlamentarul Islington North a afirmat că PMQs implică un nivel de confruntare prea înalt și că se va abține de la replici și atacuri, angajându-se să se concentreze în schimb pe probleme serioase precum sărăcia, inegalitatea și provocările cu care se confruntă tinerii. Dl Corbyn a declarat că Angela Eagle, Ministrul de finanțe, îi va ține locul la PMQs atunci când el nu poate participa - de exemplu atunci când Dl Cameron se deplasează în străinătate. A exprimat de asemenea ideea că va permite altor colegi să ia cuvântul ocazional, spunând că l-a abordat pe Președintele Camerei Deputaților, John Bercow, pentru a discuta acest aspect." } }
+{ "translation": { "en": "When he became leader in 2005, Mr Cameron said he wanted to move away from the \"Punch and Judy\" style of politics often associated with PMQs but admitted some years later that he had failed. Since it was first televised in 1990, PMQs has been seen as a key barometer of a leader's judgement, their command of the Commons and their standing among their fellow MPs although critics have argued it has become a caricature and is in need of far-reaching reforms. 'Shot in Joburg': Homeless youth trained as photographers Downtown Johannesburg is a tough place to be homeless.", "ro": "În 2005, când a preluat conducerea, Dl Cameron a declarat că dorește să renunțe la stilul politic „Punch and Judy” asociat adesea cu PMQs însă a recunoscut câțiva ani mai târziu că nu a reușit în demersul său. De la prima transmisie, în 1990, PMQs a fost considerată un barometru cheie al raționamentului unui lider, al modului în care acesta conduce Camera Deputaților și a poziției sale în rândul colegilor parlamentari, deși criticii afirmă a ca devenit o caricatură și că are nevoie de o reformare profundă. „Cadru în Joburg”: Tineri fără adăpost beneficiază de cursuri de fotografie Este dificil să fii un om fără adăpost în Johannesburg." } }
+{ "translation": { "en": "But one group of former street children have found a way to learn a skill and make a living. \"I was shot in Joburg\" is a non-profit studio that teaches homeless youngsters how to take photographs of their neighbourhood and make a profit from it. BBC News went to meet one of the project's first graduates. JD Sports boss says higher wages could hurt expansion JD Sports Executive Chairman Peter Cowgill says a higher minimum wage for UK workers could mean \"more spending power in the pockets of potential consumers.\" But that spending power is unlikely to outweigh the higher labour costs at his firm, he says.", "ro": "Însă un grup de oameni care au trăit pe străzi în copilărie au găsit un mod de a învăța o meserie și de a-și câștiga traiul. „I was shot în Joburg” este un studio non-profit care îi învață pe tinerii fără adăpost să facă fotografii ale zonelor în care trăiesc și să câștige bani din asta. BBC News s-a întâlnit cu unul dintre primii absolvenți ai proiectului. Șeful JD Sports spune că salariile mai mari ar putea dăuna extinderii Președintele JD Sports, Peter Cowgill, declară că o creștere a salariului minim în Marea Britanie ar putea însemna „o putere de cumpărare mai mare în buzunarele potențialilor consumatori.” Este însă puțin probabil ca respectiva putere de cumpărare să depășească costurile mai mari pentru forța de muncă în cadrul firmei, afirmă el." } }
+{ "translation": { "en": "The costs could hit JD Sports' expansion plans, he added, which could mean fewer extra jobs. Thanasi Kokkinakis backed by Tennis Australia president Steve Healy Thanasi Kokkinakis deserves kudos rather than criticism for his behaviour. Thanasi Kokkinakis has been the collateral damage in the recent storm around his friend Nick Kyrgios and deserves kudos rather than criticism for his own behaviour, according to Tennis Australia president Steve Healy.", "ro": "Costurile ar putea avea impact asupra planurilor de extindere ale JD Sports, a adăugat el, ceea ce ar putea însemna mai puține locuri de muncă noi. Thanasi Kokkinakis susținut de președintele Tennis Australia, Steve Healy Thanasi Kokkinakis ar merita să fie lăudat și nu criticat pentru comportamentul său. Thanasi Kokkinakis a fost victimă colaterală în „furtuna” creată în jurul prietenului său, Nick Kyrgios, iar comportamentul său merită mai degrabă cuvinte de laudă și nu critică, în opinia președintelui Tennis Australia, Steve Healy." } }
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/wmt_en_ro/train.json b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/wmt_en_ro/train.json
new file mode 100644
index 0000000000000000000000000000000000000000..269d5156c23e5b1dbe51db6ec39618e48eefa17b
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/wmt_en_ro/train.json
@@ -0,0 +1,11 @@
+{ "translation": { "en": "Corrections to votes and voting intentions: see Minutes Assignment conferred on a Member: see Minutes Membership of committees and delegations: see Minutes Decisions concerning certain documents: see Minutes Forwarding of texts adopted during the sitting: see Minutes Dates for next sittings: see Minutes", "ro": "Corectările voturilor şi intenţiile de vot: a se vedea procesul-verbal Misiune încredinţată unui deputat: consultaţi procesul-verbal Componenţa comisiilor şi a delegaţiilor: a se vedea procesul-verbal Decizii privind anumite documente: a se vedea procesul-verbal Transmiterea textelor adoptate în cursul prezentei şedinţe: a se vedea procesul-verbal Calendarul următoarelor şedinţe: a se vedea procesul-verbal" } }
+{ "translation": { "en": "Membership of Parliament: see Minutes Approval of Minutes of previous sitting: see Minutes Membership of Parliament: see Minutes Verification of credentials: see Minutes Documents received: see Minutes Written statements and oral questions (tabling): see Minutes Petitions: see Minutes Texts of agreements forwarded by the Council: see Minutes Action taken on Parliament's resolutions: see Minutes Agenda for next sitting: see Minutes Closure of sitting (The sitting was closed at 7.45 p.m.)", "ro": "Componenţa Parlamentului: a se vedea procesul-verbal Aprobarea procesului-verbal al şedinţei precedente: a se vedea procesul-verbal Componenţa Parlamentului: a se vedea procesul-verbal Verificarea prerogativelor: a se vedea procesul-verbal Depunere de documente: a se vedea procesul-verbal Declaraţii scrise şi întrebări orale (depunere): consultaţi procesul-verbal Petiţii: a se vedea procesul-verbal Transmiterea de către Consiliu a textelor acordurilor: a se vedea procesul-verbal Cursul dat rezoluţiilor Parlamentului: a se vedea procesul-verbal Ordinea de zi a următoarei şedinţe: a se vedea procesul-verbal Ridicarea şedinţei (Se levanta la sesión a las 19.45 horas)" } }
+{ "translation": { "en": "Election of Vice-Presidents of the European Parliament (deadline for submitting nominations): see Minutes (The sitting was suspended at 12.40 p.m. and resumed at 3.00 p.m.) Election of Quaestors of the European Parliament (deadline for submitting nominations): see Minutes (The sitting was suspended at 3.25 p.m. and resumed at 6.00 p.m.) Agenda for next sitting: see Minutes Closure of sitting (The sitting was closed at 6.15 p.m.) Opening of the sitting (The sitting was opened at 9.35 a.m.) Documents received: see Minutes Approval of Minutes of previous sitting: see Minutes Membership of Parliament: see Minutes", "ro": "Alegerea vicepreşedinţilor Parlamentului European (termenul de depunere a candidaturilor): consultaţi procesul-verbal (Die Sitzung wird um 12.40 Uhr unterbrochen und um 15.00 Uhr wiederaufgenommen). Alegerea chestorilor Parlamentului European (termenul de depunere a candidaturilor): consultaţi procesul-verbal (Die Sitzung wird um 15.25 Uhr unterbrochen und um 18.00 Uhr wiederaufgenommen). Ordinea de zi a următoarei şedinţe: a se vedea procesul-verbal Ridicarea şedinţei (Die Sitzung wird um 18.15 Uhr geschlossen.) Deschiderea şedinţei (Die Sitzung wird um 9.35 Uhr eröffnet.) Depunerea documentelor: a se vedea procesul-verbal Aprobarea procesului-verbal al şedinţei precedente: a se vedea procesul-verbal Componenţa Parlamentului: a se vedea procesul-verbal" } }
+{ "translation": { "en": "Membership of committees (deadline for tabling amendments): see Minutes (The sitting was suspended at 7 p.m. and resumed at 9 p.m.) Agenda for next sitting: see Minutes Closure of sitting (The sitting was suspended at 23.25 p.m.) Documents received: see Minutes Communication of Council common positions: see Minutes (The sitting was suspended at 11.35 a.m. and resumed for voting time at noon) Approval of Minutes of previous sitting: see Minutes Committee of Inquiry into the crisis of the Equitable Life Assurance Society (extension of mandate): see Minutes", "ro": "Componenţa comisiilor (termenul de depunere a amendamentelor): consultaţi procesul-verbal (La seduta, sospesa alle 19.00, è ripresa alle 21.00) Ordinea de zi a următoarei şedinţe: a se vedea procesul-verbal Ridicarea şedinţei (Die Sitzung wird um 23.25 Uhr geschlossen.) Depunerea documentelor: a se vedea procesul-verbal Comunicarea poziţiilor comune ale Parlamentului: a se vedea procesul-verbal (La séance, suspendue à 11h35 dans l'attente de l'Heure des votes, est reprise à midi) Aprobarea procesului-verbal al şedinţei precedente: a se vedea procesul-verbal Comisia de anchetă privind criza societăţii de asigurări \"Equitable Life” (prelungirea mandatului): consultaţi procesul-verbal" } }
+{ "translation": { "en": "Announcement by the President: see Minutes 1. Membership of committees (vote) 2. Amendment of the ACP-EC Partnership Agreement (vote) 4. Certification of train drivers operating locomotives and trains on the railway system in the Community (vote) 6. Law applicable to non-contractual obligations (\"ROME II\") (vote) 8. Seventh and eighth annual reports on arms exports (vote) Corrections to votes and voting intentions: see Minutes Membership of committees and delegations: see Minutes Request for waiver of parliamentary immunity: see Minutes Decisions concerning certain documents: see Minutes", "ro": "Comunicarea Preşedintelui: consultaţi procesul-verbal 1. Componenţa comisiilor (vot) 2. Modificarea Acordului de parteneriat ACP-CE (\"Acordul de la Cotonou”) (vot) 4. Certificarea mecanicilor de locomotivă care conduc locomotive şi trenuri în sistemul feroviar comunitar (vot) 6. Legea aplicabilă obligaţiilor necontractuale (\"Roma II”) (vot) 8. Al şaptelea şi al optulea raport anual privind exportul de armament (vot) Corectările voturilor şi intenţiile de vot: a se vedea procesul-verbal Componenţa comisiilor şi a delegaţiilor: a se vedea procesul-verbal Cerere de ridicare a imunităţii parlamentare: consultaţi procesul-verbal Decizii privind anumite documente: a se vedea procesul-verbal" } }
+{ "translation": { "en": "Written statements for entry", "ro": "Declaraţii scrise înscrise" } }
+{ "translation": { "en": "Written statements for entry in the register (Rule 116): see Minutes Forwarding of texts adopted during the sitting: see Minutes Dates for next sittings: see Minutes Adjournment of the session I declare the session of the European Parliament adjourned. (The sitting was closed at 1 p.m.) Approval of Minutes of previous sitting: see Minutes Membership of Parliament: see Minutes Request for the defence of parliamentary immunity: see Minutes Appointments to committees (proposal by the Conference of Presidents): see Minutes Documents received: see Minutes Texts of agreements forwarded by the Council: see Minutes", "ro": "Declaraţii scrise înscrise în registru (articolul 116 din Regulamentul de procedură): a se vedea procesul-verbal Transmiterea textelor adoptate în cursul prezentei şedinţe: a se vedea procesul-verbal Calendarul următoarelor şedinţe: a se vedea procesul-verbal Întreruperea sesiunii Dichiaro interrotta la sessione del Parlamento europeo. (La seduta è tolta alle 13.00) Aprobarea procesului-verbal al şedinţei precedente: a se vedea procesul-verbal Componenţa Parlamentului: a se vedea procesul-verbal Cerere de apărare a imunităţii parlamentare: consultaţi procesul-verbal Numiri în comisii (propunerea Conferinţei preşedinţilor): consultaţi procesul-verbal Depunerea documentelor: a se vedea procesul-verbal Transmiterea de către Consiliu a textelor acordurilor: a se vedea procesul-verbal" } }
+{ "translation": { "en": "Action taken on Parliament's resolutions: see Minutes Oral questions and written statements (tabling): see Minutes Written statements (Rule 116): see Minutes Agenda: see Minutes 1. Appointments to parliamentary committees (vote): see Minutes Voting time Agenda for next sitting: see Minutes Closure of sitting (The sitting was closed at 12 midnight) Opening of the sitting (The sitting was opened at 09.05) Documents received: see Minutes Approval of Minutes of previous sitting: see Minutes 1. Protection of passengers against displaced luggage (vote) 2.", "ro": "Continuări ale rezoluţiilor Parlamentului: consultaţi procesul-verbal Declaraţii scrise şi întrebări orale (depunere): consultaţi procesul-verbal Declaraţii scrise (articolul 116 din Regulamentul de procedură) Ordinea de zi: a se vedea procesul-verbal 1. Numiri în comisiile parlamentare (vot): consultaţi procesul-verbal Timpul afectat votului Ordinea de zi a următoarei şedinţe: a se vedea procesul-verbal Ridicarea şedinţei (La seduta è tolta alle 24.00) Deschiderea şedinţei (The sitting was opened at 09.05) Depunerea documentelor: a se vedea procesul-verbal Aprobarea procesului-verbal al şedinţei precedente: a se vedea procesul-verbal 1. Protecţia pasagerilor împotriva deplasării bagajelor (vot) 2." } }
+{ "translation": { "en": "Approval of motor vehicles with regard to the forward field of vision of the driver (vote) 3. EC-Korea Agreement on scientific and technological cooperation (vote) 4. Mainstreaming sustainability in development cooperation policies (vote) 5. Draft Amending Budget No 1/2007 (vote) 7. EC-Gabon Fisheries Partnership (vote) 10. Limitation periods in cross-border disputes involving personal injuries and fatal accidents (vote) 12. Strategy for a strengthened partnership with the Pacific Islands (vote) 13. The European private company statute (vote) That concludes the vote.", "ro": "Omologarea vehiculelor cu motor cu privire la câmpul de vizibilitate înainte al conducătorului auto (vot) 3. Acordul CE-Coreea de cooperare ştiinţifică şi tehnologică (vot) 4. Integrarea durabilităţii în politicile de cooperare pentru dezvoltare (vot) 5. Proiect de buget rectificativ nr.1/2007 (vot) 7. Acordul de parteneriat în domeniul pescuitului între Comunitatea Europeană şi Republica Gaboneză (vot) 10. Termenele de prescripţie aplicabile în cadrul litigiilor transfrontaliere cu privire la vătămările corporale şi accidentele mortale (vot) 12. Relaţiile UE cu insulele din Pacific: Strategie pentru un parteneriat consolidat (vot) 13. Statutul societăţii private europene (vot) Damit ist die Abstimmungsstunde beendet." } }
+{ "translation": { "en": "Corrections to votes and voting intentions: see Minutes Assignment conferred on a Member: see Minutes Membership of committees and delegations: see Minutes Decisions concerning certain documents: see Minutes Forwarding of texts adopted during the sitting: see Minutes Dates for next sittings: see Minutes", "ro": "Corectările voturilor şi intenţiile de vot: a se vedea procesul-verbal Misiune încredinţată unui deputat: consultaţi procesul-verbal Componenţa comisiilor şi a delegaţiilor: a se vedea procesul-verbal Decizii privind anumite documente: a se vedea procesul-verbal Transmiterea textelor adoptate în cursul prezentei şedinţe: a se vedea procesul-verbal Calendarul următoarelor şedinţe: a se vedea procesul-verbal" } }
+{ "translation": { "en": "Written statements for entry", "ro": "Declaraţii scrise înscrise" } }
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/wmt_en_ro/val.json b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/wmt_en_ro/val.json
new file mode 100644
index 0000000000000000000000000000000000000000..22cdd68ecd1c5bd0018bbe04d756f4c10bd3b919
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/wmt_en_ro/val.json
@@ -0,0 +1,16 @@
+{ "translation": { "en": "Brazil's Former Presidential Chief-of-Staff to Stand Trial A federal judge on Tuesday accepted the charges filed against Brazil's former presidential chief of staff for his alleged involvement in a massive corruption scheme at state-owned oil company Petrobras. The federal prosecutor's office said Jose Dirceu will face trial on the corruption, racketeering and money laundering charges filed earlier this month. Fourteen other people will also be tried, including Joao Vaccari Neto, the former treasurer of Brazil's governing Workers' Party and Renato de Souza Duque, Petrobras' former head of corporate services.", "ro": "Fostul șef al cabinetului prezidențial brazilian este adus în fața instanței Marți, un judecător federal a acceptat acuzațiile aduse împotriva fostului șef al cabinetului prezidențial brazilian pentru presupusa implicare a acestuia într-o schemă masivă de corupție privind compania petrolieră de stat Petrobras. Biroul procurorului federal a declarat că Jose Dirceu va fi trimis în judecată pentru acuzațiile de corupție, înșelătorie și spălare de bani aduse în această lună. Alte paisprezece persoane vor fi judecate, printre acestea numărându-se Joao Vaccari Neto, fostul trezorier al Partidului Muncitorilor, aflat la putere în Brazilia, și Renato de Souza Duque, fostul președinte al serviciilor pentru întreprinderi ale Petrobras." } }
+{ "translation": { "en": "Dirceu is the most senior member of the ruling Workers' Party to be taken into custody in connection with the scheme. Dirceu served as former President Luiz Inacio Lula da Silva's chief of staff between 2003 and 2005. He was arrested early August in his home, where he already was under house arrest serving an 11-year sentence for his involvement in a cash-for-votes scheme in Congress more than 10 years ago. Prosecutors have said that Dirceu masterminded the kickback scheme at Petrobras, accepted bribes while in office and continued to receive payments from contractors after he was jailed in late 2013 for the vote-buying scandal.", "ro": "Dirceu este cel mai vechi membru al Partidului Muncitorilor aflat la guvernare luat în custodie pentru legăturile cu această schemă. Dirceu a servit ca șef de cabinet al fostului președinte Luiz Inacio Lula da Silva între 2003 și 2005. A fost arestat la începutul lui august de acasă, unde deja se afla sub arest la domiciliu, cu o pedeapsă de 11 ani pentru implicarea într-o schemă de cumpărare a voturilor în Congres cu peste 10 ani în urmă. Procurorii au declarat că Dirceu a dezvoltat schema de luare de mită de la Petrobras, a acceptat mită în timp ce se afla în funcție și a continuat să primească plăți de la antreprenori după ce a fost închis la sfârșitul lui 2013 pentru scandalul voturilor cumpărate." } }
+{ "translation": { "en": "According to prosecutors, the scheme at Petrobras involved roughly $2 billion in bribes and other illegal funds. Some of that money was allegedly funneled back to campaign coffers of the ruling party and its allies. It also allegedly included the payment of bribes to Petrobras executives in return for inflated contracts. 'Miraculous' recovery for Peshawar massacre schoolboy A teenager paralysed after being shot four times in Pakistan's deadliest terror attack has made a \"miraculous\" recovery following treatment in the UK. Muhammad Ibrahim Khan, 13, had been told by doctors in Pakistan that he would never walk again.", "ro": "Conform procurorilor, schema de la Petrobras a implicat aproximativ 2 miliarde de dolari sub formă de mită și alte fonduri ilegale. O parte din acei bani s-ar fi întors în fondul de campanie al partidului aflat la guvernare și al aliaților acestora. De asemenea, ar fi inclus mită către directorii Petrobras în schimbul unor contracte umflate. Recuperarea „miraculoasă” a unui elev supraviețuitor al masacrului de la Peshawar Un adolescent paralizat după ce fusese împușcat de patru ori în cel mai cumplit atac terorist din Pakistan a reușit o recuperare „miraculoasă” după ce a urmat un tratament în Regatul Unit. Lui Mohamed Ibrahim Khan, în vârstă de 13 ani, doctorii din Pakistan îi spuseseră că nu va mai putea să meargă niciodată." } }
+{ "translation": { "en": "At least 140 people, mostly children, were killed when gunmen stormed Peshawar's Army Public School last December. Muhammad, who arrived in London last month for surgery, is being discharged from hospital later. Exactly nine months ago, on an ordinary Tuesday morning, Muhammad sat in his first aid class listening to his teachers intently. At the same time seven gunmen disguised in security uniforms were entering the Army Public School. They were strapped with explosives and had one simple mission in mind: Kill every man, woman and child they came across. \"I can't forget what happened that day,\" Muhammad says with a severe stare.", "ro": "Cel puțin 140 de persoane, majoritatea copii, au fost ucise când bărbați înarmați au atacat școala publică a armatei din Peshawar în luna decembrie a anului trecut. Mohamed, care a sosit la Londra luna trecută pentru operație, va fi externat mai târziu din spital. Exact cu nouă luni în urmă, într-o dimineață obișnuită de marți, Mohamed stătea la ora de primul ajutor și își asculta atent profesorii. Chiar atunci, șapte bărbați înarmați deghizați în uniformele agenților de pază intrau în școala publică a armatei. Purtau centuri cu explozivi și aveau de îndeplinit o misiune simplă: să îi ucidă pe toți bărbații, femeile și copiii care le ieșeau în cale. „Nu pot uita ce s-a întâmplat în acea zi”, spune Mohamed cu o privire aspră." } }
+{ "translation": { "en": "We were sitting in the auditorium, we were asking questions... and then we heard heavy gunfire outside. The terrorists moved inside and they started killing - our teacher was burned alive. Muhammad described pulling four other pupils out of the auditorium as the carnage unfolded. He said he then heard his friend, Hamza calling to him. He said, 'oh brother save me'. I held his hand. That's when I was shot in the back, and he was shot in the head. Most of the people killed in the attack were pupils Hamza died in Muhammad's arms. Muhammad recalled blacking out after that, and the next thing he knew he was in a hospital bed, paralysed from the waist down.", "ro": "Stăteam în amfiteatru, puneam întrebări... apoi am auzit focuri de armă afară. Teroriștii au intrat înăuntru și au început să ucidă. Profesorul nostru a fost ars de viu. Mohamed descrie cum a scos patru elevi din amfiteatru în timp ce se desfășura carnagiul. Apoi spune că și-a auzit prietenul, pe Hamza, strigându-l. Spunea „oh, frate, salvează-mă”. L-am ținut de mână. Atunci eu am fost împușcat în spate, iar el în cap. Cei mai mulți dintre cei uciși în atac erau elevi Hamza a murit în brațele lui Mohamed. Mohamed își amintește că imediat după asta a leșinat și că următorul lucru pe care l-a știut a fost că se afla pe un pat de spital, paralizat de la brâu în jos." } }
+{ "translation": { "en": "Doctors in Peshawar in northern Pakistan, and then Rawalpindi, close to the capital, told his family there was no treatment, and he would never walk again. \"Seeing him I felt like my soul had left my body,\" says Muhammad's father, Sher Khan Those nine months were the hardest in my life. But Mr Khan and his wife, Sherbano, refused to believe that their cricket-mad son would never be able to use his legs again. They campaigned, and appealed for help on Pakistani TV, gaining the support of high profile people such as cricketer turned politician Imran Khan.", "ro": "Doctorii din Peshawar din nordul Pakistanului, apoi cei din Rawalpindi, aproape de capitală, i-au spus familiei sale că nu exista tratament și că nu va mai putea merge niciodată. „Când l-am văzut, am simțit cum îmi iese sufletul”, spune Sher Khan, tatăl lui Mohamed. Acele nouă luni au fost cele mai grele din viața mea. Însă Khan și soția lui, Sherbano, au refuzat să creadă că fiul lor atât de pasionat de crichet nu-și va mai putea folosi vreodată picioarele. Au făcut o campanie și au cerut ajutor de la televiziunea pakistaneză, atrăgând sprijinul unor oameni faimoși precum Imran Khan, jucător de crichet devenit politician." } }
+{ "translation": { "en": "Finally, they were able to raise the funds to bring Muhammad to the UK and provide him with treatment at London's private Harley Street Clinic. Consultant neurosurgeon Irfan Malik described Muhammad as \"terrified\" when he first arrived at the hospital. \"He'd spent the last [few] months lying on a bed, unable to move side to side,\" says Mr Malik. He was weak, he had a pressure sore on his back. He wasn't in great shape. A vertebra at the base of Muhammad's spine was destroyed Muhammad was shot in his shoulder, his hip, and his back during the attack, damaging his lower spine - leading to paralysis.", "ro": "Într-un final, au reușit să strângă fonduri pentru a-l duce pe Mohamed în Regatul Unit și a-i oferi tratament la clinica privată Harley Street din Londra. Neurochirurgul consultant Irfan Malik l-a descris pe Mohamed drept „înspăimântat” când acesta a ajuns la spital. „Își petrecuse ultimele [câteva] luni zăcând în pat, fără să se poată mișca de pe o parte pe alta, spune Malik. Era slăbit, se pusese multă presiune pe spatele lui. Nu era într-o formă prea bună. O vertebră de la baza coloanei vertebrale a lui Mohamed fusese distrusă Mohamed fusese împușcat în umăr, în șold și în spate în timpul atacului, iar coloana vertebrală inferioară îi fusese distrusă, ducând la paralizie." } }
+{ "translation": { "en": "But during six hours of surgery, Mr Malik and his team were able to reattach nerve endings and reconstruct the damaged part of the spine. Even Mr Malik was surprised at what happened next. Exactly one week after the surgery Muhammad stood up and started taking steps and walking. We were not expecting to get that sort of excellent result. That was miraculous,\" he says. Less than two weeks after his operation, Muhammad is ready to leave hospital and start the long road to recovery. Muhammad has defied the odds and started to walk again He says he wants to build his strength and continue his education in the UK. But he says he is determined to return to Pakistan, join the army and help fight terrorism.", "ro": "Însă, în timpul unei operații care a durat șase ore, Malik și echipa lui au reușit să lege din nou terminațiile nervoase și să reconstruiască partea distrusă a coloanei. Chiar și Malik a fost surprins de ceea ce s-a întâmplat în continuare. Exact la o săptămână după operație, Mohamed s-a ridicat și a început să facă pași și să meargă. Nu ne așteptam la un rezultat atât de bun. A fost un miracol”, spune acesta. În mai puțin de două săptămâni de la operație, Mohamed este gata să părăsească spitalul și să înceapă procesul lung de recuperare. Mohamed a sfidat soarta și a început să meargă din nou Vrea să devină puternic și să își continue studiile în Regatul Unit. Însă este hotărât să revină în Pakistan, să se înroleze în armată și să lupte împotriva terorismului." } }
+{ "translation": { "en": "\"I feel like I have a second chance at life,\" he says as he shows off pictures he's drawn of guns scribbled out next to school books and pens Muhammad grows physically stronger every day but the psychological trauma he continues to endure is unimaginable. \"My anger is not diminishing\" he says. In my school little kids were killed. What was their crime? His mother, wiping a tear from her eye, caressed his head and said: \"I can see my son walking again.\" He'll be able to get on with his normal life. 'Super Voice' 4G service from Three offers better signal Three is making use of a lower frequency 4G spectrum that can travel more widely", "ro": "„Simt că am încă o șansă la viață” spune el, arătând imaginile cu arme desenate de el lângă manuale școlare și stilouri Fizic, Mohamed devine tot mai puternic în fiecare zi, însă trauma psihologică prin care trece și acum este de neimaginat. „Furia mea nu a scăzut”, mărturisește el. În școala mea au fost uciși copii mici. Ce crimă au comis ei? Mama lui își șterge o lacrimă, îl mângâie pe creștet și spune: „Îmi văd fiul mergând din nou”. Va putea să-și continue firesc viața. Serviciul 4G „Super Voice” de la Three oferă semnal mai bun Three folosește un spectru 4G cu o frecvență mai joasă, care poate acoperi o zonă mai extinsă" } }
+{ "translation": { "en": "Mobile phone provider Three has launched a UK service it says will improve reception inside buildings and in rural black spots. Its 4G Super Voice enables customers to make calls and send texts using a lower frequency spectrum. Other networks are looking into introducing the technology, known as Voice Over Long-Term Evolution (VoLTE). It currently works on only the Samsung Galaxy S5, but recent iPhone handsets will be added in the coming months. Three said up to 5.5 million customers would have access to the service by 2017.", "ro": "Furnizorul de telefonie mobilă Three a lansat în Regatul Unit un serviciu despre care spune că va îmbunătăți recepția în interiorul clădirilor și în zonele rurale fără semnal. Serviciul 4G Super Voice le permite clienților să efectueze apeluri și să trimită mesaje text folosind un spectru cu o frecvență mai joasă. Și alte rețele intenționează să introducă aceeași tehnologie, cunoscută ca „Voice Over Long-Term Evolution (VoLTE)”. Aceasta funcționează momentan doar cu Samsung Galaxy S5, însă telefoanele iPhone recente vor beneficia de ea în lunile următoare. Three menționează că până la 5,5 milioane de clienți vor avea acces la serviciu până în 2017." } }
+{ "translation": { "en": "Chief technology officer Bryn Jones said: \"By the end of the year, one million of our customers will have access to better indoor coverage and be able to use their phones in more places than ever before.\" Stars prepare for panto season Pantomime season is big business for theatres up and down the UK, with many getting ready for this year's season now. Some of the biggest names in showbusiness now take part in the yuletide theatre. Matthew Kelly and Hayley Mills will be appearing in Cinderella - one as an ugly sister, the other as fairy godmother. They reveal their panto secrets to BBC Breakfast. Steven Wilson: 'If I don't do anything, I feel this creeping guilt'", "ro": "Responsabilul șef pentru tehnologie, Bryn Jones a declarat: „Până la sfârșitul anului, un milion dintre clienții noștri vor avea acces la o acoperire mai bună în interior și își vor putea folosi telefoanele în mai multe locuri ca până acum”. Vedetele se pregătesc pentru stagiunea de pantomimă Stagiunea de pantomimă este foarte importantă pentru teatrele din tot Regatul Unit, multe dintre ele pregătindu-se acum pentru stagiunea din acest an. Acum, la teatrul de Crăciun participă unele dintre numele cele mai mari din showbusiness. Matthew Kelly și Hayley Mills vor apărea în Cenușăreasa - primul în rolul uneia dintre surorile rele, iar a doua în rolul zânei. Aceștia dezvăluie secretele pantomimei lor la BBC Breakfast. Steven Wilson: „Dacă nu fac nimic, mă simt vinovat”" } }
+{ "translation": { "en": "Steven Wilson was recently the big winner at the Progressive Music Awards Steven Wilson is often dubbed the hardest working musician in the world of progressive rock. The multi-talented musician won three prizes at this month's Progressive Music Awards in London, including album of the year for Hand. The Guardian's five-star review called it \"a smart, soulful and immersive work of art.\" Since the 1980s, Wilson has been the driving force in a number of musical projects, the best known of which is the rock band Porcupine Tree. Now, ahead of two sell-out shows at the Royal Albert Hall, Wilson is releasing a vinyl-only double LP, Transience, to showcase the \"more accessible\" side of his solo output.", "ro": "Steven Wilson a fost desemnat recent drept marele câștigător al Progressive Music Awards Steven Wilson a fost numit de multe ori drept cel mai muncitor muzician din lumea rockului progresiv. Talentatul muzician a câștigat trei premii la Progressive Music Awards, care a avut loc luna aceasta la Londra, printre care și premiul pentru cel mai bun album al anului pentru Hand. În recenzia sa de cinci stele, The Guardian a numit albumul „o operă de artă inteligentă, expresivă și captivantă”. Încă din anii 1980, Wilson este motorul mai multor proiecte muzicale, cel mai cunoscut dintre acestea fiind trupa de rock Porcupine Tree. Acum, înainte de două spectacole cu casa închisă la Royal Albert Hall, Wilson lansează un dublu LP doar în format vinil, Transience, pentru a arăta latura „mai accesibilă” a activității sale solo." } }
+{ "translation": { "en": "He tells the BBC about his love of vinyl, his busy schedule and explains how comic actor Matt Berry came to be his support act. What does vinyl mean to you? I grew up at the very tail end of the vinyl era, and at the time, I remember, we couldn't wait for CD to come along because vinyl was so frustrating. You would buy the record, take it home, and it would have a scratch, and you would have to take it back again. I love CDs, and for some kinds of music - classical for example - it is better than vinyl. But the problem with the CD and digital downloads is that there's nothing you can really cherish or treasure. Owning vinyl is like having a beautiful painting hanging in your living room.", "ro": "A povestit pentru BBC despre dragostea lui pentru viniluri și despre programul său încărcat și a explicat cum a ajuns actorul de comedie Matt Berry să îi deschidă spectacolele. Ce înseamnă vinil pentru tine? Am crescut chiar în perioada de sfârșit a erei vinilurilor și îmi amintesc că atunci abia așteptam apariția CD-ului, căci vinilul era atât de enervant. Cumpărai un disc, mergeai cu el acasă, avea o zgârietură și trebuia să îl aduci înapoi. Iubesc CD-urile, iar pentru anumite tipuri de muzică, de exemplu cea clasică, sunt mai bune decât vinilurile. Însă problema cu CD-urile și cu descărcările digitale este aceea că nu mai există nimic pe care să îl prețuiești cu adevărat. Să ai un vinil e ca și cum ai avea un tablou frumos agățat în sufragerie." } }
+{ "translation": { "en": "It's something you can hold, pore over the lyrics and immerse yourself in the art work. I thought it was just a nostalgic thing, but it can't be if kids too young to remember vinyl are enjoying that kind of experience. Do you have a piece of vinyl that you treasure? The truth is I got rid of 100% of my vinyl in the 90s. All the vinyl I have is re-bought. I started off from the perspective that I wanted to recreate the collection I had when I was 15, but it's gone beyond that. The first record which I persuaded my parents to buy for me was Electric Light Orchestra's Out of the Blue.", "ro": "E ceva ce poți ține în mână, în timp ce te lași absorbit de versuri și copleșit de actul artistic. Am crezut că e doar o chestie nostalgică, însă nu are cum să fie așa dacă unor puști prea tineri să-și amintească de viniluri le place acest gen de experiență. Ai vreun vinil la care ții în mod special? Recunosc că am scăpat de toate vinilurile în anii '90. Toate vinilurile pe care le am sunt cumpărate din nou. Am pornit de la ideea de a reface colecția pe care o aveam la 15 ani, însă am trecut de limita aceea. Primul disc pe care mi-am convins părinții să mi-l cumpere a fost Out of the Blue de la Electric Light Orchestra." } }
+{ "translation": { "en": "If I still had my original copy, it would have sentimental value, but, alas, it's in a charity shop somewhere. Steven Wilson hopes the album will be a doorway for potential new fans Why release your new compilation Transience on vinyl? It was originally conceived as an idea for Record Store Day, but we missed the boat on that. My record company had suggested I put together some of my shorter, more accessible songs. I got a bit obsessed by the idea to make something like \"an introduction to Steven Wilson,\" and I was committed to it being a vinyl-only release. Anyone who buys the vinyl does also get a high-resolution download.", "ro": "Dacă aș mai fi avut încă exemplarul inițial, acesta ar fi avut valoare sentimentală, însă, din păcate, se află pe undeva printr-un magazin de caritate. Steven Wilson speră că albumul va fi o poartă către posibili fani noi De ce ți-ai lansat noua compilație Transience pe vinil? Aceasta a fost concepută inițial ca idee pentru Ziua magazinelor de discuri, însă am ratat ocazia. Casa mea de discuri sugerase să adun câteva dintre melodiile mele mai scurte și mai accesibile. Am ajuns să fiu ușor obsedat de ideea de a face ceva gen „introducere în muzica lui Steven Wilson” și am ținut neapărat ca proiectul să fie lansat doar pe vinil. Cine cumpără vinilul primește, de asemenea, și o variantă descărcată la rezoluție înaltă." } }
+{ "translation": { "en": "Do you have a concern that the album won't show your work in a true light?", "ro": "Ești îngrijorat că albumul nu va arăta muzica ta în adevărata ei lumină?" } }
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/xsum/sample.json b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/xsum/sample.json
new file mode 100644
index 0000000000000000000000000000000000000000..ea6e8a8bb8f6705b20776a4e126b8822d6889f7e
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/tests_samples/xsum/sample.json
@@ -0,0 +1,10 @@
+{"document": "The warning begins at 22:00 GMT on Saturday and ends at 10:00 on Sunday.\nThe ice could lead to difficult driving conditions on untreated roads and slippery conditions on pavements, the weather service warned.\nOnly the southernmost counties and parts of the most westerly counties are expected to escape.\nCounties expected to be affected are Carmarthenshire, Powys, Ceredigion, Pembrokeshire, Denbighshire, Gwynedd, Wrexham, Conwy, Flintshire, Anglesey, Monmouthshire, Blaenau Gwent, Caerphilly, Merthyr Tydfil, Neath Port Talbot, Rhondda Cynon Taff and Torfaen.", "summary": "The Met Office has issued a yellow weather warning for ice across most of Wales."}
+{"document": "You can see highlights of Sunderland v Arsenal on Match of the Day at 22:20 BST on Saturday on BBC One and the BBC Sport website.\nStoke and West Ham, for example, have started to climb away from the relegation zone but the biggest worry for Sunderland fans is that their side do not look remotely capable of doing the same.\nI know the Black Cats have got out of trouble before having found themselves in a similar situation but this time, after picking up only two points from their first nine games, things look really desperate for the only top-flight team without a win.\nAt least one element of their struggles seems to be self-inflicted, with everyone at the club feeling sorry for themselves - and not just because they have lost some players to injury and conceded some costly late goals.\nThere is a negative feeling about the place with the manager David Moyes and his players talking about how they have gone backwards since last season, when they should be searching for any kind of spark that could change things around.\nFrom the outside, looking at the way they play and their lack of creativity, it is hard to see what that spark might be or what could fundamentally change under Moyes until the January transfer window opens.\nIf they can get one win under their belt then they will get a bit of belief back but, the longer this winless run goes on, the more negativity there will be.\nMedia playback is not supported on this device\nSunderland finished last season on a high under Sam Allardyce, with a run of just one defeat in their last 11 games securing their safety.\nIn the space of five months, all of that confidence and momentum seems to have been sucked out of the club, despite them effectively having the same group of players who, not so long ago, looked inspired.\nThat is not all down to Moyes, but he has to take some responsibility for it.\nI am yet to see a defined style of play from Sunderland since he took charge at the end of July.\nThat is in contrast to Allardyce's time as manager, when they were resolute and difficult to beat and, at the end of his stint at the Stadium of Light, also played with a purpose when they went forward.\nOff the pitch, Moyes has not helped himself much either.\nThere was no need for him to be so pessimistic when he came out after the second game of the season and announced they would be in a relegation fight, which did not send out the right message to his players or the fans.\nWhen he took charge, he had actually started out by being unrealistically positive - talking about Sunderland becoming a club that regularly finished in the top half of the Premier League - but his expectations went downhill very quickly.\nI know you can argue that he has been proved right, because Sunderland are now battling the drop, but it meant there was a cloud over from them almost as soon as the season had started.\nIt seems to be a case that if you stop Jermain Defoe, you stop Sunderland. His statistics stand up well in comparison to last season, but the rest of their team are not doing enough in attack.\nThey were reliant on Defoe last season too, but others did chip in - in their first nine league games of 2015-16, five players found the net. This time around, only Defoe and Patrick van Aanholt have scored in the same period.\nIt is going to be a massive struggle for them to stay up from the position they are now in anyway, but they badly need a win and quickly. I don't see it coming at home to Arsenal on Saturday, though.\nDo they even look capable of holding out for a draw against the Gunners, the way another struggling team Middlesbrough did at Emirates Stadium last weekend? No.\nIf you struggle to make chances and score goals, as Sunderland do, that puts more pressure on your defence because you know if you concede then you are in big trouble.\nAnd the Black Cats have problems at the back as well - their only clean sheet in 12 matches under Moyes was against League One side Shrewsbury Town in the EFL Cup.\nIt does not bode well against an Arsenal side that are averaging more than two goals a game this season.\nIt is hard to find any positives from Sunderland's situation but at least they have not been cut adrift at the bottom - yet.\nUnless they win soon, that could happen. I think Hull are also in for a very tough season but when I look at the other two teams immediately above them, Boro and Swansea, they definitely have more about them than the Black Cats do.\nMedia playback is not supported on this device\nChanging manager has clearly not helped Sunderland and comparisons with his predecessor do not help Moyes much either.\nYou cannot tell me that, if Allardyce was still in charge, Sunderland would have only picked up two points so far. It just would not have happened.\nMoyes replaced him relatively late in the summer, which is difficult in itself, but he can only complain about the things that have gone against him up to a point. He should be doing much better than he is.\nHe is still the manager and he is capable of turning things around, so it is right there is no suggestion of him getting the sack.\nBut that will not last forever. This industry is results-driven and Moyes' results are not good enough.\nThat clearly has to change soon and, looking at Sunderland's next few fixtures, the one that stands out as a must-win is their home game against Hull on 19 November.\nIf they fail to beat Arsenal and Bournemouth, then the visit of the Tigers will be the game to define Moyes' tenure. If Sunderland are still without a win after that, things will become extremely difficult for him.\nChris Sutton was speaking to BBC Sport's Chris Bevan.", "summary": "We are exactly a quarter of the way through the Premier League season and some teams at the bottom of the table seem to be turning things around after making a bad start."}
+{"document": "The win keeps the Candystripes two points behind leaders Dundalk who won 2-0 away to Shamrock Rovers.\nFormer Plymouth striker Patterson scored his sixth goal of the season in the 14th minute at the Brandywell.\nHe shot into an empty net after the ball broke to him when keeper Dean Delany thwarted Barry McNamee.\nKurtis Byrne should have netted a speedy equaliser but the son of former Celtic player Paul Byrne completely missed his kick in front of goal.\nThat was the one big scare for Kenny Shiels' men on a night when both keepers had a quiet night.\nDerry City have won six and drawn two in the eight games they have played since losing to Finn Harps on the first day of the season.", "summary": "Rory Patterson's early goal proved enough to give second-placed Derry City a home victory over Bohemians in Friday night's Premier Division clash."}
+{"document": "The centre-right coalition led by Mr Passos Coelho won the most seats in the election on 4 October.\nBut Socialist leader Antonio Costa has been working to build a coalition with far-left parties.\nMany believe that Mr Passos Coelho will fail to pass the test of a vote of no confidence in Portugal's parliament.\nPresident Anibal Cavaco Silva would then be expected to ask the left to form a government.\nThere are fears that weeks of uncertainty could harm Portugal's economic recovery, more than a year after it exited the strict terms of its €78bn (£57bn) international bailout.\nEU officials have threatened to take action against Portugal for missing a 15 October deadline to present its draft 2016 budget.\nPortugal is still running one of the highest budget deficits in the eurozone.\n12%\nof the workforce is unemployed\n20%\nof people live below the poverty line\n485,000 emigrated from Portugal between 2011 and 2014\n125% debt to GDP - the second highest rate in the European Union\nMr Passos Coelho's Social Democrats have promised to present a budget, but the two left-wing parties campaigned strongly against his outgoing government's record of harsh austerity.\nThe Left Bloc is seen as allied to the anti-austerity Syriza party in Greece, which for months tried to renegotiate the terms of Greece's eurozone bailout.\nPortugal's Communist Party is regarded as anti-euro and anti-Nato, although it is thought to have moderated its eurozone policies in recent weeks.\nIf Mr Costa's Socialists are eventually chosen to lead a left-wing coalition, it would be the first time since the fall of Portugal's dictatorship in 1974 that a right-wing president appointed a government backed by communists.\nAfter his re-appointment as prime minister leading a right-of-centre coalition, Pedro Passos Coelho has 10 days to appoint ministers and secure parliamentary approval.\nThat may prove impossible, since his coalition lost its majority in the 4 October election and the Socialists have pledged to reject his programme if their talks with other parties succeed.\nTogether, the Socialists, Left Bloc and Communist Party have a majority. All wanted the president to appoint Mr Costa - arguing that anything else was a waste of time.\nIf Mr Passos Coelho does fail, the president could then appoint Mr Costa or keep the incumbent on as caretaker.\nFresh legislative elections may only take place from June, after voters have elected a new president early next year.", "summary": "The Portuguese president has invited incumbent Prime Minister Pedro Passos Coelho to form the next government, despite him having lost his majority."}
+{"document": "Nev Edwards scored an early try for Sale, before Castres' Florian Vialelle went over, but Julien Dumora's penalty put the hosts 10-7 ahead at the break.\nJoe Ford sent over a penalty before Castres' Marc-Antoine Rallier and Sales' Will Addison were sin-binned.\nJulien Caminati's late attempt to stop Charlie Ingall saw Sale awarded the decisive penalty try.\nThe win moves the English Premiership side to within one point of Pool Two leaders Newport Gwent Dragons after three games.\nSale got off to the ideal start, Edwards sprinting away for the game's opening points from an Andrei Ostrikov kick, but Castres heaped the pressure on in search of a reply, which came through Vialelle on eight minutes.\nSharks flanker Magnus Lund was forced off with a head injury before the television match official denied Castres a second try, with replays showing that the Sharks defence did enough to force full-back Caminati into touch.\nFord had a chance to put Sale ahead again, but his penalty on 27 minutes drifted wide. Dumora, however, made no mistake soon after, slotting over to give the French side the lead on 33 minutes.\nA combination of probing grubber kicks and scrappy play eventually led to Ford teeing up his second penalty attempt, with the fly-half this time booting the three points to make it 10-10.\nRallier's yellow card following a scuffle saw Ford opt for the posts soon after, but he was off target again before Sales' one-man advantage was lost as Addison was sin-binned.\nSharks pushed for the breakthrough as Ingall went close to touching down, and the video referee eventually gave the penalty try after deciding that Caminati's attempt to stop the winger was illegal.\nCastres: Caminati; Martial, Vialelle, Combezou, Decrop; Dumora, Dupont; Taumoepeau, Rallier, Montes; Samson, Moreaux, Caballero, Diarra, Beattie.\nReplacements: Beziat, Tichit, Martinez, Desroche, Babillot, Fontaine, Lamerat, Seron.\nSale: Arscott; Edwards, Addison, Jennings, Ingall; Ford, Mitchell, Lewis-Roberts, Briggs, Mujati, Mills, Ostrikov, Lund, Seymour (capt), Easter.\nReplacements: Taylor, Flynn, Parker, Beaumont, Neild, Jeffers, James, Haley.\nReferee: David Wilkinson (Ireland)", "summary": "A late penalty try gave Sale victory over Castres at Stade Pierre-Antoine in their European Challenge Cup clash."}
+{"document": "The 33-year-old was released by Norwich this summer after five years at the club, during which time he made 75 Canaries first-team appearances.\nTurner also had spells on loan at Fulham and Sheffield Wednesday during his time at Carrow Road.\nIn total, the centre-back has made 436 senior career appearances for eight different clubs.\nFind all the latest football transfers on our dedicated page.", "summary": "League One side Southend United have signed former Hull and Norwich defender Michael Turner on a one-year deal."}
+{"document": "United contacted St Johnstone this week with a view to speaking to 52-year-old Wright about the job but this approach was rejected by the Saints board.\nThe Tannadice club - bottom of the Premiership - are seeking to replace Jackie McNamara, who left last month.\nDave Bowman took the first team for Saturday's loss to Partick Thistle.\nThe Tangerines have won only once this season and prop up the table with five points from 10 games.\nFormer Northern Ireland goalkeeper Wright, who replaced Steve Lomas at McDiarmid Park in 2013, led St Johnstone to Scottish Cup success in his first season in charge.\nHe has also secured two successive top-six finishes for the Perth side and previously managed in his homeland.", "summary": "St Johnstone boss Tommy Wright is no longer under consideration for the Dundee United manager's job, BBC Scotland has learned."}
+{"document": "Media playback is unsupported on your device\n2 November 2014 Last updated at 17:20 GMT\nHomes and businesses were damaged in the storm, but weather experts were not able to confirm it was a tornado.\nNavtej Johal reports.", "summary": "Residents in Coalville in Leicestershire are cleaning up after high winds hit the town."}
+{"document": "5 August 2015 Last updated at 06:36 BST\nShe's now 84 and has been telling Newsround the inspiring story of her life before and after that devastating and world-changing event.\nThis animation contains some sad moments that you might find upsetting.\nYou can find out more about what happened in Hiroshima here.\nWatch 'Hiroshima: A Newsround Special' - Thursday 6 August at 5.30pm on the CBBC channel and on the Newsround website.", "summary": "Bun Hashizume was 14 years old and lived in Hiroshima, in Japan, when a nuclear bomb was dropped on the city 70 years ago, at the end of World War Two."}
+{"document": "But what has been your moment of the year?\nFrom Ben Stokes' 258 off 198 balls against South Africa to Stuart Broad's 6-17 against the same opponents, and Alastair Cook being the first Englishman to reach 10,000 Test runs, there are lots of highlights.\nOr perhaps you revelled in Australia being skittled for just 85? Or the dog that invaded the pitch at Vizag?\nThe cricket brains of BBC Sport and BBC Radio 5 live asked you to rank your top 10, and your shortlist will be revealed on Tuesday's Tuffers and Vaughan Cricket Show (20:30 GMT, BBC Radio 5 live and online).\nVotes will no longer count but you can still pick your top 10 and share with friends.\nWhat are your top 10 cricketing moments from this year?", "summary": "It's been topsy-turvy for the England side but eventful and entertaining nonetheless."}
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/vocab.json b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/vocab.json
new file mode 100644
index 0000000000000000000000000000000000000000..c5d99b8ae9d4d6d94d91af3e7e2515f61c8ce7d9
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/vocab.json
@@ -0,0 +1 @@
+{"l": 0, "o": 1, "w": 2, "e": 3, "r": 4, "s": 5, "t": 6, "i": 7, "d": 8, "n": 9, "Ġ": 10, "Ġl": 11, "Ġn": 12, "Ġlo": 13, "Ġlow": 14, "er": 15, "Ġlowest": 16, "Ġnewer": 17, "Ġwider": 18, "": 19, "<|endoftext|>": 20}
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/vocab.txt b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/vocab.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ad9f94bc6876d33f79e8dd7bbc19c2dab700f1df
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fixtures/vocab.txt
@@ -0,0 +1,10 @@
+[PAD]
+[SEP]
+[MASK]
+[CLS]
+[unused3]
+[unused4]
+[unused5]
+[unused6]
+[unused7]
+[unused8]
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/fsdp/test_fsdp.py b/tasks/tasksmith-441eeab80047/tests/source/tests/fsdp/test_fsdp.py
new file mode 100644
index 0000000000000000000000000000000000000000..cce33cc7e6cd0f9c32f14b414d195576c3840524
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/fsdp/test_fsdp.py
@@ -0,0 +1,357 @@
+# Copyright 2023 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 itertools
+import os
+import subprocess
+import unittest
+from copy import deepcopy
+from functools import partial
+
+from parameterized import parameterized
+
+import tests.trainer.test_trainer
+from tests.trainer.test_trainer import TrainerIntegrationCommon # noqa
+from transformers import is_torch_available
+from transformers.testing_utils import (
+ TestCasePlus,
+ backend_device_count,
+ execute_subprocess_async,
+ mockenv_context,
+ require_accelerate,
+ require_fsdp,
+ require_torch_accelerator,
+ require_torch_multi_accelerator,
+ run_first,
+ slow,
+ torch_device,
+)
+from transformers.trainer_callback import TrainerState
+from transformers.trainer_utils import FSDPOption, set_seed
+from transformers.utils import (
+ is_accelerate_available,
+ is_torch_bf16_available_on_device,
+ is_torch_fp16_available_on_device,
+)
+
+
+if is_torch_available():
+ from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_1
+ from transformers.trainer import FSDP_MODEL_NAME
+else:
+ is_torch_greater_or_equal_than_2_1 = False
+
+# default torch.distributed port
+DEFAULT_MASTER_PORT = "10999"
+
+dtypes = []
+if is_torch_bf16_available_on_device(torch_device):
+ dtypes += ["bf16"]
+if is_torch_fp16_available_on_device(torch_device):
+ dtypes += ["fp16"]
+
+sharding_strategies = ["full_shard", "shard_grad_op"]
+state_dict_types = ["FULL_STATE_DICT", "SHARDED_STATE_DICT"]
+params = list(itertools.product(sharding_strategies, dtypes))
+
+set_seed(42)
+
+
+def get_master_port(real_launcher=False):
+ """
+ When using a single gpu launcher emulation (i.e. not deepspeed or python -m torch.distributed)
+ the issue is that once the port is tied it can't be used anywhere else outside of this process,
+ since torch.dist doesn't free the port until the process exits. Therefore for the sake of being
+ able to run both emulated launcher and normal launcher tests we need 2 distinct ports.
+
+ This function will give the right port in the right context. For real launcher it'll give the
+ base port, for emulated launcher it'll give the base port + 1. In both cases a string is
+ returned.
+
+ Args:
+ `real_launcher`: whether a real launcher is going to be used, or the emulated one
+
+ """
+
+ master_port_base = os.environ.get("DS_TEST_PORT", DEFAULT_MASTER_PORT)
+ if not real_launcher:
+ master_port_base = str(int(master_port_base) + 1)
+ return master_port_base
+
+
+if is_torch_available():
+ from tests.trainer.test_trainer import ( # noqa
+ RegressionModelConfig,
+ RegressionPreTrainedModel,
+ )
+
+ # hack to restore original logging level pre #21700
+ get_regression_trainer = partial(tests.trainer.test_trainer.get_regression_trainer, log_level="info")
+
+require_fsdp_version = require_fsdp
+if is_accelerate_available():
+ from accelerate.utils.constants import (
+ FSDP_PYTORCH_VERSION,
+ FSDP_SHARDING_STRATEGY,
+ )
+
+ require_fsdp_version = partial(require_fsdp, min_version=FSDP_PYTORCH_VERSION)
+
+
+def get_launcher(distributed=False, use_accelerate=False):
+ # 1. explicitly set --num_nodes=1 just in case these tests end up run on a multi-node setup
+ # - it won't be able to handle that
+ # 2. for now testing with just 2 gpus max (since some quality tests may give different
+ # results with mode gpus because we use very little data)
+ num_gpus = min(2, backend_device_count(torch_device)) if distributed else 1
+ master_port = get_master_port(real_launcher=True)
+ if use_accelerate:
+ return f"""accelerate launch
+ --num_processes {num_gpus}
+ --main_process_port {master_port}
+ --use_fsdp
+ --fsdp_auto_wrap_policy TRANSFORMER_BASED_WRAP
+ --fsdp_state_dict_type SHARDED_STATE_DICT
+ --fsdp_transformer_layer_cls_to_wrap BertLayer""".split()
+ return f"torchrun --nnodes 1 --nproc-per-node {num_gpus} --master-port {master_port}".split()
+
+
+def _parameterized_custom_name_func(func, param_num, param):
+ # customize the test name generator function as we want both params to appear in the sub-test
+ # name, as by default it shows only the first param
+ param_based_name = parameterized.to_safe_name("_".join(str(x) for x in param.args))
+ return f"{func.__name__}_{param_based_name}"
+
+
+@require_accelerate
+@require_torch_accelerator
+@require_fsdp_version
+class TrainerIntegrationFSDP(TestCasePlus, TrainerIntegrationCommon):
+ def setUp(self):
+ super().setUp()
+ master_port = get_master_port(real_launcher=False)
+ self.dist_env_1_gpu = {
+ "MASTER_ADDR": "localhost",
+ "MASTER_PORT": master_port,
+ "RANK": "0",
+ "LOCAL_RANK": "0",
+ "WORLD_SIZE": "1",
+ }
+
+ self.fsdp_config = {
+ "backward_prefetch": "BACKWARD_PRE",
+ "forward_prefetch": "false",
+ "limit_all_gathers": "false",
+ "use_orig_params": "true",
+ "sync_module_states": "true",
+ "cpu_ram_efficient_loading": "true",
+ "activation_checkpointing": "false",
+ "min_num_params": 1,
+ }
+
+ def tearDown(self):
+ super().tearDown()
+
+ @parameterized.expand(params, name_func=_parameterized_custom_name_func)
+ def test_fsdp_config(self, sharding_strategy, dtype):
+ output_dir = self.get_auto_remove_tmp_dir()
+ kwargs = {
+ "output_dir": output_dir,
+ "train_len": 128,
+ "save_steps": 5,
+ "learning_rate": 0.1,
+ "fsdp": f"{sharding_strategy} offload auto_wrap",
+ "fsdp_config": self.fsdp_config,
+ }
+ kwargs[dtype] = True
+ with mockenv_context(**self.dist_env_1_gpu):
+ trainer = get_regression_trainer(**kwargs)
+ self.assertEqual(trainer.args.fsdp[0], sharding_strategy)
+ self.assertEqual(trainer.args.fsdp[1], FSDPOption.OFFLOAD)
+ self.assertEqual(trainer.args.fsdp[2], FSDPOption.AUTO_WRAP)
+ for k, v in trainer.args.fsdp_config.items():
+ self.assertEqual(v, self.fsdp_config[k])
+ self.assertEqual(os.environ.get("ACCELERATE_USE_FSDP", "false"), "true")
+
+ @parameterized.expand(params, name_func=_parameterized_custom_name_func)
+ def test_fsdp_config_transformers_auto_wrap(self, sharding_strategy, dtype):
+ output_dir = self.get_auto_remove_tmp_dir()
+ fsdp_config = deepcopy(self.fsdp_config)
+ del fsdp_config["min_num_params"]
+ fsdp_config["transformer_layer_cls_to_wrap"] = "BertLayer"
+ kwargs = {
+ "output_dir": output_dir,
+ "train_len": 128,
+ "save_steps": 5,
+ "learning_rate": 0.1,
+ "fsdp": f"{sharding_strategy} offload auto_wrap",
+ "fsdp_config": fsdp_config,
+ }
+ kwargs[dtype] = True
+ prefix = "FSDP_"
+ with mockenv_context(**self.dist_env_1_gpu):
+ trainer = get_regression_trainer(**kwargs)
+ self.assertEqual(trainer.args.fsdp[0], sharding_strategy)
+ self.assertEqual(trainer.args.fsdp[1], FSDPOption.OFFLOAD)
+ self.assertEqual(trainer.args.fsdp[2], FSDPOption.AUTO_WRAP)
+ fsdp_sharding_strategy = str(FSDP_SHARDING_STRATEGY.index(sharding_strategy.upper()) + 1)
+ self.assertEqual(os.environ[f"{prefix}SHARDING_STRATEGY"], fsdp_sharding_strategy)
+ self.assertEqual(os.environ[f"{prefix}OFFLOAD_PARAMS"], "true")
+ self.assertEqual(os.environ[f"{prefix}AUTO_WRAP_POLICY"], "TRANSFORMER_BASED_WRAP")
+ self.assertEqual(
+ os.environ[f"{prefix}TRANSFORMER_CLS_TO_WRAP"], ",".join(fsdp_config["transformer_layer_cls_to_wrap"])
+ )
+ self.assertEqual(os.environ[f"{prefix}BACKWARD_PREFETCH"], fsdp_config["backward_prefetch"])
+ self.assertEqual(os.environ[f"{prefix}FORWARD_PREFETCH"], fsdp_config["forward_prefetch"])
+ self.assertEqual(os.environ[f"{prefix}USE_ORIG_PARAMS"], fsdp_config["use_orig_params"])
+ self.assertEqual(os.environ[f"{prefix}SYNC_MODULE_STATES"], fsdp_config["sync_module_states"])
+ self.assertEqual(
+ os.environ[f"{prefix}CPU_RAM_EFFICIENT_LOADING"], fsdp_config["cpu_ram_efficient_loading"]
+ )
+ self.assertEqual(os.environ.get("ACCELERATE_USE_FSDP", "false"), "true")
+
+ @parameterized.expand(params, name_func=_parameterized_custom_name_func)
+ @require_torch_multi_accelerator
+ @run_first
+ @slow
+ def test_basic_run(self, sharding_strategy, dtype):
+ launcher = get_launcher(distributed=True, use_accelerate=False)
+ output_dir = self.get_auto_remove_tmp_dir()
+ args = self.get_base_args(output_dir, 1, 50).split() + [f"--{dtype}"]
+ fsdp_args = ["--fsdp", f"{sharding_strategy} auto_wrap", "--fsdp_transformer_layer_cls_to_wrap", "BertLayer"]
+ script = [f"{self.examples_dir_str}/pytorch/text-classification/run_glue.py"]
+ cmd = launcher + script + args + fsdp_args
+ execute_subprocess_async(cmd, env=self.get_env())
+
+ @parameterized.expand(params, name_func=_parameterized_custom_name_func)
+ @require_torch_multi_accelerator
+ @run_first
+ @slow
+ def test_basic_run_with_gradient_accumulation(self, sharding_strategy, dtype):
+ launcher = get_launcher(distributed=True, use_accelerate=False)
+ output_dir = self.get_auto_remove_tmp_dir()
+ args = self.get_base_args(output_dir, 1, 50).split() + [f"--{dtype}", "--gradient_accumulation_steps", "2"]
+ fsdp_args = ["--fsdp", f"{sharding_strategy} auto_wrap", "--fsdp_transformer_layer_cls_to_wrap", "BertLayer"]
+ script = [f"{self.examples_dir_str}/pytorch/text-classification/run_glue.py"]
+ cmd = launcher + script + args + fsdp_args
+ execute_subprocess_async(cmd, env=self.get_env())
+
+ @parameterized.expand(dtypes)
+ @require_torch_multi_accelerator
+ @run_first
+ @slow
+ @unittest.skipIf(not is_torch_greater_or_equal_than_2_1, reason="This test on pytorch 2.0 takes 4 hours.")
+ def test_basic_run_with_cpu_offload(self, dtype):
+ launcher = get_launcher(distributed=True, use_accelerate=False)
+ output_dir = self.get_auto_remove_tmp_dir()
+ args = self.get_base_args(output_dir, 1, 50).split() + [f"--{dtype}", "--max_steps", "10"]
+ fsdp_args = ["--fsdp", "full_shard auto_wrap offload", "--fsdp_transformer_layer_cls_to_wrap", "BertLayer"]
+ script = [f"{self.examples_dir_str}/pytorch/text-classification/run_glue.py"]
+ cmd = launcher + script + args + fsdp_args
+ execute_subprocess_async(cmd, env=self.get_env())
+
+ @parameterized.expand(state_dict_types, name_func=_parameterized_custom_name_func)
+ @require_torch_multi_accelerator
+ @run_first
+ @slow
+ def test_training_and_can_resume_normally(self, state_dict_type):
+ output_dir = self.get_auto_remove_tmp_dir("./xxx", after=False)
+
+ sharding_strategy = "full_shard"
+ use_accelerate = state_dict_type == "SHARDED_STATE_DICT"
+ launcher = get_launcher(True, use_accelerate=use_accelerate)
+ args = self.get_base_args(output_dir, 2, 25).split()
+ script = [f"{self.examples_dir_str}/pytorch/text-classification/run_glue.py"]
+ logs = self.run_cmd_and_get_logs(use_accelerate, sharding_strategy, launcher, script, args, output_dir)
+
+ # resume from ckpt
+ checkpoint = os.path.join(output_dir, "checkpoint-115")
+ resume_args = args + f"--resume_from_checkpoint {checkpoint}".split()
+
+ is_fsdp_ckpt = os.path.isdir(checkpoint) and (
+ # this checks the FSDP state dict when `SHARDED_STATE_DICT` is used
+ any(
+ FSDP_MODEL_NAME in folder_name
+ for folder_name in os.listdir(checkpoint)
+ if os.path.isdir(os.path.join(checkpoint, folder_name))
+ )
+ # this checks the FSDP state dict when `FULL_STATE_DICT` is used
+ or os.path.isfile(os.path.join(checkpoint, f"{FSDP_MODEL_NAME}.bin"))
+ )
+ self.assertTrue(is_fsdp_ckpt)
+
+ logs_resume = self.run_cmd_and_get_logs(
+ use_accelerate, sharding_strategy, launcher, script, resume_args, output_dir
+ )
+
+ for log, log1 in zip(logs, logs_resume):
+ if "learning_rate" in log:
+ self.assertAlmostEqual(log["learning_rate"], log1["learning_rate"], delta=1e-5)
+
+ @require_torch_multi_accelerator
+ @run_first
+ @slow
+ def test_fsdp_cpu_offloading(self):
+ # TODO: This file is missing and should be added or the test should be removed
+ if not os.path.exists("utils/testing_scripts/fsdp_cpu_offloading.py"):
+ raise unittest.SkipTest("FSDP CPU offloading script not found!")
+
+ try:
+ subprocess.run(
+ "accelerate launch utils/testing_scripts/fsdp_cpu_offloading.py --config utils/testing_scripts/dummy_fsdp_config.yml",
+ shell=True,
+ check=True,
+ )
+ except: # noqa
+ raise AssertionError("CPU offloading failed with FSDP!")
+
+ def run_cmd_and_get_logs(self, use_accelerate, sharding_strategy, launcher, script, args, output_dir):
+ if not use_accelerate:
+ fsdp_args = [
+ "--fsdp",
+ f"{sharding_strategy} auto_wrap",
+ "--fsdp_transformer_layer_cls_to_wrap",
+ "BertLayer",
+ ]
+ cmd = launcher + script + args + fsdp_args
+ else:
+ fsdp_config = f"""
+ --fsdp_sharding_strategy {FSDP_SHARDING_STRATEGY.index(sharding_strategy.upper()) + 1}
+ """.split()
+ cmd = launcher + fsdp_config + script + args
+
+ # keep for quick debug
+ # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
+ execute_subprocess_async(cmd, env=self.get_env())
+ logs = TrainerState.load_from_json(os.path.join(output_dir, "trainer_state.json")).log_history
+ return logs
+
+ def get_base_args(self, output_dir, num_epochs, logging_steps):
+ return f"""
+ --model_name_or_path google-bert/bert-base-cased
+ --task_name mrpc
+ --output_dir {output_dir}
+ --overwrite_output_dir
+ --do_train
+ --max_seq_length 128
+ --per_device_train_batch_size 16
+ --learning_rate 5e-5
+ --num_train_epochs {num_epochs}
+ --lr_scheduler_type cosine
+ --logging_steps {logging_steps}
+ --save_strategy epoch
+ --do_eval
+ --eval_strategy epoch
+ --report_to none
+ """
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/generation/__init__.py b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_beam_constraints.py b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_beam_constraints.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae8a0c41eb950cb331ce3875219a26c562963df7
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_beam_constraints.py
@@ -0,0 +1,115 @@
+# coding=utf-8
+# Copyright 2020 The HuggingFace Team Inc.
+#
+# 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 clone 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 unittest
+
+from transformers import is_torch_available
+from transformers.testing_utils import require_torch
+
+
+if is_torch_available():
+ import torch
+
+ from transformers.generation import DisjunctiveConstraint
+
+
+@require_torch
+class ConstraintTest(unittest.TestCase):
+ def test_input_types(self):
+ # For consistency across different places the DisjunctiveConstraint is called,
+ # dc.token_ids is a list of integers. It is also initialized only by integers.
+
+ cset = [[1, 2, 4], [1, 2, 3, 4]]
+ dc = DisjunctiveConstraint(cset)
+ self.assertTrue(isinstance(dc.token_ids, list))
+
+ with self.assertRaises(ValueError):
+ DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]]))
+
+ with self.assertRaises(ValueError):
+ DisjunctiveConstraint([torch.LongTensor([1, 2, 4]), torch.LongTensor([1, 2, 3, 4, 5])])
+
+ def test_check_illegal_input(self):
+ # We can't have constraints that are complete subsets of another. This leads to a preverse
+ # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint?
+ # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially
+ # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm
+ # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it).
+ cset = [[1, 2], [1, 2, 3, 4]]
+
+ with self.assertRaises(ValueError):
+ DisjunctiveConstraint(cset) # fails here
+
+ def test_example_progression(self):
+ cset = [[1, 2, 3], [1, 2, 4]]
+
+ dc = DisjunctiveConstraint(cset)
+
+ stepped, completed, reset = dc.update(1)
+ desired = stepped is True and completed is False and reset is False
+ self.assertTrue(desired)
+ self.assertTrue(not dc.completed)
+ self.assertTrue(dc.current_seq == [1])
+
+ stepped, completed, reset = dc.update(2)
+ desired = stepped is True and completed is False and reset is False
+ self.assertTrue(desired)
+ self.assertTrue(not dc.completed)
+ self.assertTrue(dc.current_seq == [1, 2])
+
+ stepped, completed, reset = dc.update(3)
+ desired = stepped is True and completed is True and reset is False
+ self.assertTrue(desired)
+ self.assertTrue(dc.completed) # Completed!
+ self.assertTrue(dc.current_seq == [1, 2, 3])
+
+ def test_example_progression_unequal_three_mid_and_reset(self):
+ cset = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]]
+
+ dc = DisjunctiveConstraint(cset)
+
+ stepped, completed, reset = dc.update(1)
+ self.assertTrue(not dc.completed)
+ self.assertTrue(dc.current_seq == [1])
+
+ stepped, completed, reset = dc.update(2)
+ self.assertTrue(not dc.completed)
+ self.assertTrue(dc.current_seq == [1, 2])
+
+ stepped, completed, reset = dc.update(4)
+ self.assertTrue(not dc.completed)
+ self.assertTrue(dc.current_seq == [1, 2, 4])
+
+ stepped, completed, reset = dc.update(5)
+ self.assertTrue(dc.completed) # Completed!
+ self.assertTrue(dc.current_seq == [1, 2, 4, 5])
+
+ dc.reset()
+
+ stepped, completed, reset = dc.update(1)
+ self.assertTrue(not dc.completed)
+ self.assertTrue(dc.remaining() == 3)
+ self.assertTrue(dc.current_seq == [1])
+
+ stepped, completed, reset = dc.update(2)
+ self.assertTrue(not dc.completed)
+ self.assertTrue(dc.remaining() == 2)
+ self.assertTrue(dc.current_seq == [1, 2])
+
+ stepped, completed, reset = dc.update(5)
+ self.assertTrue(dc.completed) # Completed!
+ self.assertTrue(dc.remaining() == 0)
+ self.assertTrue(dc.current_seq == [1, 2, 5])
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_beam_search.py b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_beam_search.py
new file mode 100644
index 0000000000000000000000000000000000000000..47d3b4b38a7b5a22e3edf28847607e0d4f44e8bf
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_beam_search.py
@@ -0,0 +1,577 @@
+# coding=utf-8
+# Copyright 2020 The HuggingFace Team Inc.
+#
+# 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 clone 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 unittest
+
+from transformers import is_torch_available
+from transformers.testing_utils import require_torch, torch_device
+
+from ..test_modeling_common import floats_tensor, ids_tensor
+
+
+if is_torch_available():
+ import torch
+
+ from transformers.generation import (
+ BeamHypotheses,
+ BeamSearchScorer,
+ ConstrainedBeamSearchScorer,
+ DisjunctiveConstraint,
+ PhrasalConstraint,
+ )
+
+
+class BeamSearchTester:
+ def __init__(
+ self,
+ parent,
+ batch_size=3,
+ sequence_length=10,
+ vocab_size=99,
+ pad_token_id=0,
+ max_length=20,
+ num_beams=4,
+ length_penalty=2.0,
+ do_early_stopping=True,
+ num_beam_hyps_to_keep=2,
+ ):
+ self.parent = parent
+ self.batch_size = batch_size
+ self.sequence_length = sequence_length
+ self.vocab_size = vocab_size
+ self.pad_token_id = pad_token_id
+ self.max_length = max_length
+ self.num_beams = num_beams
+ self.length_penalty = length_penalty
+ self.do_early_stopping = do_early_stopping
+ self.num_beam_hyps_to_keep = num_beam_hyps_to_keep
+
+ # cannot be randomly generated
+ self.eos_token_id = vocab_size + 1
+
+ def prepare_beam_scorer(self, **kwargs):
+ return BeamSearchScorer(
+ batch_size=kwargs.get("batch_size", self.batch_size),
+ num_beams=kwargs.get("num_beams", self.num_beams),
+ device=torch_device,
+ length_penalty=kwargs.get("length_penalty", self.length_penalty),
+ do_early_stopping=kwargs.get("do_early_stopping", self.do_early_stopping),
+ num_beam_hyps_to_keep=kwargs.get("num_beam_hyps_to_keep", self.num_beam_hyps_to_keep),
+ )
+
+ def prepare_inputs(self):
+ input_ids = ids_tensor((self.batch_size * self.num_beams, self.sequence_length), self.vocab_size)
+ next_tokens = ids_tensor((self.batch_size, 2 * self.num_beams), self.vocab_size).to(torch_device)
+ next_indices = ids_tensor((self.batch_size, 2 * self.num_beams), self.num_beams).to(torch_device)
+ next_scores, _ = (-floats_tensor((self.batch_size, 2 * self.num_beams)).to(torch_device)).sort(descending=True)
+ return (input_ids, next_tokens, next_indices, next_scores)
+
+ def check_beam_hypotheses(self, input_ids, *args):
+ # check that correct number of beam hypotheses is set in beam scorer
+ beam_scorer = self.prepare_beam_scorer(do_early_stopping=True)
+ beam_hyp = beam_scorer._beam_hyps[0]
+
+ self.parent.assertEqual(len(beam_scorer._beam_hyps), self.batch_size)
+
+ # check correct type
+ self.parent.assertTrue(isinstance(beam_hyp, BeamHypotheses))
+
+ # check that num_beams is correctly set
+ self.parent.assertEqual(beam_hyp.num_beams, self.num_beams)
+
+ # check for early stopping deactivated
+ for beam_idx in range(self.num_beams):
+ beam_hyp.add(input_ids[beam_idx], -10.0)
+
+ # if early stopping True -> score does not matter
+ self.parent.assertTrue(beam_hyp.is_done(-10.0, 5))
+
+ # re-init
+ beam_scorer = self.prepare_beam_scorer(do_early_stopping=False)
+ beam_hyp = beam_scorer._beam_hyps[0]
+
+ # add `num_beams + 1` beams to change `worst_score`
+ for beam_idx in range(self.num_beams + 1):
+ beam_hyp.add(input_ids[beam_idx], -10.0 + float(beam_idx))
+
+ # -10.0 is removed => -9.0 is worst score
+ self.parent.assertAlmostEqual(beam_hyp.worst_score, -9.0 / (self.sequence_length**beam_hyp.length_penalty))
+
+ # -5.0 is better than worst score => should not be finished
+ self.parent.assertFalse(beam_hyp.is_done(-5.0, self.sequence_length))
+
+ # -20.0 is worse than worst score => should be finished
+ self.parent.assertTrue(beam_hyp.is_done(-20.0, self.sequence_length))
+
+ def check_beam_scorer_update(self, input_ids, next_tokens, next_indices, next_scores):
+ # check too many eos tokens
+ beam_scorer = self.prepare_beam_scorer()
+
+ tokens = next_tokens.clone()
+ tokens[0, :] = self.eos_token_id
+
+ with self.parent.assertRaises(ValueError):
+ beam_scorer.process(input_ids, next_scores, tokens, next_indices, eos_token_id=self.eos_token_id)
+
+ # check all batches are done
+ beam_scorer = self.prepare_beam_scorer()
+
+ tokens = next_tokens.clone()
+ tokens[:, : self.num_beams] = self.eos_token_id
+ beam_indices = torch.zeros_like(input_ids) + torch.arange(input_ids.shape[-1], device=input_ids.device)
+ beam_indices = tuple(tuple(b) for b in beam_indices)
+ beam_scorer.process(
+ input_ids, next_scores, tokens, next_indices, eos_token_id=self.eos_token_id, beam_indices=beam_indices
+ )
+ # beam scorer should be done
+ self.parent.assertTrue(beam_scorer.is_done)
+
+ # check
+ beam_scorer = self.prepare_beam_scorer()
+
+ tokens = next_tokens.clone()
+ tokens[:, 1] = self.eos_token_id
+ beam_outputs = beam_scorer.process(
+ input_ids, next_scores, tokens, next_indices, eos_token_id=self.eos_token_id, beam_indices=beam_indices
+ )
+ output_scores = beam_outputs["next_beam_scores"]
+ output_tokens = beam_outputs["next_beam_tokens"]
+ output_indices = beam_outputs["next_beam_indices"]
+
+ def cut_expected_tensor(tensor):
+ return torch.cat([tensor[:, :1], tensor[:, 2 : self.num_beams + 1]], dim=1).flatten()
+
+ # check all outptus
+ # cut out id of eos token and take best `num_beams` outputs
+ expected_output_tokens = cut_expected_tensor(tokens)
+ expected_output_scores = cut_expected_tensor(next_scores)
+
+ # add num_beams * batch_idx
+ offset = torch.div(
+ torch.arange(self.num_beams * self.batch_size, device=torch_device), self.num_beams, rounding_mode="floor"
+ )
+ expected_output_indices = cut_expected_tensor(next_indices) + offset * self.num_beams
+
+ self.parent.assertListEqual(expected_output_tokens.tolist(), output_tokens.tolist())
+ self.parent.assertListEqual(expected_output_indices.tolist(), output_indices.tolist())
+ self.parent.assertTrue(torch.allclose(expected_output_scores, output_scores, atol=1e-3))
+
+ # make sure ids of eos token are correctly saved in beam_hyps of beam scorer
+ expected_beam_indices = list(range(10))
+ for batch_idx in range(self.batch_size):
+ correct_idx = batch_idx * self.num_beams + next_indices[batch_idx, 1]
+ self.parent.assertListEqual(
+ input_ids[correct_idx].tolist(), beam_scorer._beam_hyps[batch_idx].beams[0][1].tolist()
+ )
+ self.parent.assertListEqual(
+ expected_beam_indices + [correct_idx],
+ torch.tensor(beam_scorer._beam_hyps[batch_idx].beams[0][2]).tolist(),
+ )
+
+ def check_beam_scores_finalize(self, input_ids, next_tokens, next_indices, next_scores):
+ # max_length should be only one more than current input_ids to check that eos is correctly appended
+ max_length = self.sequence_length + 1
+ beam_scorer = self.prepare_beam_scorer(num_beam_hyps_to_keep=1, length_penalty=1.0, do_early_stopping=False)
+
+ # update beams and append to input_ids
+ tokens = next_tokens.clone()
+ # first batch, first output has to finish with eos token id since scores are correctly sorted
+ tokens[0, 0] = self.eos_token_id
+ # make sure corresponding score is as good as possible to surely be picked first
+ next_scores[0, 0] = 0.0
+ beam_outputs = beam_scorer.process(
+ input_ids, next_scores, tokens, next_indices, eos_token_id=self.eos_token_id
+ )
+ output_scores = beam_outputs["next_beam_scores"]
+ output_tokens = beam_outputs["next_beam_tokens"]
+ output_indices = beam_outputs["next_beam_indices"]
+
+ input_ids = torch.cat([input_ids[output_indices, :], output_tokens.unsqueeze(-1)], dim=-1)
+
+ # finalize
+ beam_indices = torch.zeros_like(input_ids) + torch.arange(input_ids.shape[-1], device=input_ids.device)
+ beam_indices = tuple(tuple(b) for b in beam_indices)
+ sequence_output = beam_scorer.finalize(
+ input_ids,
+ output_scores,
+ output_tokens,
+ output_indices,
+ pad_token_id=self.pad_token_id,
+ eos_token_id=self.eos_token_id,
+ max_length=max_length,
+ beam_indices=beam_indices,
+ )
+
+ sequences = sequence_output["sequences"]
+ sequence_scores = sequence_output["sequence_scores"]
+
+ # since `num_beam_hyps_to_keep` = 1 => only return `batch_size` x `max_length`
+ self.parent.assertListEqual(list(sequences.shape), [self.batch_size, max_length])
+ self.parent.assertListEqual(list(sequence_scores.shape), [self.batch_size])
+
+ # check sequence_scores
+ self.parent.assertFalse((sequence_scores > 0).any().item())
+
+ # first batch has to finish with eos_token
+ self.parent.assertEqual(sequences[0, -1].item(), self.eos_token_id)
+
+ # other batches cannot finish with eos token
+ self.parent.assertNotEqual(sequences[1, -1].item(), self.eos_token_id)
+ self.parent.assertNotEqual(sequences[2, -1].item(), self.eos_token_id)
+
+ # now test that if `num_beam_hyps_to_keep` is 3 => all beams are returned
+ beam_scorer.num_beam_hyps_to_keep = self.num_beams
+ sequence_output = beam_scorer.finalize(
+ input_ids,
+ output_scores,
+ output_tokens,
+ output_indices,
+ pad_token_id=self.pad_token_id,
+ eos_token_id=self.eos_token_id,
+ max_length=max_length,
+ beam_indices=beam_indices,
+ )
+ sequences = sequence_output["sequences"]
+ sequence_scores = sequence_output["sequence_scores"]
+
+ self.parent.assertListEqual(list(sequences.shape), [self.num_beams * self.batch_size, max_length])
+ self.parent.assertListEqual(list(sequence_scores.shape), [self.num_beams * self.batch_size])
+
+
+class ConstrainedBeamSearchTester:
+ def __init__(
+ self,
+ parent,
+ constraints=None,
+ batch_size=3,
+ sequence_length=10,
+ vocab_size=99,
+ pad_token_id=0,
+ max_length=20,
+ num_beams=4,
+ length_penalty=2.0,
+ do_early_stopping=True,
+ num_beam_hyps_to_keep=2,
+ ):
+ self.parent = parent
+ self.batch_size = batch_size
+ self.sequence_length = sequence_length
+ self.vocab_size = vocab_size
+ self.pad_token_id = pad_token_id
+ self.max_length = max_length
+ self.num_beams = num_beams
+ self.length_penalty = length_penalty
+ self.do_early_stopping = do_early_stopping
+ self.num_beam_hyps_to_keep = num_beam_hyps_to_keep
+
+ if constraints is None:
+ force_tokens = torch.randint(10, 50, (1, 2))[0].tolist()
+ disjunctive_tokens = torch.randint(10, 50, (2, 2)).tolist()
+
+ constraints = [PhrasalConstraint(force_tokens), DisjunctiveConstraint(disjunctive_tokens)]
+ self.constraints = constraints
+ # cannot be randomly generated
+ self.eos_token_id = vocab_size + 1
+
+ def prepare_constrained_beam_scorer(self, **kwargs):
+ return ConstrainedBeamSearchScorer(
+ constraints=kwargs.get("constraints", self.constraints),
+ batch_size=kwargs.get("batch_size", self.batch_size),
+ num_beams=kwargs.get("num_beams", self.num_beams),
+ device=torch_device,
+ length_penalty=kwargs.get("length_penalty", self.length_penalty),
+ do_early_stopping=kwargs.get("do_early_stopping", self.do_early_stopping),
+ num_beam_hyps_to_keep=kwargs.get("num_beam_hyps_to_keep", self.num_beam_hyps_to_keep),
+ )
+
+ def prepare_inputs(self):
+ input_ids = ids_tensor((self.batch_size * self.num_beams, self.sequence_length), self.vocab_size)
+ next_tokens = ids_tensor((self.batch_size, 2 * self.num_beams), self.vocab_size).to(torch_device)
+ next_indices = ids_tensor((self.batch_size, 2 * self.num_beams), self.num_beams).to(torch_device)
+ next_scores, _ = (-floats_tensor((self.batch_size, 2 * self.num_beams)).to(torch_device)).sort(descending=True)
+ scores_for_all_vocab, _ = (
+ -floats_tensor((self.batch_size * self.num_beams, self.vocab_size)).to(torch_device)
+ ).sort(descending=True)
+ return (input_ids, next_tokens, next_indices, next_scores, scores_for_all_vocab)
+
+ def check_beam_hypotheses(self, input_ids, *args):
+ # check that correct number of beam hypotheses is set in beam scorer
+ constrained_beam_scorer = self.prepare_constrained_beam_scorer(do_early_stopping=True)
+ beam_hyp = constrained_beam_scorer._beam_hyps[0]
+
+ self.parent.assertEqual(len(constrained_beam_scorer._beam_hyps), self.batch_size)
+
+ # check correct type
+ self.parent.assertTrue(isinstance(beam_hyp, BeamHypotheses))
+
+ # check that num_beams is correctly set
+ self.parent.assertEqual(beam_hyp.num_beams, self.num_beams)
+
+ # check for early stopping deactivated
+ for beam_idx in range(self.num_beams):
+ beam_hyp.add(input_ids[beam_idx], -10.0)
+
+ # if early stopping True -> score does not matter
+ self.parent.assertTrue(beam_hyp.is_done(-10.0, 5))
+
+ # re-init
+ constrained_beam_scorer = self.prepare_constrained_beam_scorer(do_early_stopping=False)
+ beam_hyp = constrained_beam_scorer._beam_hyps[0]
+
+ # add `num_beams + 1` beams to change `worst_score`
+ for beam_idx in range(self.num_beams + 1):
+ beam_hyp.add(input_ids[beam_idx], -10.0 + float(beam_idx))
+
+ # -10.0 is removed => -9.0 is worst score
+ self.parent.assertAlmostEqual(beam_hyp.worst_score, -9.0 / (self.sequence_length**beam_hyp.length_penalty))
+
+ # -5.0 is better than worst score => should not be finished
+ self.parent.assertFalse(beam_hyp.is_done(-5.0, self.sequence_length))
+
+ # -20.0 is worse than worst score => should be finished
+ self.parent.assertTrue(beam_hyp.is_done(-20.0, self.sequence_length))
+
+ def check_constrained_beam_scorer_update(
+ self, input_ids, next_tokens, next_indices, next_scores, scores_for_all_vocab
+ ):
+ # check too many eos tokens
+ constrained_beam_scorer = self.prepare_constrained_beam_scorer()
+ stacked_token_ids = []
+ for constraint in self.constraints:
+ token_ids = constraint.token_ids
+ token_ids = token_ids[0] if isinstance(token_ids[0], list) else token_ids
+ stacked_token_ids = stacked_token_ids + token_ids
+
+ fulfilling_sequence = torch.LongTensor(stacked_token_ids)
+ fulfill_len = fulfilling_sequence.size(0)
+ input_ids[:, :fulfill_len] = fulfilling_sequence
+
+ tokens = next_tokens.clone()
+ tokens[0, :] = self.eos_token_id
+
+ with self.parent.assertRaises(ValueError):
+ constrained_beam_scorer.process(
+ input_ids, next_scores, tokens, next_indices, scores_for_all_vocab, eos_token_id=self.eos_token_id
+ )
+
+ # check all batches are done
+ constrained_beam_scorer = self.prepare_constrained_beam_scorer()
+
+ tokens = next_tokens.clone()
+ tokens[:, : self.num_beams] = self.eos_token_id
+ constrained_beam_scorer.process(
+ input_ids, next_scores, tokens, next_indices, scores_for_all_vocab, eos_token_id=self.eos_token_id
+ )
+ # beam scorer should be done
+ self.parent.assertTrue(constrained_beam_scorer.is_done)
+
+ # check
+ constrained_beam_scorer = self.prepare_constrained_beam_scorer()
+
+ tokens = next_tokens.clone()
+ tokens[:, 1] = self.eos_token_id
+ beam_outputs = constrained_beam_scorer.process(
+ input_ids, next_scores, tokens, next_indices, scores_for_all_vocab, eos_token_id=self.eos_token_id
+ )
+ output_scores = beam_outputs["next_beam_scores"]
+ output_tokens = beam_outputs["next_beam_tokens"]
+ output_indices = beam_outputs["next_beam_indices"]
+
+ def cut_expected_tensor(tensor):
+ return torch.cat([tensor[:, :1], tensor[:, 2 : self.num_beams + 1]], dim=1).flatten()
+
+ # check all outptus
+ # cut out id of eos token and take best `num_beams` outputs
+ expected_output_tokens = cut_expected_tensor(tokens)
+ expected_output_scores = cut_expected_tensor(next_scores)
+
+ # add num_beams * batch_idx
+ offset = torch.div(
+ torch.arange(self.num_beams * self.batch_size, device=torch_device), self.num_beams, rounding_mode="floor"
+ )
+ expected_output_indices = cut_expected_tensor(next_indices) + offset * self.num_beams
+
+ self.parent.assertListEqual(expected_output_tokens.tolist(), output_tokens.tolist())
+ self.parent.assertListEqual(expected_output_indices.tolist(), output_indices.tolist())
+ self.parent.assertTrue(torch.allclose(expected_output_scores, output_scores, atol=1e-3))
+
+ # make sure ids of eos token are correctly saved in beam_hyps of beam scorer
+ for batch_idx in range(self.batch_size):
+ correct_idx = batch_idx * self.num_beams + next_indices[batch_idx, 1]
+ self.parent.assertListEqual(
+ input_ids[correct_idx].tolist(), constrained_beam_scorer._beam_hyps[batch_idx].beams[0][1].tolist()
+ )
+
+ def check_constrained_beam_scorer_finalize(
+ self, input_ids, next_tokens, next_indices, next_scores, scores_for_all_vocab
+ ):
+ # max_length should be only one more than current input_ids to check that eos is correctly appended
+ max_length = self.sequence_length + 1
+
+ # for testing finalize, we do want to have fulfilled constraints
+ stacked_token_ids = []
+ for constraint in self.constraints:
+ token_ids = constraint.token_ids
+ token_ids = token_ids[0] if isinstance(token_ids[0], list) else token_ids
+ stacked_token_ids = stacked_token_ids + token_ids
+
+ fulfilling_sequence = torch.LongTensor(stacked_token_ids)
+
+ fulfill_len = fulfilling_sequence.size(0)
+ input_ids[:, :fulfill_len] = fulfilling_sequence
+
+ constrained_beam_scorer = self.prepare_constrained_beam_scorer(
+ num_beam_hyps_to_keep=1, length_penalty=1.0, do_early_stopping=False
+ )
+
+ constraints = constrained_beam_scorer.constraints
+ # update beams and append to input_ids
+ tokens = next_tokens.clone()
+ # first batch, first output has to finish with eos token id since scores are correctly sorted
+ tokens[0, 0] = self.eos_token_id
+ # make sure corresponding score is as good as possible to surely be picked first
+ next_scores[0, 0] = 0.0
+
+ beam_outputs = constrained_beam_scorer.process(
+ input_ids, next_scores, tokens, next_indices, scores_for_all_vocab, eos_token_id=self.eos_token_id
+ )
+ output_scores = beam_outputs["next_beam_scores"]
+ output_tokens = beam_outputs["next_beam_tokens"]
+ output_indices = beam_outputs["next_beam_indices"]
+ input_ids = torch.cat([input_ids[output_indices, :], output_tokens.unsqueeze(-1)], dim=-1)
+
+ # finalize
+ sequence_output = constrained_beam_scorer.finalize(
+ input_ids,
+ output_scores,
+ output_tokens,
+ output_indices,
+ pad_token_id=self.pad_token_id,
+ eos_token_id=self.eos_token_id,
+ max_length=max_length,
+ )
+
+ sequences = sequence_output["sequences"]
+ sequence_scores = sequence_output["sequence_scores"]
+
+ # since `num_beam_hyps_to_keep` = 1 => only return `batch_size` x `max_length`
+ self.parent.assertListEqual(list(sequences.shape), [self.batch_size, max_length])
+ self.parent.assertListEqual(list(sequence_scores.shape), [self.batch_size])
+
+ # check sequence_scores
+ self.parent.assertFalse((sequence_scores > 0).any().item())
+
+ # first batch has to finish with eos_token
+ self.parent.assertEqual(sequences[0, -1].item(), self.eos_token_id)
+
+ # other batches cannot finish with eos token
+ self.parent.assertNotEqual(sequences[1, -1].item(), self.eos_token_id)
+ self.parent.assertNotEqual(sequences[2, -1].item(), self.eos_token_id)
+
+ # test that the constraint is indeed fulfilled
+ for output, constraint in [(s, c) for s in sequences for c in constraints]:
+ forced_token_ids = constraint.token_ids
+ if isinstance(forced_token_ids[0], list):
+ # disjunctive case
+ flag = False
+ for token_ids in forced_token_ids:
+ if self._check_sequence_inside_sequence(output, token_ids):
+ flag = True
+ break
+ self.parent.assertEqual(flag, True)
+ else:
+ self.parent.assertEqual(self._check_sequence_inside_sequence(output, forced_token_ids), True)
+
+ # now test that if `num_beam_hyps_to_keep` is 3 => all beams are returned
+
+ # constrained_beam_scorer.num_beam_hyps_to_keep = self.num_beams
+ constrained_beam_scorer = self.prepare_constrained_beam_scorer(
+ num_beam_hyps_to_keep=self.num_beams, length_penalty=1.0, do_early_stopping=False
+ )
+
+ sequence_output = constrained_beam_scorer.finalize(
+ input_ids,
+ output_scores,
+ output_tokens,
+ output_indices,
+ pad_token_id=self.pad_token_id,
+ eos_token_id=self.eos_token_id,
+ max_length=max_length,
+ )
+ sequences = sequence_output["sequences"]
+ sequence_scores = sequence_output["sequence_scores"]
+
+ self.parent.assertListEqual(list(sequences.shape), [self.num_beams * self.batch_size, max_length])
+ self.parent.assertListEqual(list(sequence_scores.shape), [self.num_beams * self.batch_size])
+
+ def _check_sequence_inside_sequence(self, tensor_1, tensor_2):
+ # check if tensor_1 inside tensor_2 or tensor_2 inside tensor_1.
+ # set to same device. we don't care what device.
+
+ if not isinstance(tensor_1, list):
+ tensor_1 = tensor_1.cpu().tolist()
+ if not isinstance(tensor_2, list):
+ tensor_2 = tensor_2.cpu().tolist()
+
+ in_order = len(tensor_1) <= len(tensor_2)
+ longer = tensor_2 if in_order else tensor_1
+ shorter = tensor_1 if in_order else tensor_2
+
+ flag = False
+ chunk_size = len(shorter)
+ for chunk_idx in range(len(longer) - chunk_size + 1):
+ subseq = longer[chunk_idx : chunk_idx + chunk_size]
+ if subseq == shorter:
+ flag = True
+ break
+
+ return flag
+
+
+@require_torch
+class BeamSearchTest(unittest.TestCase):
+ def setUp(self):
+ self.beam_search_tester = BeamSearchTester(self)
+
+ def test_beam_hypotheses(self):
+ inputs = self.beam_search_tester.prepare_inputs()
+ self.beam_search_tester.check_beam_hypotheses(*inputs)
+
+ def test_beam_scorer_update(self):
+ inputs = self.beam_search_tester.prepare_inputs()
+ self.beam_search_tester.check_beam_scorer_update(*inputs)
+
+ def test_beam_scorer_finalize(self):
+ inputs = self.beam_search_tester.prepare_inputs()
+ self.beam_search_tester.check_beam_scores_finalize(*inputs)
+
+
+@require_torch
+class ConstrainedBeamSearchTest(unittest.TestCase):
+ def setUp(self):
+ self.constrained_beam_search_tester = ConstrainedBeamSearchTester(self)
+
+ def test_constrained_beam_hypotheses(self):
+ inputs = self.constrained_beam_search_tester.prepare_inputs()
+ self.constrained_beam_search_tester.check_beam_hypotheses(*inputs)
+
+ def test_constrained_beam_scorer_update(self):
+ inputs = self.constrained_beam_search_tester.prepare_inputs()
+ self.constrained_beam_search_tester.check_constrained_beam_scorer_update(*inputs)
+
+ def test_constrained_beam_scorer_finalize(self):
+ inputs = self.constrained_beam_search_tester.prepare_inputs()
+ self.constrained_beam_search_tester.check_constrained_beam_scorer_finalize(*inputs)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_candidate_generator.py b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_candidate_generator.py
new file mode 100644
index 0000000000000000000000000000000000000000..38df48ab08d2c42efbaac25c651a3a33d198a046
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_candidate_generator.py
@@ -0,0 +1,325 @@
+import gc
+import unittest
+import weakref
+from unittest.mock import MagicMock
+
+import torch
+
+from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, GenerationConfig, pipeline
+from transformers.generation.candidate_generator import (
+ AssistantToTargetTranslator,
+ AssistantVocabTranslatorCache,
+ UniversalSpeculativeDecodingGenerator,
+)
+from transformers.testing_utils import require_torch, torch_device
+
+
+@require_torch
+class TestAssistantToTargetTranslator(unittest.TestCase):
+ def setUp(self):
+ # Create mock tokenizers with predefined vocabularies
+ self.target_tokenizer = MagicMock()
+ self.assistant_tokenizer = MagicMock()
+
+ # Define mock vocabularies for the tokenizers
+ self.target_vocab = {"hello": 0, "world": 1, "foo": 2, "bar": 3}
+ self.assistant_vocab = {"hello": 0, "world": 1, "foo": 2, "baz": 4}
+
+ self.target_tokenizer.get_vocab.return_value = self.target_vocab
+ self.assistant_tokenizer.get_vocab.return_value = self.assistant_vocab
+ self.assistant_model_device = torch_device
+ self.target_vocab_size = 6
+
+ # Instantiate the class under test
+ self.translator = AssistantToTargetTranslator(
+ target_tokenizer=self.target_tokenizer,
+ assistant_tokenizer=self.assistant_tokenizer,
+ assistant_model_device=self.assistant_model_device,
+ target_vocab_size=self.target_vocab_size,
+ )
+
+ def test_get_assistant_to_target_input_ids(self):
+ """Test the mapping from assistant tokens to target tokens."""
+ expected_mapping = [0, 1, 2, self.translator.SUPPRESS_TOKEN_ID, self.translator.SUPPRESS_TOKEN_ID]
+ actual_mapping = self.translator._assistant_to_target_input_ids.tolist()
+ self.assertEqual(actual_mapping, expected_mapping)
+
+ def test_get_suppress_input_ids(self):
+ """Test the suppression of assistant input IDs not present in the target vocabulary."""
+ expected_suppress_ids = [3, 4]
+ actual_suppress_ids = self.translator._get_suppress_input_ids().tolist()
+ self.assertEqual(actual_suppress_ids, expected_suppress_ids)
+
+ def test_get_target_ids(self):
+ """Test the translation of assistant candidate IDs to target candidate IDs."""
+ assistant_input_ids = torch.LongTensor([[0, 1, 2]]).to(
+ self.assistant_model_device
+ ) # 'hello world foo' in assistant tokenizer
+ target_input_ids = torch.LongTensor([[0, 1, 2]]).to(
+ self.assistant_model_device
+ ) # 'hello world foo' in target tokenizer
+ assistant_candidate_ids = torch.LongTensor([[0, 1, 2, 4]]).to(
+ self.assistant_model_device
+ ) # 'hello world foo baz' in assistant tokenizer
+
+ expected_target_ids = torch.LongTensor(
+ [[0, 1, 2, self.translator.SUPPRESS_TOKEN_ID]]
+ ).to(
+ self.assistant_model_device
+ ) # 'hello world foo baz' in target tokenizer (baz is mapped to self.translator.suppress_tokens_id since it does not exist in target vocab)
+
+ actual_target_ids = self.translator.get_target_ids(
+ assistant_input_ids, target_input_ids, assistant_candidate_ids
+ )
+ self.assertTrue(torch.equal(actual_target_ids, expected_target_ids))
+
+ def test_get_target_logits(self):
+ """Test the conversion of assistant logits to target logits."""
+ # Assistant logits for IDs 0, 1, 2
+ assistant_logits = torch.FloatTensor([[[0.1, 0.2, 0.3, 0.4, self.translator.FILTER_VALUE]]]).to(
+ self.assistant_model_device
+ ) # Shape (1, 1, 5)
+
+ # Expected target logits (target_vocab_size = 4)
+ expected_target_logits = torch.full((1, 1, self.target_vocab_size), self.translator.FILTER_VALUE).to(
+ self.assistant_model_device
+ )
+ expected_target_logits[0, 0, 0] = 0.1 # 'hello'
+ expected_target_logits[0, 0, 1] = 0.2 # 'world'
+ expected_target_logits[0, 0, 2] = 0.3 # 'foo'
+ # The 'bar' token in target vocab remains at -inf
+
+ actual_target_logits = self.translator.get_target_logits(assistant_logits)
+ self.assertTrue(torch.equal(actual_target_logits, expected_target_logits))
+
+
+class MockTokenizer:
+ """A simple mock tokenizer class that supports weak references."""
+
+ def __init__(self, vocab=None):
+ self._vocab = vocab or {}
+
+ def get_vocab(self):
+ return self._vocab
+
+ def __call__(self, text, add_special_tokens=True):
+ # Mock implementation of the __call__ method
+ tokens = text.split()
+ input_ids = [self._vocab.get(token, 0) for token in tokens]
+ return {"input_ids": input_ids}
+
+
+@require_torch
+class TestAssistantVocabTranslatorCache(unittest.TestCase):
+ def setUp(self):
+ # Clear the cache before each test
+ AssistantVocabTranslatorCache._cache.clear()
+ # Create mock tokenizers with different vocabularies
+ self.target_tokenizer = MockTokenizer({"hello": 0, "world": 1})
+ self.assistant_tokenizer = MockTokenizer({"hello": 0, "world": 1, "foo": 2})
+ self.other_target_tokenizer = MockTokenizer({"foo": 2, "bar": 3})
+ self.other_assistant_tokenizer = MockTokenizer({"baz": 4, "qux": 5})
+ self.assistant_model_device = torch_device
+ self.target_vocab_size = 6
+
+ def test_same_instance_for_same_tokenizers(self):
+ """Test that the same translator is returned for the same tokenizers."""
+ translator1 = AssistantVocabTranslatorCache.get_translator(
+ self.target_tokenizer,
+ self.assistant_tokenizer,
+ assistant_model_device=self.assistant_model_device,
+ target_vocab_size=self.target_vocab_size,
+ )
+ translator2 = AssistantVocabTranslatorCache.get_translator(
+ self.target_tokenizer,
+ self.assistant_tokenizer,
+ assistant_model_device=self.assistant_model_device,
+ target_vocab_size=self.target_vocab_size,
+ )
+ self.assertIs(translator1, translator2, "Translators should be cached and identical")
+
+ def test_different_instances_for_different_tokenizers(self):
+ """Test that different tokenizers produce different translators."""
+ translator1 = AssistantVocabTranslatorCache.get_translator(
+ self.target_tokenizer,
+ self.assistant_tokenizer,
+ assistant_model_device=self.assistant_model_device,
+ target_vocab_size=self.target_vocab_size,
+ )
+ translator2 = AssistantVocabTranslatorCache.get_translator(
+ self.other_target_tokenizer,
+ self.other_assistant_tokenizer,
+ assistant_model_device=self.assistant_model_device,
+ target_vocab_size=self.target_vocab_size,
+ )
+ self.assertIsNot(translator1, translator2, "Translators should differ for different tokenizers")
+
+ def test_cache_with_weakref_key(self):
+ """Ensure that the cache uses weak references as keys."""
+ initial_cache_size = len(AssistantVocabTranslatorCache._cache)
+ target_tokenizer = MockTokenizer({"hello": 0})
+ assistant_tokenizer = MockTokenizer({"hello": 0})
+
+ # Store translator in a local variable to avoid it being kept alive
+ translator = AssistantVocabTranslatorCache.get_translator(
+ target_tokenizer,
+ assistant_tokenizer,
+ assistant_model_device=self.assistant_model_device,
+ target_vocab_size=self.target_vocab_size,
+ )
+ self.assertEqual(len(AssistantVocabTranslatorCache._cache), initial_cache_size + 1)
+
+ # Delete all strong references
+ del target_tokenizer
+ del assistant_tokenizer
+ del translator
+
+ # Force garbage collection
+ gc.collect()
+
+ # Call cleanup to remove dead entries
+ AssistantVocabTranslatorCache.cleanup()
+
+ # The cache size remains increased due to strong references
+ self.assertEqual(len(AssistantVocabTranslatorCache._cache), initial_cache_size + 1)
+
+ def test_weakref_cache_cleanup(self):
+ """Test that the cache cleans up translators when tokenizers are garbage collected."""
+
+ def create_translator():
+ target_tokenizer = MockTokenizer({"hello": 0})
+ assistant_tokenizer = MockTokenizer({"hello": 0})
+ translator = AssistantVocabTranslatorCache.get_translator(
+ target_tokenizer,
+ assistant_tokenizer,
+ assistant_model_device=self.assistant_model_device,
+ target_vocab_size=self.target_vocab_size,
+ )
+ # Create weak references before returning
+ refs = (weakref.ref(translator), weakref.ref(target_tokenizer), weakref.ref(assistant_tokenizer))
+ # Remove strong references inside the function
+ del target_tokenizer
+ del assistant_tokenizer
+ del translator
+ return refs
+
+ translator_ref, target_ref, assistant_ref = create_translator()
+
+ # Force garbage collection
+ gc.collect()
+
+ # Call cleanup to remove dead entries
+ AssistantVocabTranslatorCache.cleanup()
+
+ # The tokenizers and translator are not garbage collected due to strong references
+ self.assertIsNotNone(target_ref(), "Target tokenizer should still be alive due to strong references")
+ self.assertIsNotNone(assistant_ref(), "Assistant tokenizer should still be alive due to strong references")
+ self.assertIsNotNone(translator_ref(), "Translator should still be alive due to strong references")
+
+
+@require_torch
+class TestUniversalSpeculativeDecoding(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.target_name = "hf-internal-testing/tiny-random-LlamaForCausalLM"
+ cls.assistant_name = "hf-internal-testing/tiny-random-PhiForCausalLM"
+
+ def setUp(self):
+ self.target_tokenizer = AutoTokenizer.from_pretrained(self.target_name)
+ self.target_config = AutoConfig.from_pretrained(self.target_name)
+ self.assistant_model = AutoModelForCausalLM.from_pretrained(self.assistant_name).to(torch_device)
+ self.assistant_tokenizer = AutoTokenizer.from_pretrained(self.assistant_name)
+
+ self.generation_config = GenerationConfig()
+
+ # Ensure required tokens exist
+ if self.target_tokenizer.pad_token_id is None:
+ self.target_tokenizer.pad_token_id = self.target_tokenizer.eos_token_id
+ if self.target_tokenizer.bos_token_id is None:
+ self.target_tokenizer.bos_token_id = self.target_tokenizer.eos_token_id
+ if self.assistant_tokenizer.pad_token_id is None:
+ self.assistant_tokenizer.pad_token_id = self.assistant_tokenizer.eos_token_id
+ if self.target_tokenizer.bos_token_id is None:
+ self.assistant_tokenizer.bos_token_id = self.assistant_tokenizer.eos_token_id
+
+ self.input_ids = torch.tensor([[1, 2, 3]]).to(torch_device)
+ self.model_kwargs = {
+ "attention_mask": torch.ones_like(self.input_ids).to(torch_device),
+ }
+
+ atm_translator = AssistantVocabTranslatorCache.get_translator(
+ self.target_tokenizer, self.assistant_tokenizer, self.target_config.vocab_size, torch_device
+ )
+ self.generator = UniversalSpeculativeDecodingGenerator(
+ input_ids=self.input_ids,
+ assistant_model=self.assistant_model,
+ target_tokenizer=self.target_tokenizer,
+ assistant_tokenizer=self.assistant_tokenizer,
+ generation_config=self.generation_config,
+ model_kwargs=self.model_kwargs,
+ atm_translator=atm_translator,
+ )
+
+ def test_basic_generation(self):
+ """Test basic speculative decoding works"""
+ input_text = "The quick brown fox"
+ input_ids = self.target_tokenizer.encode(input_text, return_tensors="pt")
+ self.generator.input_ids = input_ids
+ candidates, scores = self.generator.get_candidates(input_ids)
+
+ self.assertIsNotNone(candidates)
+ self.assertIsNotNone(scores)
+ self.assertTrue(torch.is_tensor(candidates))
+ self.assertTrue(torch.is_tensor(scores))
+
+ def test_mismatched_vocabularies(self):
+ """Test handling of mismatched vocabularies between models"""
+ # Create input with tokens present in main but not assistant vocab
+ # Find a token that is not in the assistant tokenizer but in
+ # the main tokenizer.
+ missing_token = next(
+ token
+ for token in self.target_tokenizer.get_vocab()
+ if token not in self.assistant_tokenizer.get_vocab()
+ and token not in self.target_tokenizer.all_special_tokens
+ and "reserved_" not in token
+ )
+ input_ids = torch.tensor([[self.target_tokenizer.convert_tokens_to_ids(missing_token)]])
+ self.generator.input_ids = input_ids
+ candidates, scores = self.generator.get_candidates(input_ids)
+ self.assertIsNotNone(candidates)
+
+ def test_speculation_depth(self):
+ """Test different speculation depths"""
+ input_ids = self.target_tokenizer.encode("Test text", return_tensors="pt")
+ self.generator.input_ids = input_ids
+
+ for depth in [1, 8, 17]:
+ self.generator.num_assistant_tokens = depth
+ candidates, scores = self.generator.get_candidates(input_ids)
+ self.assertLessEqual(candidates.shape[1] - input_ids.shape[1], depth)
+
+ def test_device_consistency(self):
+ """Test handling of inputs on different devices"""
+ input_ids = torch.tensor([[1, 2, 3]]).to(torch_device)
+ self.generator.input_ids = input_ids
+ candidates, _ = self.generator.get_candidates(input_ids)
+ self.assertEqual(candidates.device, input_ids.device)
+
+ def test_usd_vs_vanilla_sampling(cls):
+ """Test that USD matches vanilla sampling with temperature set to nearly 0"""
+ prompt = "Test text"
+
+ pipe_usd = pipeline("text-generation", model=cls.target_name, assistant_model=cls.assistant_name)
+ pipe_usd_output = pipe_usd(prompt, max_new_tokens=5, do_sample=True, temperature=1e-9) # Nearly 0 temperature
+ usd_text = pipe_usd_output[0]["generated_text"]
+
+ pipe_vanilla = pipeline(
+ "text-generation",
+ model=cls.target_name,
+ )
+ pipe_vanilla_output = pipe_vanilla(prompt, max_new_tokens=5, do_sample=False)
+ vanilla_text = pipe_vanilla_output[0]["generated_text"]
+
+ # Assert that the outputs match
+ cls.assertEqual(usd_text, vanilla_text)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_configuration_utils.py b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_configuration_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef30599581ffae4501888bd895a73cf4f8edc43f
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_configuration_utils.py
@@ -0,0 +1,765 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Team Inc.
+#
+# 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 clone 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 copy
+import os
+import tempfile
+import unittest
+import warnings
+
+from huggingface_hub import HfFolder, create_pull_request
+from parameterized import parameterized
+
+from transformers import AutoConfig, GenerationConfig, WatermarkingConfig, is_torch_available
+
+
+if is_torch_available():
+ import torch
+
+from transformers.generation import (
+ ClassifierFreeGuidanceLogitsProcessor,
+ EncoderNoRepeatNGramLogitsProcessor,
+ EncoderRepetitionPenaltyLogitsProcessor,
+ EpsilonLogitsWarper,
+ EtaLogitsWarper,
+ ExponentialDecayLengthPenalty,
+ ForcedBOSTokenLogitsProcessor,
+ ForcedEOSTokenLogitsProcessor,
+ GenerationMode,
+ HammingDiversityLogitsProcessor,
+ MinLengthLogitsProcessor,
+ MinNewTokensLengthLogitsProcessor,
+ MinPLogitsWarper,
+ NoBadWordsLogitsProcessor,
+ NoRepeatNGramLogitsProcessor,
+ PrefixConstrainedLogitsProcessor,
+ RepetitionPenaltyLogitsProcessor,
+ SequenceBiasLogitsProcessor,
+ SuppressTokensAtBeginLogitsProcessor,
+ SuppressTokensLogitsProcessor,
+ TemperatureLogitsWarper,
+ TopKLogitsWarper,
+ TopPLogitsWarper,
+ TypicalLogitsWarper,
+ UnbatchedClassifierFreeGuidanceLogitsProcessor,
+ WatermarkLogitsProcessor,
+)
+from transformers.testing_utils import TOKEN, TemporaryHubRepo, is_staging_test, torch_device
+
+
+class GenerationConfigTest(unittest.TestCase):
+ @parameterized.expand([(None,), ("foo.json",)])
+ def test_save_load_config(self, config_name):
+ config = GenerationConfig(
+ do_sample=True,
+ temperature=0.7,
+ length_penalty=1.0,
+ bad_words_ids=[[1, 2, 3], [4, 5]],
+ )
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ config.save_pretrained(tmp_dir, config_name=config_name)
+ loaded_config = GenerationConfig.from_pretrained(tmp_dir, config_name=config_name)
+
+ # Checks parameters that were specified
+ self.assertEqual(loaded_config.do_sample, True)
+ self.assertEqual(loaded_config.temperature, 0.7)
+ self.assertEqual(loaded_config.length_penalty, 1.0)
+ self.assertEqual(loaded_config.bad_words_ids, [[1, 2, 3], [4, 5]])
+
+ # Checks parameters that were not specified (defaults)
+ self.assertEqual(loaded_config.top_k, 50)
+ self.assertEqual(loaded_config.max_length, 20)
+ self.assertEqual(loaded_config.max_time, None)
+
+ def test_from_model_config(self):
+ model_config = AutoConfig.from_pretrained("openai-community/gpt2")
+ generation_config_from_model = GenerationConfig.from_model_config(model_config)
+ default_generation_config = GenerationConfig()
+
+ # The generation config has loaded a few non-default parameters from the model config
+ self.assertNotEqual(generation_config_from_model, default_generation_config)
+
+ # One of those parameters is eos_token_id -- check if it matches
+ self.assertNotEqual(generation_config_from_model.eos_token_id, default_generation_config.eos_token_id)
+ self.assertEqual(generation_config_from_model.eos_token_id, model_config.eos_token_id)
+
+ def test_update(self):
+ generation_config = GenerationConfig()
+ update_kwargs = {
+ "max_new_tokens": 1024,
+ "foo": "bar",
+ }
+ update_kwargs_copy = copy.deepcopy(update_kwargs)
+ unused_kwargs = generation_config.update(**update_kwargs)
+
+ # update_kwargs was not modified (no side effects)
+ self.assertEqual(update_kwargs, update_kwargs_copy)
+
+ # update_kwargs was used to update the config on valid attributes
+ self.assertEqual(generation_config.max_new_tokens, 1024)
+
+ # `.update()` returns a dictionary of unused kwargs
+ self.assertEqual(unused_kwargs, {"foo": "bar"})
+
+ # TODO: @Arthur and/or @Joao
+ # FAILED tests/generation/test_configuration_utils.py::GenerationConfigTest::test_initialize_new_kwargs - AttributeError: 'GenerationConfig' object has no attribute 'get_text_config'
+ # See: https://app.circleci.com/pipelines/github/huggingface/transformers/104831/workflows/e5e61514-51b7-4c8c-bba7-3c4d2986956e/jobs/1394252
+ @unittest.skip("failed with `'GenerationConfig' object has no attribute 'get_text_config'`")
+ def test_initialize_new_kwargs(self):
+ generation_config = GenerationConfig()
+ generation_config.foo = "bar"
+
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ # update_kwargs was used to update the config on valid attributes
+ self.assertEqual(new_config.foo, "bar")
+
+ generation_config = GenerationConfig.from_model_config(new_config)
+ assert not hasattr(generation_config, "foo") # no new kwargs should be initialized if from config
+
+ def test_kwarg_init(self):
+ """Tests that we can overwrite attributes at `from_pretrained` time."""
+ default_config = GenerationConfig()
+ self.assertEqual(default_config.temperature, 1.0)
+ self.assertEqual(default_config.do_sample, False)
+ self.assertEqual(default_config.num_beams, 1)
+
+ config = GenerationConfig(
+ do_sample=True,
+ temperature=0.7,
+ length_penalty=1.0,
+ bad_words_ids=[[1, 2, 3], [4, 5]],
+ )
+ self.assertEqual(config.temperature, 0.7)
+ self.assertEqual(config.do_sample, True)
+ self.assertEqual(config.num_beams, 1)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ config.save_pretrained(tmp_dir)
+ loaded_config = GenerationConfig.from_pretrained(tmp_dir, temperature=1.0)
+
+ self.assertEqual(loaded_config.temperature, 1.0)
+ self.assertEqual(loaded_config.do_sample, True)
+ self.assertEqual(loaded_config.num_beams, 1) # default value
+
+ def test_validate(self):
+ """
+ Tests that the `validate` method is working as expected. Note that `validate` is called at initialization time
+ """
+ # A correct configuration will not throw any warning
+ with warnings.catch_warnings(record=True) as captured_warnings:
+ GenerationConfig()
+ self.assertEqual(len(captured_warnings), 0)
+
+ # Inconsequent but technically wrong configuration will throw a warning (e.g. setting sampling
+ # parameters with `do_sample=False`). May be escalated to an error in the future.
+ with warnings.catch_warnings(record=True) as captured_warnings:
+ GenerationConfig(do_sample=False, temperature=0.5)
+ self.assertEqual(len(captured_warnings), 1)
+
+ with warnings.catch_warnings(record=True) as captured_warnings:
+ GenerationConfig(return_dict_in_generate=False, output_scores=True)
+ self.assertEqual(len(captured_warnings), 1)
+
+ # Expanding on the case above, we can update a bad configuration to get rid of the warning. Ideally,
+ # that is done by unsetting the parameter (i.e. setting it to None)
+ generation_config_bad_temperature = GenerationConfig(do_sample=False, temperature=0.5)
+ with warnings.catch_warnings(record=True) as captured_warnings:
+ # BAD - 0.9 means it is still set, we should warn
+ generation_config_bad_temperature.update(temperature=0.9)
+ self.assertEqual(len(captured_warnings), 1)
+ generation_config_bad_temperature = GenerationConfig(do_sample=False, temperature=0.5)
+ with warnings.catch_warnings(record=True) as captured_warnings:
+ # CORNER CASE - 1.0 is the default, we can't detect whether it is set by the user or not, we shouldn't warn
+ generation_config_bad_temperature.update(temperature=1.0)
+ self.assertEqual(len(captured_warnings), 0)
+ generation_config_bad_temperature = GenerationConfig(do_sample=False, temperature=0.5)
+ with warnings.catch_warnings(record=True) as captured_warnings:
+ # OK - None means it is unset, nothing to warn about
+ generation_config_bad_temperature.update(temperature=None)
+ self.assertEqual(len(captured_warnings), 0)
+
+ # Impossible sets of contraints/parameters will raise an exception
+ with self.assertRaises(ValueError):
+ GenerationConfig(do_sample=False, num_beams=1, num_return_sequences=2)
+ with self.assertRaises(ValueError):
+ # dummy constraint
+ GenerationConfig(do_sample=True, num_beams=2, constraints=["dummy"])
+ with self.assertRaises(ValueError):
+ GenerationConfig(do_sample=True, num_beams=2, force_words_ids=[[[1, 2, 3]]])
+
+ # Passing `generate()`-only flags to `validate` will raise an exception
+ with self.assertRaises(ValueError):
+ GenerationConfig(logits_processor="foo")
+
+ # Model-specific parameters will NOT raise an exception or a warning
+ with warnings.catch_warnings(record=True) as captured_warnings:
+ GenerationConfig(foo="bar")
+ self.assertEqual(len(captured_warnings), 0)
+
+ def test_refuse_to_save(self):
+ """Tests that we refuse to save a generation config that fails validation."""
+
+ # setting the temperature alone is invalid, as we also need to set do_sample to True -> throws a warning that
+ # is caught, doesn't save, and raises an exception
+ config = GenerationConfig()
+ config.temperature = 0.5
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ with self.assertRaises(ValueError) as exc:
+ config.save_pretrained(tmp_dir)
+ self.assertTrue("Fix these issues to save the configuration." in str(exc.exception))
+ self.assertTrue(len(os.listdir(tmp_dir)) == 0)
+
+ # greedy decoding throws an exception if we try to return multiple sequences -> throws an exception that is
+ # caught, doesn't save, and raises a warning
+ config = GenerationConfig()
+ config.num_return_sequences = 2
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ with self.assertRaises(ValueError) as exc:
+ config.save_pretrained(tmp_dir)
+ self.assertTrue("Fix these issues to save the configuration." in str(exc.exception))
+ self.assertTrue(len(os.listdir(tmp_dir)) == 0)
+
+ # final check: no warnings/exceptions thrown if it is correct, and file is saved
+ config = GenerationConfig()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ with warnings.catch_warnings(record=True) as captured_warnings:
+ config.save_pretrained(tmp_dir)
+ self.assertEqual(len(captured_warnings), 0)
+ self.assertTrue(len(os.listdir(tmp_dir)) == 1)
+
+ def test_generation_mode(self):
+ """Tests that the `get_generation_mode` method is working as expected."""
+ config = GenerationConfig()
+ self.assertEqual(config.get_generation_mode(), GenerationMode.GREEDY_SEARCH)
+
+ config = GenerationConfig(do_sample=True)
+ self.assertEqual(config.get_generation_mode(), GenerationMode.SAMPLE)
+
+ config = GenerationConfig(num_beams=2)
+ self.assertEqual(config.get_generation_mode(), GenerationMode.BEAM_SEARCH)
+
+ config = GenerationConfig(top_k=10, do_sample=False, penalty_alpha=0.6)
+ self.assertEqual(config.get_generation_mode(), GenerationMode.CONTRASTIVE_SEARCH)
+
+ config = GenerationConfig()
+ self.assertEqual(config.get_generation_mode(assistant_model="foo"), GenerationMode.ASSISTED_GENERATION)
+
+ def test_static_cache_without_cache_config(self):
+ """Regression test for #35026 -- static cache should work without a cache config."""
+ config = GenerationConfig(cache_implementation="static")
+ self.assertEqual(config.cache_implementation, "static")
+ self.assertEqual(config.cache_config, None)
+
+
+class GenerationConfigSerializationTest(unittest.TestCase):
+ def test_serialize_generation_sequence_bias(self):
+ """Tests that GenerationConfig is serialized and SequenceBiasLogitsProcessor is initialized with sequence_bias parameter"""
+ generation_config = GenerationConfig()
+ sequence_bias = [[[45, 67], -0.6], [[89], 1.2]]
+ generation_config.sequence_bias = sequence_bias
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertSequenceEqual(new_config.sequence_bias, sequence_bias)
+
+ expected_sequence_bias = {(45, 67): -0.6, (89,): 1.2}
+ bias_logits_processor = SequenceBiasLogitsProcessor(new_config.sequence_bias)
+ self.assertDictEqual(bias_logits_processor.sequence_bias, expected_sequence_bias)
+
+ def test_serialize_generation_min_length_eos_token(self):
+ """Tests that GenerationConfig is serialized and MinLengthLogitsProcessor is initialized with min_length and eos_token_id"""
+ eos_token_id = 0
+ min_length = 10
+
+ generation_config = GenerationConfig(min_length=min_length, eos_token_id=eos_token_id)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.min_length, min_length)
+ self.assertEqual(new_config.eos_token_id, eos_token_id)
+
+ min_dist_processor = MinLengthLogitsProcessor(
+ min_length=new_config.min_length, eos_token_id=new_config.eos_token_id
+ )
+ self.assertEqual(min_dist_processor.min_length, min_length)
+ self.assertEqual(min_dist_processor.eos_token_id, eos_token_id)
+
+ def test_serialize_generation_min_new_tokens(self):
+ """Tests that GenerationConfig is serialized and MinNewTokensLengthLogitsProcessor is initialized with min_new_tokens"""
+ eos_token_id = 0
+ min_new_tokens = 5
+ prompt_length_to_skip = 2
+
+ generation_config = GenerationConfig(min_new_tokens=min_new_tokens)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.min_new_tokens, min_new_tokens)
+
+ min_new_tokens_processor = MinNewTokensLengthLogitsProcessor(
+ prompt_length_to_skip=prompt_length_to_skip,
+ min_new_tokens=new_config.min_new_tokens,
+ eos_token_id=eos_token_id,
+ )
+ self.assertEqual(min_new_tokens_processor.min_new_tokens, min_new_tokens)
+
+ def test_serialize_generation_temperature(self):
+ """Tests that GenerationConfig is serialized and TemperatureLogitsWarper is initialized with temperature"""
+ temperature = 2.0
+
+ generation_config = GenerationConfig(temperature=temperature, do_sample=True)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.temperature, temperature)
+
+ temperature_logits_warper = TemperatureLogitsWarper(temperature=new_config.temperature)
+ self.assertEqual(temperature_logits_warper.temperature, temperature)
+
+ def test_serialize_generation_repetition_penalty(self):
+ """Tests that GenerationConfig is serialized and RepetitionPenaltyLogitsProcessor is initialized with repetition_penalty"""
+ penalty = 2.0
+
+ generation_config = GenerationConfig(repetition_penalty=penalty)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.repetition_penalty, penalty)
+
+ rep_penalty_proc = RepetitionPenaltyLogitsProcessor(penalty=new_config.repetition_penalty)
+ self.assertEqual(rep_penalty_proc.penalty, penalty)
+
+ def test_serialize_generation_encoder_repetition_penalty(self):
+ """Tests that GenerationConfig is serialized and EncoderRepetitionPenaltyLogitsProcessor is initialized with penalty and input_ids"""
+ penalty = 2.0
+ input_ids = torch.tensor([[0, 1], [5, 0]], device=torch_device, dtype=torch.long)
+
+ generation_config = GenerationConfig(encoder_repetition_penalty=penalty)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.encoder_repetition_penalty, penalty)
+
+ rep_penalty_proc = EncoderRepetitionPenaltyLogitsProcessor(
+ penalty=new_config.encoder_repetition_penalty, encoder_input_ids=input_ids
+ )
+ self.assertEqual(rep_penalty_proc.penalty, 1 / penalty)
+ torch.testing.assert_close(rep_penalty_proc.encoder_input_ids, input_ids)
+
+ def test_serialize_generation_top_p(self):
+ """Tests that GenerationConfig is serialized and TopPLogitsWarper is initialized with top_p"""
+ top_p = 0.8
+
+ generation_config = GenerationConfig(top_p=top_p, do_sample=True)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.top_p, top_p)
+
+ rep_penalty_proc = TopPLogitsWarper(top_p=new_config.top_p)
+ self.assertEqual(rep_penalty_proc.top_p, top_p)
+
+ def test_serialize_generation_top_k(self):
+ """Tests that GenerationConfig is serialized and TopKLogitsWarper is initialized with top_k"""
+ top_k = 2
+
+ generation_config = GenerationConfig(top_k=top_k, do_sample=True)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.top_k, top_k)
+
+ top_k_logits_wrap = TopKLogitsWarper(top_k=new_config.top_k)
+ self.assertEqual(top_k_logits_wrap.top_k, top_k)
+
+ def test_serialize_generation_min_p(self):
+ """Tests that GenerationConfig is serialized and MinPLogitsWarper is initialized with min_p"""
+ min_p = 0.8
+
+ generation_config = GenerationConfig(min_p=min_p, do_sample=True)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.min_p, min_p)
+
+ min_k_logits_wrap = MinPLogitsWarper(min_p=new_config.min_p)
+ self.assertEqual(min_k_logits_wrap.min_p, min_p)
+
+ def test_serialize_generation_typical_p(self):
+ """Tests that GenerationConfig is serialized and TypicalLogitsWarper is initialized with mass"""
+ mass = 0.8
+
+ generation_config = GenerationConfig(typical_p=mass, do_sample=True)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.typical_p, mass)
+
+ typical_p_logits_wrap = TypicalLogitsWarper(mass=new_config.typical_p)
+ self.assertEqual(typical_p_logits_wrap.mass, mass)
+
+ def test_serialize_generation_epsilon_cutoff(self):
+ """Tests that GenerationConfig is serialized and EpsilonLogitsWarper is initialized with epsilon"""
+ epsilon = 0.8
+
+ generation_config = GenerationConfig(epsilon_cutoff=epsilon, do_sample=True)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.epsilon_cutoff, epsilon)
+
+ epsilon_logits_wrap = EpsilonLogitsWarper(epsilon=new_config.epsilon_cutoff)
+ self.assertEqual(epsilon_logits_wrap.epsilon, epsilon)
+
+ def test_serialize_generation_eta_cutoff(self):
+ """Tests that GenerationConfig is serialized and EtaLogitsWarper is initialized with epsilon"""
+ epsilon = 0.8
+
+ generation_config = GenerationConfig(eta_cutoff=epsilon, do_sample=True)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.eta_cutoff, epsilon)
+
+ eta_logits_wrap = EtaLogitsWarper(epsilon=new_config.eta_cutoff)
+ self.assertEqual(eta_logits_wrap.epsilon, epsilon)
+
+ def test_serialize_generation_ngram_size(self):
+ """Tests that GenerationConfig is serialized and NoRepeatNGramLogitsProcessor is initialized with ngram_size"""
+ ngram_size = 2
+
+ generation_config = GenerationConfig(no_repeat_ngram_size=ngram_size, do_sample=True)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.no_repeat_ngram_size, ngram_size)
+
+ no_repeat_ngram_proc = NoRepeatNGramLogitsProcessor(ngram_size=new_config.no_repeat_ngram_size)
+ self.assertEqual(no_repeat_ngram_proc.ngram_size, ngram_size)
+
+ def test_serialize_generation_encoder_ngram_size(self):
+ """Tests that GenerationConfig is serialized and EncoderNoRepeatNGramLogitsProcessor is initialized with ngram_size"""
+ ngram_size = 2
+ input_ids = torch.tensor([[0, 1], [5, 0]], device=torch_device, dtype=torch.long)
+
+ generation_config = GenerationConfig(encoder_no_repeat_ngram_size=ngram_size, do_sample=True)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.encoder_no_repeat_ngram_size, ngram_size)
+
+ encoder_no_repeat_ngram_proc = EncoderNoRepeatNGramLogitsProcessor(
+ encoder_ngram_size=new_config.encoder_no_repeat_ngram_size, encoder_input_ids=input_ids
+ )
+ self.assertEqual(encoder_no_repeat_ngram_proc.ngram_size, ngram_size)
+
+ def test_serialize_generation_bad_words_ids(self):
+ """Tests that GenerationConfig is serialized and NoBadWordsLogitsProcessor is initialized with bad_words_ids"""
+ bad_word_tokens = [[1], [4], [1, 0], [0, 1, 2], [1, 3, 1, 3]]
+
+ generation_config = GenerationConfig(bad_words_ids=bad_word_tokens)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertSequenceEqual(new_config.bad_words_ids, bad_word_tokens)
+
+ no_bad_words_dist_proc = NoBadWordsLogitsProcessor(bad_words_ids=new_config.bad_words_ids)
+ self.assertSequenceEqual(no_bad_words_dist_proc.bad_word_ids, bad_word_tokens)
+
+ def test_serialize_generation_num_beams(self):
+ """Tests that GenerationConfig is serialized and PrefixConstrainedLogitsProcessor is initialized with num_beams"""
+ num_beams = 1
+
+ def prefix_allowed_tokens_fn(batch_id, inputs_ids):
+ return [[0, 1], [2, 3]][batch_id]
+
+ generation_config = GenerationConfig(num_beams=num_beams)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.num_beams, num_beams)
+
+ prefix_constrained_logits_proc = PrefixConstrainedLogitsProcessor(
+ prefix_allowed_tokens_fn, num_beams=new_config.num_beams
+ )
+ self.assertEqual(prefix_constrained_logits_proc._num_beams, num_beams)
+
+ def test_serialize_generation_diversity_penalty_and_num_bean_groups(self):
+ """Tests that GenerationConfig is serialized and HammingDiversityLogitsProcessor is initialized with diversity_penalty_and_num_bean_groups"""
+ num_beams = 2
+ num_beam_groups = 2
+ diversity_penalty = 1.0
+
+ generation_config = GenerationConfig(
+ num_beams=num_beams, diversity_penalty=diversity_penalty, num_beam_groups=num_beam_groups
+ )
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.num_beams, num_beams)
+ self.assertEqual(new_config.diversity_penalty, diversity_penalty)
+ self.assertEqual(new_config.num_beam_groups, num_beam_groups)
+
+ diversity_logits_processor = HammingDiversityLogitsProcessor(
+ diversity_penalty=new_config.diversity_penalty,
+ num_beams=new_config.num_beams,
+ num_beam_groups=new_config.num_beam_groups,
+ )
+ self.assertEqual(diversity_logits_processor._num_beams, num_beams)
+ self.assertEqual(diversity_logits_processor._diversity_penalty, diversity_penalty)
+ self.assertEqual(diversity_logits_processor._num_sub_beams, num_beams // num_beam_groups)
+
+ def test_serialize_generation_bos_token_id(self):
+ """Tests that GenerationConfig is serialized and ForcedBOSTokenLogitsProcessor is initialized with bos_token_id"""
+ bos_token_id = 0
+
+ generation_config = GenerationConfig(bos_token_id=bos_token_id)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.bos_token_id, bos_token_id)
+
+ logits_processor = ForcedBOSTokenLogitsProcessor(bos_token_id=new_config.bos_token_id)
+ self.assertEqual(logits_processor.bos_token_id, bos_token_id)
+
+ def test_serialize_generation_eos_token_id(self):
+ """Tests that GenerationConfig is serialized and ForcedEOSTokenLogitsProcessor is initialized with eos_token_id"""
+ eos_token_id = 0
+ max_length = 5
+
+ generation_config = GenerationConfig(eos_token_id=eos_token_id)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.eos_token_id, eos_token_id)
+
+ logits_processor = ForcedEOSTokenLogitsProcessor(
+ max_length=max_length, eos_token_id=new_config.eos_token_id, device=torch_device
+ )
+ self.assertEqual(logits_processor.eos_token_id, eos_token_id)
+
+ def test_serialize_generation_exponential_decay_length_penalty(self):
+ """Tests that GenerationConfig is serialized and ExponentialDecayLengthPenalty is initialized with regulation_start and regulation_factor"""
+ eos_token_id = 0
+ penalty_start = 5
+ penalty_factor = 1.1
+ input_ids_seq_length = 10
+ exponential_decay_length_penalty = (penalty_start, penalty_factor)
+
+ generation_config = GenerationConfig(exponential_decay_length_penalty=exponential_decay_length_penalty)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.exponential_decay_length_penalty, [penalty_start, penalty_factor])
+
+ exponential_decay_processor = ExponentialDecayLengthPenalty(
+ exponential_decay_length_penalty=new_config.exponential_decay_length_penalty,
+ eos_token_id=eos_token_id,
+ input_ids_seq_length=input_ids_seq_length,
+ )
+ self.assertEqual(
+ exponential_decay_processor.regulation_start, exponential_decay_length_penalty[0] + input_ids_seq_length
+ )
+ self.assertEqual(exponential_decay_processor.regulation_factor, exponential_decay_length_penalty[1])
+
+ def test_serialize_generation_begin_suppress_tokens(self):
+ """Tests that GenerationConfig is serialized and SuppressTokensAtBeginLogitsProcessor is initialized with begin_suppress_token and begin_index"""
+
+ begin_suppress_tokens = [220, 50256]
+ begin_index = 0
+ generation_config = GenerationConfig(begin_suppress_tokens=begin_suppress_tokens)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertSequenceEqual(new_config.begin_suppress_tokens, begin_suppress_tokens)
+
+ suppress_processor = SuppressTokensAtBeginLogitsProcessor(
+ begin_suppress_tokens=new_config.begin_suppress_tokens, begin_index=begin_index
+ )
+ self.assertSequenceEqual(suppress_processor.begin_suppress_tokens, begin_suppress_tokens)
+ self.assertEqual(suppress_processor.begin_index, begin_index)
+
+ def test_serialize_generation_suppress_tokens(self):
+ """Tests that GenerationConfig is serialized and SuppressTokensLogitsProcessor is initialized with suppress_token"""
+ suppress_tokens = [220, 50256]
+
+ generation_config = GenerationConfig(suppress_tokens=suppress_tokens)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertSequenceEqual(new_config.suppress_tokens, suppress_tokens)
+
+ suppress_processor = SuppressTokensLogitsProcessor(suppress_tokens=new_config.suppress_tokens)
+ self.assertSequenceEqual(suppress_processor.suppress_tokens, suppress_tokens)
+
+ def test_serialize_generation_guidance_scale(self):
+ """Tests that GenerationConfig is serialized and ClassifierFreeGuidanceLogitsProcessor is initialized with guidance_scale"""
+ guidance_scale = 2.0
+ generation_config = GenerationConfig(guidance_scale=guidance_scale)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.guidance_scale, guidance_scale)
+
+ classifier_processor = ClassifierFreeGuidanceLogitsProcessor(guidance_scale=new_config.guidance_scale)
+ self.assertEqual(classifier_processor.guidance_scale, guidance_scale)
+
+ def test_serialize_generation_guidance_scale_unbatched(self):
+ """Tests that GenerationConfig is serialized and UnbatchedClassifierFreeGuidanceLogitsProcessor is initialized with guidance_scale"""
+ guidance_scale = 2.0
+
+ input_ids = torch.LongTensor([[0]])
+
+ generation_config = GenerationConfig(guidance_scale=guidance_scale)
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.guidance_scale, guidance_scale)
+
+ cfg = UnbatchedClassifierFreeGuidanceLogitsProcessor(new_config.guidance_scale, {}, input_ids)
+ self.assertEqual(cfg.guidance_scale, guidance_scale)
+
+ def test_serialize_generation_watermarking_config(self):
+ """Tests that GenerationConfig is serialized and WatermarkLogitsProcessor is initialized with WatermarkingConfig parameters"""
+
+ vocab_size = 20
+ bias = 2.0
+ greenlist_ratio = 0.5
+ hashing_key = 10
+ seeding_scheme = "lefthash"
+ context_width = 10
+ watermarking_config = WatermarkingConfig(
+ bias=bias,
+ greenlist_ratio=greenlist_ratio,
+ hashing_key=hashing_key,
+ seeding_scheme=seeding_scheme,
+ context_width=context_width,
+ )
+ generation_config = GenerationConfig(watermarking_config=watermarking_config)
+
+ with tempfile.TemporaryDirectory("test-generation-config") as tmp_dir:
+ generation_config.save_pretrained(tmp_dir)
+ new_config = GenerationConfig.from_pretrained(tmp_dir)
+ self.assertEqual(new_config.watermarking_config.bias, bias)
+ self.assertEqual(new_config.watermarking_config.greenlist_ratio, greenlist_ratio)
+ self.assertEqual(new_config.watermarking_config.hashing_key, hashing_key)
+ self.assertEqual(new_config.watermarking_config.seeding_scheme, seeding_scheme)
+ self.assertEqual(new_config.watermarking_config.context_width, context_width)
+
+ watermark = WatermarkLogitsProcessor(
+ vocab_size=vocab_size,
+ device=torch_device,
+ greenlist_ratio=new_config.watermarking_config.greenlist_ratio,
+ bias=new_config.watermarking_config.bias,
+ hashing_key=new_config.watermarking_config.hashing_key,
+ seeding_scheme=new_config.watermarking_config.seeding_scheme,
+ context_width=new_config.watermarking_config.context_width,
+ )
+ self.assertEqual(watermark.bias, bias)
+ self.assertEqual(watermark.greenlist_size, int(vocab_size * greenlist_ratio))
+ self.assertEqual(watermark.hash_key, hashing_key)
+ self.assertEqual(watermark.seeding_scheme, seeding_scheme)
+ self.assertEqual(watermark.context_width, context_width)
+
+
+@is_staging_test
+class ConfigPushToHubTester(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls._token = TOKEN
+ HfFolder.save_token(TOKEN)
+
+ def test_push_to_hub(self):
+ with TemporaryHubRepo(token=self._token) as tmp_repo:
+ config = GenerationConfig(
+ do_sample=True,
+ temperature=0.7,
+ length_penalty=1.0,
+ )
+ config.push_to_hub(tmp_repo.repo_id, token=self._token)
+
+ new_config = GenerationConfig.from_pretrained(tmp_repo.repo_id)
+ for k, v in config.to_dict().items():
+ if k != "transformers_version":
+ self.assertEqual(v, getattr(new_config, k))
+
+ def test_push_to_hub_via_save_pretrained(self):
+ with TemporaryHubRepo(token=self._token) as tmp_repo:
+ config = GenerationConfig(
+ do_sample=True,
+ temperature=0.7,
+ length_penalty=1.0,
+ )
+ # Push to hub via save_pretrained
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ config.save_pretrained(tmp_dir, repo_id=tmp_repo.repo_id, push_to_hub=True, token=self._token)
+
+ new_config = GenerationConfig.from_pretrained(tmp_repo.repo_id)
+ for k, v in config.to_dict().items():
+ if k != "transformers_version":
+ self.assertEqual(v, getattr(new_config, k))
+
+ def test_push_to_hub_in_organization(self):
+ with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo:
+ config = GenerationConfig(
+ do_sample=True,
+ temperature=0.7,
+ length_penalty=1.0,
+ )
+ config.push_to_hub(tmp_repo.repo_id, token=self._token)
+
+ new_config = GenerationConfig.from_pretrained(tmp_repo.repo_id)
+ for k, v in config.to_dict().items():
+ if k != "transformers_version":
+ self.assertEqual(v, getattr(new_config, k))
+
+ def test_push_to_hub_in_organization_via_save_pretrained(self):
+ with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo:
+ config = GenerationConfig(
+ do_sample=True,
+ temperature=0.7,
+ length_penalty=1.0,
+ )
+ # Push to hub via save_pretrained
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ config.save_pretrained(tmp_dir, repo_id=tmp_repo.repo_id, push_to_hub=True, token=self._token)
+
+ new_config = GenerationConfig.from_pretrained(tmp_repo.repo_id)
+ for k, v in config.to_dict().items():
+ if k != "transformers_version":
+ self.assertEqual(v, getattr(new_config, k))
+
+ def test_push_to_hub_on_pr_revision(self):
+ with TemporaryHubRepo(token=self._token) as tmp_repo:
+ # create a PR
+ pr = create_pull_request(repo_id=tmp_repo.repo_id, title="Test PR", token=self._token)
+ revision = f"refs/pr/{pr.num}"
+
+ # push to PR ref
+ config = GenerationConfig(
+ do_sample=True,
+ temperature=0.7,
+ length_penalty=1.0,
+ )
+ config.push_to_hub(tmp_repo.repo_id, token=self._token, revision=revision)
+
+ # load from PR ref
+ new_config = GenerationConfig.from_pretrained(tmp_repo.repo_id, revision=revision)
+ for k, v in config.to_dict().items():
+ if k != "transformers_version":
+ self.assertEqual(v, getattr(new_config, k))
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_fsdp.py b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_fsdp.py
new file mode 100644
index 0000000000000000000000000000000000000000..904ccdea63baf97b6c90624f3a46f36c6c729c98
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_fsdp.py
@@ -0,0 +1,148 @@
+# 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
+from typing import Any, Callable
+
+from transformers import is_torch_available
+from transformers.testing_utils import (
+ TestCasePlus,
+ execute_subprocess_async,
+ get_torch_dist_unique_port,
+ require_torch_multi_gpu,
+)
+
+
+if is_torch_available():
+ import functools
+
+ import torch
+ import torch.distributed
+ from torch.distributed._composable.fsdp import fully_shard, register_fsdp_forward_method
+ from torch.distributed.device_mesh import init_device_mesh
+ from torch.distributed.fsdp import FullyShardedDataParallel
+ from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy
+
+ from transformers import AutoModelForCausalLM, AutoTokenizer
+ from transformers.models.gpt2.modeling_gpt2 import GPT2Block
+
+ data = 4 * [
+ "Hello world!",
+ "The quick brown fox jumps over the lazy dog.",
+ ]
+
+ def manage_process_group(func: Callable[..., Any]) -> Callable[..., Any]:
+ """Manage the creation and destruction of the distributed process group for the wrapped function."""
+
+ def wrapped(*args: Any, **kwargs: Any) -> Any:
+ torch.distributed.init_process_group(world_size=torch.cuda.device_count())
+ try:
+ return func(*args, **kwargs)
+ finally:
+ torch.distributed.destroy_process_group()
+
+ return wrapped
+
+ @manage_process_group
+ def fsdp_generate():
+ torch.cuda.set_device(device := torch.device(rank := torch.distributed.get_rank()))
+
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(device)
+
+ fsdp_model = FullyShardedDataParallel(
+ model,
+ auto_wrap_policy=functools.partial(transformer_auto_wrap_policy, transformer_layer_cls={GPT2Block}),
+ limit_all_gathers=True,
+ use_orig_params=True,
+ )
+
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ batch = tokenizer(data[rank], return_tensors="pt", return_attention_mask=True).to(device)
+
+ with FullyShardedDataParallel.summon_full_params(fsdp_model):
+ _ = fsdp_model.module.generate(
+ input_ids=batch["input_ids"],
+ attention_mask=batch["attention_mask"],
+ max_length=30,
+ )
+
+ @manage_process_group
+ def fsdp2_generate():
+ torch.cuda.set_device(device := torch.device(rank := torch.distributed.get_rank()))
+
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(device)
+
+ mesh = init_device_mesh("cuda", (torch.distributed.get_world_size(),))
+ for submodule in model.modules():
+ if isinstance(submodule, GPT2Block):
+ fully_shard(submodule, mesh=mesh)
+ fully_shard(model, mesh=mesh)
+
+ register_fsdp_forward_method(model, "generate")
+
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ batch = tokenizer(data[rank], return_tensors="pt", return_attention_mask=True).to(device)
+
+ _ = model.generate(
+ input_ids=batch["input_ids"],
+ attention_mask=batch["attention_mask"],
+ max_length=30,
+ )
+
+
+class TestFSDPGeneration(TestCasePlus):
+ @require_torch_multi_gpu
+ def test_fsdp_generate(self):
+ distributed_args = f"""--nproc_per_node={torch.cuda.device_count()}
+ --master_port={get_torch_dist_unique_port()}
+ {self.test_file_dir}/test_fsdp.py
+ """.split()
+ args = "--fsdp".split()
+ cmd = ["torchrun"] + distributed_args + args
+ execute_subprocess_async(cmd, env=self.get_env())
+ # successful return here == success - any errors would have caused an error in the sub-call
+
+ @require_torch_multi_gpu
+ def test_fsdp2_generate(self):
+ distributed_args = f"""--nproc_per_node={torch.cuda.device_count()}
+ --master_port={get_torch_dist_unique_port()}
+ {self.test_file_dir}/test_fsdp.py
+ """.split()
+ args = "--fsdp2".split()
+ cmd = ["torchrun"] + distributed_args + args
+ execute_subprocess_async(cmd, env=self.get_env())
+ # successful return here == success - any errors would have caused an error in the sub-call
+
+
+if __name__ == "__main__":
+ # The script below is meant to be run under torch.distributed, on a machine with multiple GPUs:
+ #
+ # PYTHONPATH="src" python -m torch.distributed.run --nproc_per_node 2 --output_dir output_dir ./tests/generation/test_fsdp.py --fsdp
+
+ class CLIArgs(argparse.Namespace):
+ fsdp: bool
+ fsdp2: bool
+
+ parser = argparse.ArgumentParser()
+ group = parser.add_mutually_exclusive_group()
+ group.add_argument("--fsdp", action="store_true")
+ group.add_argument("--fsdp2", action="store_true")
+ args = parser.parse_args(namespace=CLIArgs())
+
+ if args.fsdp:
+ fsdp_generate()
+ elif args.fsdp2:
+ fsdp2_generate()
+ else:
+ raise ValueError("Missing test selection")
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_logits_process.py b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_logits_process.py
new file mode 100644
index 0000000000000000000000000000000000000000..a922a71c22c68466a2c1775edbcdf1e45537b412
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_logits_process.py
@@ -0,0 +1,1163 @@
+# coding=utf-8
+# Copyright 2020 The HuggingFace Team Inc.
+#
+# 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 clone 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 unittest
+from typing import List, Union
+
+import numpy as np
+from parameterized import parameterized
+
+from transformers import is_torch_available
+from transformers.testing_utils import require_torch, torch_device
+
+from ..test_modeling_common import ids_tensor
+
+
+if is_torch_available():
+ import torch
+ from torch import nn
+
+ from transformers.generation import (
+ EncoderNoRepeatNGramLogitsProcessor,
+ EncoderRepetitionPenaltyLogitsProcessor,
+ EpsilonLogitsWarper,
+ EtaLogitsWarper,
+ ExponentialDecayLengthPenalty,
+ ForcedBOSTokenLogitsProcessor,
+ ForcedEOSTokenLogitsProcessor,
+ HammingDiversityLogitsProcessor,
+ InfNanRemoveLogitsProcessor,
+ LogitNormalization,
+ LogitsProcessorList,
+ MinLengthLogitsProcessor,
+ MinNewTokensLengthLogitsProcessor,
+ MinPLogitsWarper,
+ NoBadWordsLogitsProcessor,
+ NoRepeatNGramLogitsProcessor,
+ PrefixConstrainedLogitsProcessor,
+ RepetitionPenaltyLogitsProcessor,
+ SequenceBiasLogitsProcessor,
+ SynthIDTextWatermarkLogitsProcessor,
+ TemperatureLogitsWarper,
+ TopKLogitsWarper,
+ TopPLogitsWarper,
+ TypicalLogitsWarper,
+ UnbatchedClassifierFreeGuidanceLogitsProcessor,
+ WatermarkLogitsProcessor,
+ )
+ from transformers.generation.logits_process import BarkEosPrioritizerLogitsProcessor
+
+
+@require_torch
+class LogitsProcessorTest(unittest.TestCase):
+ def _get_uniform_logits(self, batch_size: int, length: int):
+ scores = torch.ones((batch_size, length), device=torch_device, dtype=torch.float) / length
+ return scores
+
+ def test_min_length_dist_processor(self):
+ vocab_size = 20
+ batch_size = 4
+ eos_token_id = 0
+
+ min_dist_processor = MinLengthLogitsProcessor(min_length=10, eos_token_id=eos_token_id, device=torch_device)
+
+ # check that min length is applied at length 5
+ input_ids = ids_tensor((batch_size, 5), vocab_size=20)
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+ scores_before_min_length = min_dist_processor(input_ids, scores)
+ self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist(), 4 * [-float("inf")])
+
+ # check that min length is not applied anymore at length 15
+ input_ids = ids_tensor((batch_size, 15), vocab_size=20)
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+ scores_before_min_length = min_dist_processor(input_ids, scores)
+ self.assertFalse(torch.isinf(scores_before_min_length).any())
+
+ @parameterized.expand([(0,), ([0, 18],)])
+ def test_new_min_length_dist_processor(self, eos_token_id: Union[int, List[int]]):
+ vocab_size = 20
+ batch_size = 4
+
+ # check that first input is skipped (min new length applying)
+ input_ids = ids_tensor((batch_size, 5), vocab_size=20)
+ new_min_dist_processor = MinNewTokensLengthLogitsProcessor(
+ prompt_length_to_skip=input_ids.shape[-1], min_new_tokens=3, eos_token_id=eos_token_id, device=torch_device
+ )
+
+ expected_eos_scores_before_min_length = batch_size * [-float("inf")]
+ if isinstance(eos_token_id, list):
+ expected_eos_scores_before_min_length *= len(eos_token_id)
+
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+ scores_before_min_length = new_min_dist_processor(input_ids, scores)
+ self.assertListEqual(
+ scores_before_min_length[:, eos_token_id].flatten().tolist(), expected_eos_scores_before_min_length
+ )
+
+ # check that, for skipping, now prompt length is 5, after that we expect first 5 tokens will be skipped
+ self.assertTrue(new_min_dist_processor.prompt_length_to_skip == 5)
+
+ # check that min length is applied at length 2
+ input_ids = ids_tensor((batch_size, 2), vocab_size=20)
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+ scores_before_min_length = new_min_dist_processor(input_ids, scores)
+ self.assertListEqual(
+ scores_before_min_length[:, eos_token_id].flatten().tolist(), expected_eos_scores_before_min_length
+ )
+
+ # check that min new length is applied at length 6 (because it has only 1 new token)
+ input_ids = ids_tensor((batch_size, 6), vocab_size=20)
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+ scores_before_min_length = new_min_dist_processor(input_ids, scores)
+ self.assertListEqual(
+ scores_before_min_length[:, eos_token_id].flatten().tolist(), expected_eos_scores_before_min_length
+ )
+
+ # check that min new length is applied at length 7 (because it has only 2 new tokens)
+ input_ids = ids_tensor((batch_size, 7), vocab_size=20)
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+ scores_before_min_length = new_min_dist_processor(input_ids, scores)
+ self.assertListEqual(
+ scores_before_min_length[:, eos_token_id].flatten().tolist(), expected_eos_scores_before_min_length
+ )
+
+ # check that min new length is not applied anymore at length 8
+ input_ids = ids_tensor((batch_size, 8), vocab_size=20)
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+ scores_before_min_length = new_min_dist_processor(input_ids, scores)
+ self.assertFalse(torch.isinf(scores_before_min_length).any())
+
+ # check that min new length is not applied anymore at length 15
+ input_ids = ids_tensor((batch_size, 15), vocab_size=20)
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+ scores_before_min_length = new_min_dist_processor(input_ids, scores)
+ self.assertFalse(torch.isinf(scores_before_min_length).any())
+
+ def test_temperature_dist_warper(self):
+ input_ids = None
+ length = 20
+
+ scores = self._get_uniform_logits(batch_size=2, length=length)
+
+ # tweak scores to not be uniform anymore
+ scores[1, 5] = (1 / length) + 0.1 # peak, 1st batch
+ scores[1, 10] = (1 / length) - 0.4 # valley, 1st batch
+
+ # compute softmax
+ probs = nn.functional.softmax(scores, dim=-1)
+
+ temp_dist_warper_sharper = TemperatureLogitsWarper(temperature=0.5)
+ temp_dist_warper_smoother = TemperatureLogitsWarper(temperature=1.3)
+
+ warped_prob_sharp = nn.functional.softmax(temp_dist_warper_sharper(input_ids, scores), dim=-1)
+ warped_prob_smooth = nn.functional.softmax(temp_dist_warper_smoother(input_ids, scores), dim=-1)
+ processed_scores = temp_dist_warper_smoother(input_ids, scores)
+
+ # uniform distribution stays uniform
+ torch.testing.assert_close(probs[0, :], warped_prob_sharp[0, :], rtol=1e-3, atol=1e-3)
+ torch.testing.assert_close(probs[0, :], warped_prob_smooth[0, :], rtol=1e-3, atol=1e-3)
+
+ # sharp peaks get higher, valleys get lower
+ self.assertLess(probs[1, :].max(), warped_prob_sharp[1, :].max())
+ self.assertGreater(probs[1, :].min(), warped_prob_sharp[1, :].min())
+
+ # smooth peaks get lower, valleys get higher
+ self.assertGreater(probs[1, :].max(), warped_prob_smooth[1, :].max())
+ self.assertLess(probs[1, :].min(), warped_prob_smooth[1, :].min())
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(scores == processed_scores))
+
+ def test_repetition_penalty_dist_process(self):
+ input_ids = torch.tensor([[0, 1], [5, 0]], device=torch_device, dtype=torch.long)
+ vocab_size = 10
+
+ scores = self._get_uniform_logits(batch_size=2, length=vocab_size)
+
+ # give values special values
+ scores[0, 0] = -(1 / vocab_size)
+ scores[1, 5] = 4 / vocab_size
+
+ rep_penalty_proc = RepetitionPenaltyLogitsProcessor(penalty=2.0)
+
+ processed_scores = rep_penalty_proc(input_ids, scores)
+
+ # check that values were correctly changed
+ self.assertAlmostEqual(processed_scores[0, 0].item(), -(1 / vocab_size) * 2)
+ self.assertAlmostEqual(processed_scores[0, 1].item(), (1 / vocab_size) / 2)
+
+ self.assertAlmostEqual(processed_scores[1, 0].item(), (1 / vocab_size) / 2)
+ self.assertAlmostEqual(processed_scores[1, 5].item(), (4 / vocab_size) / 2)
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(scores == processed_scores))
+
+ def test_encoder_repetition_penalty_dist_process(self):
+ input_ids = torch.tensor([[0, 1], [5, 0]], device=torch_device, dtype=torch.long)
+ vocab_size = 10
+
+ scores = self._get_uniform_logits(batch_size=2, length=vocab_size)
+
+ # give values special values
+ scores[0, 0] = -(1 / vocab_size)
+ scores[1, 5] = 4 / vocab_size
+
+ rep_penalty_proc = EncoderRepetitionPenaltyLogitsProcessor(penalty=2.0, encoder_input_ids=input_ids)
+
+ processed_scores = rep_penalty_proc(input_ids, scores)
+
+ # check that values were correctly changed
+ self.assertAlmostEqual(processed_scores[0, 0].item(), -(1 / vocab_size) / 2)
+ self.assertAlmostEqual(processed_scores[0, 1].item(), (1 / vocab_size) * 2)
+
+ self.assertAlmostEqual(processed_scores[1, 0].item(), (1 / vocab_size) * 2)
+ self.assertAlmostEqual(processed_scores[1, 5].item(), (4 / vocab_size) * 2)
+
+ # check that values not in the encoder ids were NOT changed
+ self.assertAlmostEqual(processed_scores[0, 2].item(), (1 / vocab_size))
+ self.assertAlmostEqual(processed_scores[1, 2].item(), (1 / vocab_size))
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(scores == processed_scores))
+
+ def test_top_k_dist_warper(self):
+ input_ids = None
+ vocab_size = 10
+ batch_size = 2
+
+ # create ramp distribution
+ ramp_logits = (
+ torch.arange(vocab_size, device=torch_device, dtype=torch.float).unsqueeze(0).repeat(batch_size, 1)
+ )
+ ramp_logits[1:, : vocab_size // 2] = ramp_logits[1:, : vocab_size // 2] + vocab_size
+
+ top_k_warp = TopKLogitsWarper(3)
+
+ scores = top_k_warp(input_ids, ramp_logits)
+
+ # check that correct tokens are filtered
+ self.assertListEqual(torch.isinf(scores[0]).tolist(), 7 * [True] + 3 * [False])
+ self.assertListEqual(torch.isinf(scores[1]).tolist(), 2 * [True] + 3 * [False] + 5 * [True])
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(scores == ramp_logits))
+
+ # check special cases
+ length = 5
+
+ logits = self._get_uniform_logits(batch_size=batch_size, length=length)
+ top_k_warp_safety_check = TopKLogitsWarper(top_k=1, filter_value=0.0, min_tokens_to_keep=3)
+
+ scores = top_k_warp_safety_check(input_ids, logits)
+ # uniform dist is not changed
+ self.assertListEqual((scores == 0.0).to(torch.long).sum(dim=-1).tolist(), [0, 0])
+
+ ramp_logits = torch.arange(length, device=torch_device, dtype=torch.float).unsqueeze(0).repeat(batch_size, 1)
+ scores = top_k_warp_safety_check(input_ids, ramp_logits)
+
+ # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified
+ self.assertListEqual((scores == 0.0).to(torch.long).sum(dim=-1).tolist(), [2, 2])
+
+ def test_top_p_dist_warper(self):
+ input_ids = None
+ vocab_size = 10
+ batch_size = 2
+
+ # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)
+ dist = torch.log(
+ torch.tensor([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]], device=torch_device, dtype=torch.float)
+ )
+
+ top_p_warp = TopPLogitsWarper(0.8)
+ filtered_dist = torch.exp(top_p_warp(input_ids, dist))
+
+ # dist should be filtered to keep min num values so that sum is >= top_p
+ # exp (-inf) => 0
+ EXPECTED_FILTERED_DIST = torch.tensor(
+ [[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]], device=torch_device, dtype=torch.float
+ )
+ torch.testing.assert_close(filtered_dist, EXPECTED_FILTERED_DIST, rtol=1e-3, atol=1e-3)
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(top_p_warp(input_ids, dist) == dist))
+
+ # check edge cases with negative and extreme logits
+ ramp_logits = torch.arange(vocab_size, device=torch_device, dtype=torch.float).unsqueeze(0).repeat(
+ batch_size, 1
+ ) - (vocab_size // 2)
+
+ # make ramp_logits more extreme
+ ramp_logits[1] = ramp_logits[1] * 100.0
+
+ # make sure at least 2 tokens are kept
+ top_p_warp = TopPLogitsWarper(0.9, min_tokens_to_keep=2, filter_value=0.0)
+ filtered_dist = top_p_warp(input_ids, ramp_logits)
+
+ # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2.
+ self.assertListEqual((filtered_dist != 0.0).to(torch.long).sum(dim=-1).tolist(), [3, 2])
+
+ def test_min_p_dist_warper(self):
+ input_ids = None
+ vocab_size = 10
+ batch_size = 2
+
+ # create distribution and take log (inverse to Softmax as taken in MinPLogitsWarper)
+ dist = torch.log(
+ torch.tensor(
+ [
+ [0.9, 0.0274, 0.047, 0.0274], # two tokens should be kept (0.047 > 0.9*0.05=0.045)
+ [0.15, 0.3, 0.3, 0.25], # all should be kept -- no high-probability token
+ [0.97, 0.01, 0.01, 0.01], # only the first token should be kept
+ ],
+ device=torch_device,
+ dtype=torch.float,
+ )
+ )
+
+ min_p_warp = MinPLogitsWarper(0.05)
+ filtered_dist = torch.exp(min_p_warp(input_ids, dist))
+
+ # exp (-inf) => 0
+ EXPECTED_FILTERED_DIST = torch.tensor(
+ [[0.9, 0.0, 0.047, 0.0], [0.15, 0.3, 0.3, 0.25], [0.97, 0.0, 0.0, 0.0]],
+ device=torch_device,
+ dtype=torch.float,
+ )
+ torch.testing.assert_close(filtered_dist, EXPECTED_FILTERED_DIST, rtol=1e-3, atol=1e-3)
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(min_p_warp(input_ids, dist) == dist))
+
+ # check edge cases with negative and extreme logits
+ ramp_logits = torch.arange(vocab_size, device=torch_device, dtype=torch.float) - (vocab_size // 2)
+ ramp_logits = ramp_logits.unsqueeze(0).repeat(batch_size, 1)
+
+ # make ramp_logits more extreme
+ ramp_logits[1] = ramp_logits[1] * 100.0
+
+ # make sure at least 2 tokens are kept
+ min_p_warp = MinPLogitsWarper(0.9, min_tokens_to_keep=2, filter_value=0.0)
+ filtered_dist = min_p_warp(input_ids, ramp_logits)
+
+ # first batch should keep two tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2.
+ self.assertListEqual((filtered_dist != 0.0).to(torch.long).sum(dim=-1).tolist(), [2, 2])
+
+ def test_typical_dist_warper(self):
+ input_ids = None
+ vocab_size = 10
+ batch_size = 2
+
+ # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)
+ dist = torch.log(
+ torch.tensor([[0.97, 0.01, 0.01, 0.01], [0.4, 0.2, 0.2, 0.2]], device=torch_device, dtype=torch.float)
+ )
+
+ typical_warp = TypicalLogitsWarper(0.5)
+ filtered_dist = torch.exp(typical_warp(input_ids, dist))
+
+ # dist should be filtered to keep min num values so that sum is >= 0.7
+ # exp (-inf) => 0
+ EXPECTED_FILTERED_DIST = torch.tensor(
+ [[0.97, 0.0, 0.0, 0.0], [0.0, 0.2, 0.2, 0.2]], device=torch_device, dtype=torch.float
+ )
+ torch.testing.assert_close(filtered_dist, EXPECTED_FILTERED_DIST, rtol=1e-3, atol=1e-3)
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(typical_warp(input_ids, dist) == dist))
+
+ # check special cases
+ length = 5
+
+ logits = self._get_uniform_logits(batch_size=batch_size, length=length)
+ typical_warp_safety_check = TypicalLogitsWarper(mass=0.5, filter_value=0.0, min_tokens_to_keep=3)
+
+ scores = typical_warp_safety_check(input_ids, logits)
+ # uniform dist is not changed
+ self.assertListEqual((scores == 0.0).to(torch.long).sum(dim=-1).tolist(), [0, 0])
+
+ # check edge cases with negative and extreme logits
+ ramp_logits = torch.arange(vocab_size, device=torch_device, dtype=torch.float).unsqueeze(0).repeat(
+ batch_size, 1
+ ) - (vocab_size // 2)
+
+ # make ramp_logits more extreme
+ ramp_logits[1] = ramp_logits[1] * 100.0
+
+ # make sure at least 2 tokens are kept
+ typical_warp = TypicalLogitsWarper(0.7, min_tokens_to_keep=2, filter_value=0.0)
+ filtered_dist = typical_warp(input_ids, ramp_logits)
+
+ # first batch should keep two tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2.
+ self.assertListEqual((filtered_dist != 0.0).to(torch.long).sum(dim=-1).tolist(), [2, 2])
+
+ def test_epsilon_dist_warper(self):
+ input_ids = None
+ vocab_size = 10
+ batch_size = 2
+
+ # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)
+ dist = torch.log(
+ torch.tensor(
+ [[0.87, 0.099, 0.001, 0.03], [0.4, 0.299, 0.101, 0.2]], device=torch_device, dtype=torch.float
+ )
+ )
+
+ epsilon_warp = EpsilonLogitsWarper(0.1)
+ filtered_dist = torch.exp(epsilon_warp(input_ids, dist))
+
+ # dist should be filtered to only keep values with proba >= 0.1
+ # exp (-inf) => 0
+ EXPECTED_FILTERED_DIST = torch.tensor(
+ [[0.87, 0, 0, 0], [0.4, 0.299, 0.101, 0.2]], device=torch_device, dtype=torch.float
+ )
+ torch.testing.assert_close(filtered_dist, EXPECTED_FILTERED_DIST, rtol=1e-3, atol=1e-3)
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(epsilon_warp(input_ids, dist) == dist))
+
+ # check edge cases with negative and extreme logits
+ ramp_logits = torch.arange(vocab_size, device=torch_device, dtype=torch.float).unsqueeze(0).repeat(
+ batch_size, 1
+ ) - (vocab_size // 2)
+
+ # make ramp_logits more extreme
+ ramp_logits[1] = ramp_logits[1] * 100.0
+
+ # make sure at least 2 tokens are kept
+ epsilon_warp = EpsilonLogitsWarper(5e-2, min_tokens_to_keep=2, filter_value=0.0)
+ filtered_dist = epsilon_warp(input_ids, ramp_logits)
+
+ # first batch should keep 3 tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2.
+ self.assertListEqual((filtered_dist != 0.0).to(torch.long).sum(dim=-1).tolist(), [3, 2])
+
+ def test_eta_dist_warper(self):
+ input_ids = None
+ vocab_size = 10
+ batch_size = 2
+
+ # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)
+ dist = torch.log(
+ torch.tensor([[0.0, 0.1, 0.8, 0.1], [0.01, 0.04, 0.9, 0.05]], device=torch_device, dtype=torch.float)
+ )
+
+ eta_warp = EtaLogitsWarper(0.0625, device=torch_device)
+ filtered_dist = torch.exp(eta_warp(input_ids, dist))
+
+ # dist should be filtered to only keep values with proba >= min(0.0625, sqrt(0.0625) * e^-H(p))
+ # min(0.0625, 0.1320) is the cutoff for the first row and min(0.0625, 0.1644) is for the second
+ # where H is the entropy function and p is the probability vector.
+ # exp (-inf) => 0
+ EXPECTED_FILTERED_DIST = torch.tensor(
+ [[0.0, 0.1, 0.8, 0.1], [0.0, 0.0, 0.9, 0.0]], device=torch_device, dtype=torch.float
+ )
+ torch.testing.assert_close(filtered_dist, EXPECTED_FILTERED_DIST, rtol=1e-3, atol=1e-3)
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(eta_warp(input_ids, dist) == dist))
+
+ # check edge cases with negative and extreme logits
+ ramp_logits = torch.arange(vocab_size, device=torch_device, dtype=torch.float).unsqueeze(0).repeat(
+ batch_size, 1
+ ) - (vocab_size // 2)
+
+ # make ramp_logits more extreme
+ ramp_logits[1] = ramp_logits[1] * 100.0
+
+ # make sure at least 2 tokens are kept
+ eta_warp = EtaLogitsWarper(0.1, min_tokens_to_keep=2, filter_value=0.0, device=torch_device)
+ filtered_dist = eta_warp(input_ids, ramp_logits)
+
+ # first batch should keep 2 tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2.
+ self.assertListEqual((filtered_dist != 0.0).to(torch.long).sum(dim=-1).tolist(), [2, 2])
+
+ def test_no_repeat_ngram_dist_processor(self):
+ vocab_size = 3
+ batch_size = 2
+
+ input_ids = torch.tensor([[1, 1, 2, 1], [0, 1, 0, 1]], device=torch_device, dtype=torch.long)
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+
+ no_repeat_proc_2_gram = NoRepeatNGramLogitsProcessor(2)
+ no_repeat_proc_3_gram = NoRepeatNGramLogitsProcessor(3)
+
+ filtered_scores_2_gram = no_repeat_proc_2_gram(input_ids, scores)
+ filtered_scores_3_gram = no_repeat_proc_3_gram(input_ids, scores)
+
+ # 2-gram would forbid 2nd and 3rd token (1,2) at 1st batch and 1st token (0) at 2nd batch
+ self.assertListEqual(torch.isinf(filtered_scores_2_gram).tolist(), [[False, True, True], [True, False, False]])
+
+ # 3-gram would forbid no token at 1st batch and 1st token (0) at 2nd batch
+ self.assertListEqual(
+ torch.isinf(filtered_scores_3_gram).tolist(), [[False, False, False], [True, False, False]]
+ )
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(scores == filtered_scores_2_gram))
+ self.assertFalse(torch.all(scores == filtered_scores_3_gram))
+
+ def test_encoder_no_repeat_ngram_dist_processor(self):
+ vocab_size = 3
+ num_beams = 2
+ batch_size = 1
+
+ encoder_input_ids = torch.tensor([1, 2, 1, 1], device=torch_device, dtype=torch.long)
+
+ input_ids = torch.tensor([[1, 2, 1], [8, 0, 2]], device=torch_device, dtype=torch.long)
+ scores = self._get_uniform_logits(batch_size * num_beams, vocab_size)
+
+ no_repeat_proc_2_gram = EncoderNoRepeatNGramLogitsProcessor(2, encoder_input_ids=encoder_input_ids)
+ no_repeat_proc_3_gram = EncoderNoRepeatNGramLogitsProcessor(3, encoder_input_ids=encoder_input_ids)
+
+ filtered_scores_2_gram = no_repeat_proc_2_gram(input_ids, scores)
+ filtered_scores_3_gram = no_repeat_proc_3_gram(input_ids, scores)
+
+ # 2-gram would forbid 1st and 2nd token at 1st beam and 1st token (0) at 2nd beam
+ self.assertListEqual(torch.isinf(filtered_scores_2_gram).tolist(), [[False, True, True], [False, True, False]])
+
+ # 3-gram would forbid 1st token at 1st beam and no token at 2nd beam
+ self.assertListEqual(
+ torch.isinf(filtered_scores_3_gram).tolist(), [[False, True, False], [False, False, False]]
+ )
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(scores == filtered_scores_2_gram))
+ self.assertFalse(torch.all(scores == filtered_scores_3_gram))
+
+ # Batched input
+ vocab_size = 3
+ num_beams = 2
+ batch_size = 2
+ encoder_input_ids = torch.tensor([[1, 2, 1, 1], [0, 0, 2, 1]], device=torch_device, dtype=torch.long)
+
+ input_ids = torch.tensor([[1, 2, 1], [1, 0, 2], [0, 0, 0], [0, 2, 2]], device=torch_device, dtype=torch.long)
+ scores = self._get_uniform_logits(batch_size * num_beams, vocab_size)
+
+ no_repeat_proc_2_gram = EncoderNoRepeatNGramLogitsProcessor(2, encoder_input_ids=encoder_input_ids)
+ no_repeat_proc_3_gram = EncoderNoRepeatNGramLogitsProcessor(3, encoder_input_ids=encoder_input_ids)
+
+ filtered_scores_2_gram = no_repeat_proc_2_gram(input_ids, scores.clone())
+ filtered_scores_3_gram = no_repeat_proc_3_gram(input_ids, scores.clone())
+
+ # 2gram
+ # Batch 1
+ # - Beam 1: tokens (1, 2) forbidden
+ # - Beam 2: tokens (1) forbidden
+ # Batch 2
+ # - Beam 1: tokens (0, 2) forbidden
+ # - Beam 2: tokens (1) forbidden
+ self.assertListEqual(
+ torch.isinf(filtered_scores_2_gram).tolist(),
+ [[False, True, True], [False, True, False], [True, False, True], [False, True, False]],
+ )
+
+ # Batch 1
+ # - Beam 1: tokens (1) forbidden
+ # - Beam 2: tokens () forbidden
+ # Batch 2
+ # - Beam 1: tokens (2) forbidden
+ # - Beam 2: tokens () forbidden
+ self.assertListEqual(
+ torch.isinf(filtered_scores_3_gram).tolist(),
+ [[False, True, False], [False, False, False], [False, False, True], [False, False, False]],
+ )
+
+ def test_no_bad_words_dist_processor(self):
+ vocab_size = 5
+ batch_size = 2
+ eos_token_id = 4
+
+ input_ids = torch.tensor([[0, 1, 3, 1], [0, 1, 0, 1]], device=torch_device, dtype=torch.long)
+ bad_word_tokens = [[1], [4], [1, 0], [0, 1, 2], [1, 3, 1, 3]]
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+
+ no_bad_words_dist_proc = NoBadWordsLogitsProcessor(bad_words_ids=bad_word_tokens, eos_token_id=eos_token_id)
+
+ filtered_scores = no_bad_words_dist_proc(input_ids, scores)
+
+ # batch 1: 1st, 2nd, and 4th (0, 1, 3) token are forbidden
+ # batch 2: 1st, 2nd, and 3rd (0, 1, 2) token are forbidden
+ # Note that 5th element cannot be forbidden as it is EOS token
+ self.assertListEqual(
+ torch.isinf(filtered_scores).tolist(), [[True, True, False, True, False], [True, True, True, False, False]]
+ )
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(scores == filtered_scores))
+
+ # check edge case
+ no_bad_words_dist_proc = NoBadWordsLogitsProcessor(bad_words_ids=[[4]], eos_token_id=eos_token_id)
+ filtered_scores = no_bad_words_dist_proc(input_ids, scores)
+ torch.testing.assert_close(scores, filtered_scores, rtol=1e-3, atol=1e-3)
+
+ def test_bias_dist_processor(self):
+ vocab_size = 5
+ batch_size = 2
+
+ input_ids = torch.tensor([[0, 1, 3, 1], [0, 1, 0, 1]], device=torch_device, dtype=torch.long)
+ positive_bias = {(1,): 100.0, (4,): 100.0}
+ negative_bias = {(1, 0): -100.0, (0, 1, 2): -100.0, (1, 3, 1, 3): -100.0}
+ # biases the same termination twice, to ensure we can handle overlapping terminations (it won't have an effect
+ # on the test cases, though)
+ negative_bias.update({(1, 3, 1, 3, 1, 3): -100.0})
+ sequence_bias = {**positive_bias, **negative_bias}
+
+ # scores = 0 to facilitate checks
+ scores = torch.zeros((batch_size, vocab_size), dtype=torch.float, device=torch_device)
+
+ bias_dist_proc = SequenceBiasLogitsProcessor(sequence_bias=sequence_bias)
+ filtered_scores = bias_dist_proc(input_ids, scores)
+
+ # batch 1: positive bias: tokens (1, 4); negative bias: tokens (0, 3); neutral: tokens (2)
+ # batch 2: positive bias: tokens (1, 4); negative bias: tokens (0, 2); neutral: tokens (3)
+ self.assertListEqual(
+ filtered_scores.tolist(), [[-100.0, 100.0, 0.0, -100.0, 100.0], [-100.0, 100.0, -100.0, 0.0, 100.0]]
+ )
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(scores == filtered_scores))
+
+ def test_processor_list(self):
+ batch_size = 4
+ sequence_length = 10
+ vocab_size = 15
+ eos_token_id = 0
+
+ # dummy input_ids and scores
+ input_ids = ids_tensor((batch_size, sequence_length), vocab_size)
+ input_ids_comp = input_ids.clone()
+
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+ scores_comp = scores.clone()
+
+ # instantiate all dist processors
+ min_dist_proc = MinLengthLogitsProcessor(min_length=10, eos_token_id=eos_token_id, device=torch_device)
+ temp_dist_warp = TemperatureLogitsWarper(temperature=0.5)
+ rep_penalty_proc = RepetitionPenaltyLogitsProcessor(penalty=2.0)
+ top_k_warp = TopKLogitsWarper(3)
+ top_p_warp = TopPLogitsWarper(0.8)
+ no_repeat_proc = NoRepeatNGramLogitsProcessor(2)
+ no_bad_words_dist_proc = NoBadWordsLogitsProcessor(bad_words_ids=[[1]], eos_token_id=eos_token_id)
+
+ # no processor list
+ scores = min_dist_proc(input_ids, scores)
+ scores = temp_dist_warp(input_ids, scores)
+ scores = rep_penalty_proc(input_ids, scores)
+ scores = top_k_warp(input_ids, scores)
+ scores = top_p_warp(input_ids, scores)
+ scores = no_repeat_proc(input_ids, scores)
+ scores = no_bad_words_dist_proc(input_ids, scores)
+
+ # with processor list
+ processor = LogitsProcessorList(
+ [
+ min_dist_proc,
+ temp_dist_warp,
+ rep_penalty_proc,
+ top_k_warp,
+ top_p_warp,
+ no_repeat_proc,
+ no_bad_words_dist_proc,
+ ]
+ )
+ scores_comp = processor(input_ids, scores_comp)
+
+ # scores should be equal
+ torch.testing.assert_close(scores, scores_comp, rtol=1e-3, atol=1e-3)
+
+ # input_ids should never be changed
+ self.assertListEqual(input_ids.tolist(), input_ids_comp.tolist())
+
+ def test_prefix_constrained_logits_processor(self):
+ vocab_size = 5
+ batch_size = 2
+
+ input_ids = torch.tensor([[0, 1, 3, 1], [0, 1, 0, 1]], device=torch_device, dtype=torch.long)
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+
+ def prefix_allowed_tokens_fn(batch_id, inputs_ids):
+ return [[0, 1], [2, 3]][batch_id]
+
+ prefix_constrained_logits_proc = PrefixConstrainedLogitsProcessor(prefix_allowed_tokens_fn, 1)
+
+ filtered_scores = prefix_constrained_logits_proc(input_ids, scores)
+
+ # batch 1: 1st, 2nd (0, 1) token are allowed
+ # batch 2: 3rd, 4th (2, 3) token are allowed
+ self.assertListEqual(
+ torch.isinf(filtered_scores).tolist(), [[False, False, True, True, True], [True, True, False, False, True]]
+ )
+
+ def empty_prefix_allowed_tokens_fn(batch_id, inputs_ids):
+ return []
+
+ prefix_constrained_logits_proc = PrefixConstrainedLogitsProcessor(empty_prefix_allowed_tokens_fn, 1)
+
+ self.assertRaises(ValueError, prefix_constrained_logits_proc, input_ids, scores)
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(scores == filtered_scores))
+
+ def test_hamming_diversity(self):
+ vocab_size = 4
+ num_beams = 2
+ num_beam_groups = 2
+
+ scores = self._get_uniform_logits(num_beams, vocab_size)
+ # batch_idx = 0 -> index batch_idx * num_beam_groups -> idx = 0 * 2 = 0 -> penalises tokens 1
+ # batch_idx = 1 -> index batch_idx * num_beam_groups -> idx = 1 * 2 = 2 -> penalises tokens 1
+ current_tokens = torch.tensor([0, 3, 1, 2], device=torch_device, dtype=torch.long)
+
+ diversity_logits_processor = HammingDiversityLogitsProcessor(
+ diversity_penalty=1.0, num_beams=num_beams, num_beam_groups=num_beam_groups
+ )
+
+ processed_scores = diversity_logits_processor(None, scores, current_tokens, 1)
+
+ self.assertTrue(
+ torch.allclose(
+ processed_scores[0], torch.tensor([-0.7500, 0.2500, 0.2500, 0.2500], device=torch_device), atol=1e-3
+ )
+ )
+ self.assertTrue(
+ torch.allclose(
+ processed_scores[1], torch.tensor([0.2500, -0.7500, 0.2500, 0.2500], device=torch_device), atol=1e-3
+ )
+ )
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(scores == processed_scores))
+
+ def test_forced_bos_token_logits_processor(self):
+ vocab_size = 20
+ batch_size = 4
+ bos_token_id = 0
+
+ logits_processor = ForcedBOSTokenLogitsProcessor(bos_token_id=bos_token_id)
+
+ # check that all scores are -inf except the bos_token_id score
+ input_ids = ids_tensor((batch_size, 1), vocab_size=20)
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+ processed_scores = logits_processor(input_ids, scores)
+ self.assertTrue(torch.isneginf(processed_scores[:, bos_token_id + 1 :]).all())
+ # score for bos_token_id shold be zero
+ self.assertListEqual(processed_scores[:, bos_token_id].tolist(), 4 * [0])
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(scores == processed_scores))
+
+ # check that bos_token_id is not forced if current length is greater than 1
+ input_ids = ids_tensor((batch_size, 4), vocab_size=20)
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+ processed_scores = logits_processor(input_ids, scores)
+ self.assertFalse(torch.isinf(processed_scores).any())
+
+ def test_forced_eos_token_logits_processor(self):
+ vocab_size = 20
+ batch_size = 4
+ eos_token_id = 0
+ max_length = 5
+
+ logits_processor = ForcedEOSTokenLogitsProcessor(
+ max_length=max_length, eos_token_id=eos_token_id, device=torch_device
+ )
+
+ # check that all scores are -inf except the eos_token_id when max_length-1 is reached
+ input_ids = ids_tensor((batch_size, 4), vocab_size=20)
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+ processed_scores = logits_processor(input_ids, scores)
+ self.assertTrue(torch.isneginf(processed_scores[:, eos_token_id + 1 :]).all())
+ # score for eos_token_id should be zero
+ self.assertListEqual(processed_scores[:, eos_token_id].tolist(), 4 * [0])
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(scores == processed_scores))
+
+ # check that eos_token_id is not forced if max_length-1 is not reached
+ input_ids = ids_tensor((batch_size, 3), vocab_size=20)
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+ processed_scores = logits_processor(input_ids, scores)
+ self.assertFalse(torch.isinf(processed_scores).any())
+
+ def test_remove_nan_inf_logits_processor(self):
+ scores = torch.tensor(
+ [[0.0, 0.7, 0.8, float("nan")], [0.1, float("inf"), 0.3, float("-inf")]], device=torch_device
+ )
+ input_ids = ids_tensor((2, 4), vocab_size=20)
+
+ logits_processor = InfNanRemoveLogitsProcessor()
+
+ processed_scores = logits_processor(input_ids, scores)
+
+ self.assertTrue(
+ torch.allclose(
+ processed_scores,
+ torch.tensor(
+ [
+ [0.0, 0.7, 0.8, 0.0],
+ [0.1, torch.finfo(processed_scores.dtype).max, 0.3, torch.finfo(processed_scores.dtype).min],
+ ],
+ device=torch_device,
+ ),
+ atol=1e-6,
+ )
+ )
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(scores == processed_scores))
+
+ def test_exponential_decay_length_penalty(self):
+ vocab_size = 20
+ batch_size = 4
+ eos_token_id = 0
+
+ penalty_start = 5
+ penalty_factor = 1.1
+
+ input_ids = ids_tensor((batch_size, 2), vocab_size=vocab_size)
+ input_ids_seq_length = input_ids.shape[-1]
+
+ length_decay_processor = ExponentialDecayLengthPenalty(
+ exponential_decay_length_penalty=(penalty_start, penalty_factor),
+ eos_token_id=eos_token_id,
+ input_ids_seq_length=input_ids_seq_length,
+ )
+
+ # check that penalty is not applied before start
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+ scores_before_start = length_decay_processor(input_ids, scores)
+ self.assertListEqual(scores_before_start[:, eos_token_id].tolist(), scores[:, eos_token_id].tolist())
+
+ # check that penalty is applied after start
+ input_ids = ids_tensor((batch_size, 20), vocab_size=vocab_size)
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+ scores_after_start = length_decay_processor(input_ids, scores)
+ self.assertTrue(torch.gt(scores_after_start[:, eos_token_id], scores[:, eos_token_id]).all())
+
+ # check the penalty increases negative scores
+ input_ids = ids_tensor((batch_size, 20), vocab_size=vocab_size)
+ scores = torch.neg(self._get_uniform_logits(batch_size, vocab_size))
+ scores_after_start = length_decay_processor(input_ids, scores)
+ self.assertTrue(torch.gt(scores_after_start[:, eos_token_id], scores[:, eos_token_id]).all())
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(scores == scores_after_start))
+
+ def test_normalization(self):
+ input_ids = None
+
+ scores = torch.tensor(
+ [[-23.18, -29.96, -43.54, 47.77], [-33.58, -26.87, -32.96, 22.51]], device=torch_device, dtype=torch.float
+ )
+
+ logit_normalization = LogitNormalization()
+ normalized_scores = logit_normalization(input_ids, scores).exp()
+
+ ones = torch.ones(scores.shape[0], device=torch_device, dtype=torch.float)
+ self.assertTrue(normalized_scores.sum(dim=-1).allclose(ones))
+
+ self.assertTrue(normalized_scores.allclose(scores.softmax(dim=-1)))
+
+ # processor should not change logits in-place
+ self.assertFalse(torch.all(scores == normalized_scores))
+
+ def test_classifier_free_guidance(self):
+ class Namespace(dict):
+ pass
+
+ logits_uncond = torch.tensor([[[1.0, 0, 1.5]]])
+ logits_cond = torch.tensor([[[1.0, 1.0, 1.0]]])
+
+ def dummy_model(input_ids, attention_mask, use_cache=True, past_key_values=None):
+ out = Namespace()
+ out.logits = logits_uncond
+ out.past_key_values = None
+ return out
+
+ def lsm(x):
+ return torch.nn.functional.log_softmax(x, dim=-1)
+
+ # explicit unconditional prompt + attention mask
+ input_ids = torch.LongTensor([[0]])
+ cfg = UnbatchedClassifierFreeGuidanceLogitsProcessor(
+ 1.5, dummy_model, input_ids, torch.ones_like(input_ids, dtype=torch.long)
+ )
+ out = cfg(input_ids, logits_cond)[0, -1]
+
+ res = (lsm(logits_uncond) + 1.5 * (lsm(logits_cond) - lsm(logits_uncond)))[0, -1]
+
+ self.assertAlmostEqual(out[0].item(), res[0].item())
+ self.assertAlmostEqual(out[1].item(), res[1].item())
+ self.assertAlmostEqual(out[2].item(), res[2].item())
+
+ # explicit unconditional prompt
+ input_ids = torch.LongTensor([[0]])
+ cfg = UnbatchedClassifierFreeGuidanceLogitsProcessor(1.5, dummy_model, input_ids)
+ out = cfg(input_ids, logits_cond)[0, -1]
+
+ res = (lsm(logits_uncond) + 1.5 * (lsm(logits_cond) - lsm(logits_uncond)))[0, -1]
+
+ self.assertAlmostEqual(out[0].item(), res[0].item())
+ self.assertAlmostEqual(out[1].item(), res[1].item())
+ self.assertAlmostEqual(out[2].item(), res[2].item())
+
+ # all implicit
+ input_ids = torch.LongTensor([[0]])
+ cfg = UnbatchedClassifierFreeGuidanceLogitsProcessor(1.5, dummy_model)
+ out = cfg(input_ids, logits_cond)[0, -1]
+
+ res = (lsm(logits_uncond) + 1.5 * (lsm(logits_cond) - lsm(logits_uncond)))[0, -1]
+
+ self.assertAlmostEqual(out[0].item(), res[0].item())
+ self.assertAlmostEqual(out[1].item(), res[1].item())
+ self.assertAlmostEqual(out[2].item(), res[2].item())
+
+ def test_early_stop_processor(self):
+ input_ids = None
+ eos_token_id = 2
+ min_eos_p = 0.1 ## some small float
+
+ scores = self._get_uniform_logits(2, 4)
+ scores[0][eos_token_id] = -6 ## less than log(min_eos_p)
+
+ esp = BarkEosPrioritizerLogitsProcessor(eos_token_id=eos_token_id, min_eos_p=min_eos_p, device=torch_device)
+ actual_scores = esp(input_ids, scores)
+ expected_scores_list = [
+ scores[0].tolist(),
+ [float("-inf"), float("-inf"), scores[0][0], float("-inf")],
+ ]
+ self.assertListEqual(actual_scores.tolist(), expected_scores_list)
+
+ def test_early_stop_processor_multi_eos(self):
+ input_ids = None
+ eos_token_id = [2, 3]
+ min_eos_p = 0.1 ## some small float
+
+ scores = self._get_uniform_logits(2, 4)
+ scores[0][eos_token_id] = -6 ## less than log(min_eos_p)
+
+ esp = BarkEosPrioritizerLogitsProcessor(eos_token_id=eos_token_id, min_eos_p=min_eos_p, device=torch_device)
+ actual_scores = esp(input_ids, scores)
+ expected_scores_list = [
+ scores[0].tolist(),
+ [float("-inf"), float("-inf"), scores[0][0], scores[0][0]],
+ ]
+ self.assertListEqual(actual_scores.tolist(), expected_scores_list)
+
+ def test_watermarking_processor(self):
+ batch_size = 3
+ vocab_size = 20
+
+ input_ids = ids_tensor((batch_size, 5), vocab_size=20)
+ scores = self._get_uniform_logits(batch_size, vocab_size)
+
+ # raise error if incorrect seeding_scheme is passed
+ with self.assertRaises(ValueError):
+ WatermarkLogitsProcessor(vocab_size=vocab_size, device="cpu", seeding_scheme="hash")
+
+ # raise error if the greenlist_ratio in not in range (0.0, 1.0)
+ with self.assertRaises(ValueError):
+ WatermarkLogitsProcessor(vocab_size=vocab_size, device="cpu", greenlist_ratio=1.2)
+
+ watermark = WatermarkLogitsProcessor(vocab_size=vocab_size, device=input_ids.device)
+
+ # use fixed id for last token, needed for reprodicibility and tests
+ input_ids[:, -1] = 10
+ scores_wo_bias = scores[:, -1].clone()
+ out = watermark(input_ids=input_ids, scores=scores)
+ self.assertTrue((out[:, 1] == scores_wo_bias + watermark.bias).all())
+
+ @parameterized.expand([(5, 3, 10000), (10, 5, 1000)])
+ def test_synthidtext_watermarking_processor_bias_uniformity(self, ngram_len, num_layers, vocab_size):
+ """Test SynthID watermarked distribution bias uniformity over iterations."""
+ torch.manual_seed(0)
+ np.random.seed(0)
+ watermarking_config = {
+ "ngram_len": ngram_len,
+ "keys": np.random.randint(low=0, high=2**16, size=(num_layers,)),
+ "sampling_table_size": 2**16,
+ "sampling_table_seed": 0,
+ "context_history_size": 512,
+ "device": torch_device,
+ }
+ batch_size = 100000
+ ngrams = torch.randint(
+ low=0,
+ high=vocab_size,
+ size=(batch_size, ngram_len),
+ device=torch_device,
+ )
+
+ logits_processor = SynthIDTextWatermarkLogitsProcessor(**watermarking_config)
+ g_values = logits_processor.compute_g_values(ngrams)
+ g_values_mean = torch.mean(torch.mean(g_values.float(), dim=0))
+ self.assertAlmostEqual(g_values_mean, 0.5, delta=0.01)
+
+ @parameterized.expand([(10000, 3), (1000, 20)])
+ def test_synthidtext_watermark_processor_bias_uniformity_across_vocab(self, vocab_size, num_layers):
+ """Test SynthID watermarked distribution bias uniformity over vocabs of the model."""
+ batch_size = 1000
+ ngram_len = 5
+ torch.manual_seed(0)
+ np.random.seed(0)
+ watermarking_config = {
+ "ngram_len": ngram_len,
+ "keys": np.random.randint(low=0, high=2**16, size=(num_layers,)),
+ "sampling_table_size": 2**16,
+ "sampling_table_seed": 0,
+ "context_history_size": 512,
+ "device": torch_device,
+ }
+ n_minus_1_grams = torch.randint(
+ low=0,
+ high=vocab_size,
+ size=(batch_size, watermarking_config["ngram_len"] - 1),
+ device=torch_device,
+ )
+
+ logits_processor = SynthIDTextWatermarkLogitsProcessor(**watermarking_config)
+ ngram_keys, _ = logits_processor._compute_keys(
+ n_minus_1_grams,
+ torch.stack([torch.arange(vocab_size, device=torch_device) for _ in range(batch_size)]),
+ )
+
+ g_values = logits_processor.sample_g_values(ngram_keys)
+ # g_values shape should be [batch_size, vocab_size, num_layers]
+ g_values_mean = torch.mean(torch.mean(g_values.float(), dim=1))
+ self.assertAlmostEqual(g_values_mean, 0.5, delta=0.001)
+
+ @parameterized.expand([(2, "uniform"), (10, "uniform"), (2, "random"), (10, "random")])
+ def test_synthidtext_watermark_processor_distributional_convergence(self, vocab_size, logits_type):
+ """Check if watermarked distribution converges to unwatermarked logits distribution."""
+ batch_size = 1500
+ num_keys = 1000
+
+ updated_softmaxes = 0
+ np.random.seed(0)
+ torch.manual_seed(0)
+ if logits_type == "uniform":
+ fixed_logits = torch.ones((batch_size, vocab_size), device=torch_device)
+ elif logits_type == "random":
+ fixed_logits = torch.rand(
+ (
+ 1,
+ vocab_size,
+ ),
+ device=torch_device,
+ )
+ fixed_logits = fixed_logits.repeat(batch_size, 1)
+ else:
+ raise ValueError(f"Unrecognized logits_type {logits_type}")
+ for _ in range(num_keys):
+ watermarking_config = {
+ "ngram_len": 5,
+ "keys": np.random.randint(0, 10**9, size=(1,), dtype=np.int64),
+ "sampling_table_size": 2**16,
+ "sampling_table_seed": 0,
+ "context_history_size": 1024,
+ "device": torch_device,
+ }
+
+ logits_processor = SynthIDTextWatermarkLogitsProcessor(**watermarking_config)
+
+ ngrams = torch.randint(
+ low=0,
+ high=vocab_size,
+ size=(batch_size, watermarking_config["ngram_len"]),
+ device=torch_device,
+ )
+
+ # Insert ngram-1 into logit_processor state.
+ for idx in range(watermarking_config["ngram_len"] - 1):
+ _ = logits_processor(ngrams[:, :idx], fixed_logits)
+
+ updated_scores = logits_processor(ngrams, fixed_logits)
+ updated_softmaxes += torch.nn.functional.softmax(updated_scores, dim=1).cpu().numpy()
+
+ updated_softmaxes = np.mean(updated_softmaxes, axis=0) / num_keys
+ is_close = torch.all(
+ torch.isclose(
+ torch.tensor(updated_softmaxes, device=torch_device),
+ torch.nn.Softmax()(fixed_logits[0]), # Take any batch entry, all are same.
+ atol=1e-3,
+ rtol=0,
+ )
+ )
+ self.assertTrue(is_close)
+
+ @parameterized.expand([(2, 10, 1, 0.01), (100, 5, 1, 0.01), (100, 10, 2, 0.02)])
+ def test_synthidtext_watermark_processor_bias_test(self, vocab_size, ngram_len, num_layers, atol):
+ """Test SynthID watermarking bias matches theoretical value."""
+ batch_size = 20000
+ generator = torch.Generator(device=torch_device).manual_seed(0)
+ np.random.seed(0)
+
+ keys = [np.random.randint(0, 10**9) for _ in range(num_layers)]
+ # Use 10**9 rather than vocab_size to ensure variety in (n-1)-grams.
+ context = torch.randint(
+ low=0,
+ high=10**9,
+ size=(batch_size, ngram_len - 1),
+ dtype=torch.int64,
+ generator=generator,
+ device=torch_device,
+ )
+
+ context_history_size = 1024
+ logits_processor = SynthIDTextWatermarkLogitsProcessor(
+ ngram_len=ngram_len,
+ keys=keys,
+ sampling_table_size=2**16,
+ sampling_table_seed=0,
+ context_history_size=context_history_size,
+ device=torch_device,
+ )
+
+ scores = torch.ones(
+ (batch_size, vocab_size),
+ dtype=torch.float64,
+ device=torch_device,
+ )
+ # Init state of the logits processor.
+ logits_processor(context, scores)
+ # insert context into the state.
+ for idx in range(1, ngram_len - 1):
+ _ = logits_processor(context[:, :idx], scores)
+
+ updated_scores = logits_processor(context, scores)
+
+ probs = torch.nn.functional.softmax(updated_scores, dim=1)
+ generator = torch.Generator(device=torch_device).manual_seed(0)
+ next_tokens = torch.multinomial(
+ probs,
+ num_samples=1,
+ generator=generator,
+ )
+
+ ngrams = torch.concat((context, next_tokens), dim=1)
+ g_values = logits_processor.compute_g_values(ngrams)
+ mean_g_values = g_values.mean(dtype=torch.float64, dim=(0, 1))
+
+ expected_mean_g_value = logits_processor.expected_mean_g_value(
+ vocab_size=vocab_size,
+ )
+ is_close = torch.all(
+ torch.isclose(
+ mean_g_values,
+ torch.tensor(expected_mean_g_value, dtype=torch.float64, device=torch_device),
+ atol=atol,
+ rtol=0,
+ )
+ )
+ self.assertTrue(is_close)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_stopping_criteria.py b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_stopping_criteria.py
new file mode 100644
index 0000000000000000000000000000000000000000..ace7d496dab607e1190b7476395d17e027d57ae7
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_stopping_criteria.py
@@ -0,0 +1,290 @@
+# coding=utf-8
+# Copyright 2020 The HuggingFace Team Inc.
+#
+# 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 clone 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 time
+import unittest
+
+from transformers import AutoTokenizer, is_torch_available
+from transformers.testing_utils import require_torch, torch_device
+
+from ..test_modeling_common import ids_tensor
+
+
+if is_torch_available():
+ import torch
+
+ from transformers.generation import (
+ ConfidenceCriteria,
+ EosTokenCriteria,
+ MaxLengthCriteria,
+ MaxTimeCriteria,
+ StoppingCriteriaList,
+ StopStringCriteria,
+ validate_stopping_criteria,
+ )
+
+
+@require_torch
+class StoppingCriteriaTestCase(unittest.TestCase):
+ def _get_tensors(self, length):
+ batch_size = 3
+ vocab_size = 250
+
+ input_ids = ids_tensor((batch_size, length), vocab_size)
+ scores = torch.ones((batch_size, length), device=torch_device, dtype=torch.float) / length
+ return input_ids, scores
+
+ def test_list_criteria(self):
+ input_ids, scores = self._get_tensors(5)
+
+ criteria = StoppingCriteriaList(
+ [
+ MaxLengthCriteria(max_length=10),
+ MaxTimeCriteria(max_time=0.1),
+ ]
+ )
+
+ self.assertFalse(all(criteria(input_ids, scores)))
+
+ input_ids, scores = self._get_tensors(9)
+ self.assertFalse(all(criteria(input_ids, scores)))
+
+ input_ids, scores = self._get_tensors(10)
+ self.assertTrue(all(criteria(input_ids, scores)))
+
+ def test_max_length_criteria(self):
+ criteria = MaxLengthCriteria(max_length=10)
+
+ input_ids, scores = self._get_tensors(5)
+ self.assertFalse(all(criteria(input_ids, scores)))
+
+ input_ids, scores = self._get_tensors(9)
+ self.assertFalse(all(criteria(input_ids, scores)))
+
+ input_ids, scores = self._get_tensors(10)
+ self.assertTrue(all(criteria(input_ids, scores)))
+
+ def test_max_time_criteria(self):
+ input_ids, scores = self._get_tensors(5)
+
+ criteria = MaxTimeCriteria(max_time=0.1)
+ self.assertFalse(all(criteria(input_ids, scores)))
+
+ criteria = MaxTimeCriteria(max_time=0.1, initial_timestamp=time.time() - 0.2)
+ self.assertTrue(all(criteria(input_ids, scores)))
+
+ def test_eos_token_criteria(self):
+ criteria = EosTokenCriteria(eos_token_id=0)
+
+ input_ids, scores = self._get_tensors(5)
+ input_ids[:, -1] = 0
+ self.assertTrue(all(criteria(input_ids, scores)))
+
+ input_ids, scores = self._get_tensors(5)
+ input_ids[:2, -1] = 0
+ input_ids[2, -1] = 1
+ self.assertListEqual(criteria(input_ids, scores).tolist(), [True, True, False])
+
+ input_ids, scores = self._get_tensors(5)
+ input_ids[:, -1] = 1
+ self.assertListEqual(criteria(input_ids, scores).tolist(), [False, False, False])
+
+ def test_confidence_criteria(self):
+ criteria = ConfidenceCriteria(assistant_confidence_threshold=0.5)
+
+ vocab_size = 250
+ length = 5
+
+ input_ids = ids_tensor((1, length), vocab_size)
+ scores = (torch.randn((1, vocab_size)),)
+
+ # Simulate high confidence by setting the probability of the last token to be high
+ scores[0][0, input_ids[0, -1]] = 10.0 # Logits before softmax
+ self.assertFalse(criteria(input_ids, scores))
+
+ # Simulate low confidence by setting the probability of the last token to be low
+ scores[0][0, input_ids[0, -1]] = -10.0 # Logits before softmax
+ self.assertTrue(criteria(input_ids, scores))
+
+ def test_validate_stopping_criteria(self):
+ validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10)]), 10)
+
+ with self.assertWarns(UserWarning):
+ validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10)]), 11)
+
+ stopping_criteria = validate_stopping_criteria(StoppingCriteriaList(), 11)
+
+ self.assertEqual(len(stopping_criteria), 1)
+
+ def test_stop_string_criteria(self):
+ true_strings = [
+ "<|im_start|><|im_end|>",
+ "<|im_start|><|im_end|<|im_end|>",
+ ">><|im_start|>>stop",
+ "stop",
+ "e nd",
+ ]
+ false_strings = [
+ "<|im_start|><|im_end|",
+ "<|im_start|><|im_end|<|im_end|",
+ "<|im_end|><|im_start|>",
+ "<|im_end|<>stop<|im_end|",
+ "end",
+ "en d",
+ "eNd",
+ "<|im_end|",
+ "|im_end|>",
+ "s",
+ ]
+ stop_strings = ["<|im_end|>", "stop", "e nd"]
+
+ # Use a tokenizer that won't actually have special tokens for these
+ tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
+ tokenizer.pad_token_id = tokenizer.eos_token_id
+ tokenizer.padding_side = "left"
+ true_input_ids = tokenizer(true_strings, return_tensors="pt", padding="longest", add_special_tokens=False)
+ false_input_ids = tokenizer(false_strings, return_tensors="pt", padding="longest", add_special_tokens=False)
+
+ scores = None
+ criteria = StopStringCriteria(tokenizer=tokenizer, stop_strings=stop_strings)
+ for i in range(len(true_strings)):
+ self.assertTrue(criteria(true_input_ids["input_ids"][i : i + 1], scores))
+ for i in range(len(false_strings)):
+ self.assertFalse(criteria(false_input_ids["input_ids"][i : i + 1], scores))
+
+ # Now try it with a tokenizer where those are actually special tokens
+ tokenizer = AutoTokenizer.from_pretrained("cognitivecomputations/dolphin-2.5-mixtral-8x7b")
+ tokenizer.padding_side = "left"
+ true_input_ids = tokenizer(true_strings, return_tensors="pt", padding="longest", add_special_tokens=False)
+ false_input_ids = tokenizer(false_strings, return_tensors="pt", padding="longest", add_special_tokens=False)
+
+ criteria = StopStringCriteria(tokenizer=tokenizer, stop_strings=stop_strings)
+ for i in range(len(true_strings)):
+ self.assertTrue(criteria(true_input_ids["input_ids"][i : i + 1], scores))
+ for i in range(len(false_strings)):
+ self.assertFalse(criteria(false_input_ids["input_ids"][i : i + 1], scores))
+
+ def test_stop_string_criteria_vocab_size_mismatch(self):
+ """Test that StopStringCriteria handles tokens above len(tokenizer) correctly."""
+ tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
+
+ # Create input_ids with tokens above len(tokenizer)
+ input_ids = torch.tensor([[len(tokenizer) + 1024, 1, 2]], device=torch_device)
+ scores = None
+ criteria = StopStringCriteria(tokenizer=tokenizer, stop_strings=["test"])
+
+ # This should not raise an error and should return False since no stop string is matched
+ self.assertFalse(criteria(input_ids, scores))
+
+ def test_stop_string_matching_positions(self):
+ stop_string = "stop"
+ token_list = ["last", "top", "topper", "s", "p"]
+ token_indices = list(range(len(token_list)))
+ all_token_valid_positions, all_token_end_overlaps = StopStringCriteria._stop_string_get_matching_positions(
+ token_list=token_list, token_indices=token_indices, stop_strings=[stop_string]
+ )
+ valid_positions = {
+ token_list[idx]: positions for idx, positions in all_token_valid_positions[stop_string].items()
+ }
+ end_overlaps = {token_list[idx]: overlaps for idx, overlaps in all_token_end_overlaps[stop_string].items()}
+ self.assertEqual(valid_positions, {"s": [3], "last": [2]})
+ self.assertEqual(end_overlaps, {"top": [3], "topper": [3], "p": [1]})
+
+ def test_stop_string_embedding_vecs(self):
+ stop_string = "stop"
+ token_list = ["last", "top", "topper", "s", "p"]
+ token_indices = list(range(len(token_list)))
+ embedding_vec, max_valid_positions, max_valid_end_lens = StopStringCriteria._stop_string_create_embedding_vec(
+ token_list=token_list, token_indices=token_indices, stop_strings=[stop_string]
+ )
+
+ # Positions inside the stop string where the token matches (excluding end overlaps)
+ valid_positions = embedding_vec[:, 0].tolist()
+ self.assertEqual(valid_positions, [2, -1, -1, 3, -1, -1])
+
+ # Overlap lengths between end of stop string and start of token
+ end_overlaps = embedding_vec[:, 1].tolist()
+ self.assertEqual(end_overlaps, [-1, 3, 3, -1, 1, -1])
+
+ # Length of each token
+ token_lengths = embedding_vec[:-1, 2].tolist()
+ self.assertEqual(token_lengths, [len(token) for token in token_list])
+
+ def test_single_letter_stop_string(self):
+ true_strings = ["a", "baa", "abc"] # "abc" is a single token
+ false_strings = ["abbbbbbb", "b"] # "abbbbbbb" is split into multiple tokens
+ stop_strings = ["a"]
+ tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
+ tokenizer.pad_token_id = tokenizer.eos_token_id
+ tokenizer.padding_side = "left"
+
+ true_input_ids = tokenizer(true_strings, return_tensors="pt", padding="longest", add_special_tokens=False)
+ false_input_ids = tokenizer(false_strings, return_tensors="pt", padding="longest", add_special_tokens=False)
+
+ scores = None
+ criteria = StopStringCriteria(tokenizer=tokenizer, stop_strings=stop_strings)
+ for input_ids in true_input_ids["input_ids"]:
+ self.assertTrue(criteria(input_ids.unsqueeze(0), scores))
+ for input_ids in false_input_ids["input_ids"]:
+ self.assertFalse(criteria(input_ids.unsqueeze(0), scores))
+
+ def test_criterias_per_row(self):
+ text = "They completed the challenging puzzle, revealing the hidden image at the end"
+ stop_strings = ["end"]
+
+ tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
+ tokenizer.pad_token_id = tokenizer.eos_token_id
+ inputs = tokenizer(text, return_tensors="pt", add_special_tokens=False)
+
+ scores = None
+ criteria = StoppingCriteriaList(
+ [
+ MaxLengthCriteria(max_length=20),
+ StopStringCriteria(tokenizer=tokenizer, stop_strings=stop_strings),
+ ]
+ )
+
+ # trigger stopping when at leat one criteria is satisfied, one value per batch
+ self.assertTrue(criteria(inputs["input_ids"], scores))
+
+ # return False when neither is satisfied
+ self.assertFalse(criteria(inputs["input_ids"][:, :-1], scores))
+
+ def test_criterias_per_row_batched(self):
+ text = [
+ "They completed the challenging puzzle, revealing the hidden image at the end",
+ "Today a dragon flew over France",
+ "The aroma of freshly baked pizza filled the kitchen",
+ ]
+ stop_strings = ["end"]
+
+ tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
+ tokenizer.pad_token_id = tokenizer.eos_token_id
+ tokenizer.padding_side = "left"
+ inputs = tokenizer(text, return_tensors="pt", padding="longest", add_special_tokens=False)
+
+ scores = None
+ criteria = StoppingCriteriaList(
+ [
+ MaxLengthCriteria(max_length=20),
+ StopStringCriteria(tokenizer=tokenizer, stop_strings=stop_strings),
+ ]
+ )
+
+ # trigger stopping when at leat one criteria is satisfied
+ self.assertListEqual(criteria(inputs["input_ids"], scores).tolist(), [True, False, False])
+
+ # False when neither is satisfied
+ self.assertListEqual(criteria(inputs["input_ids"][:, :-1], scores).tolist(), [False, False, False])
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_streamers.py b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_streamers.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b17b6a7c43a04072a6872401a45f9d924a9bbdd
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_streamers.py
@@ -0,0 +1,175 @@
+# coding=utf-8
+# Copyright 2023 The HuggingFace Team Inc.
+#
+# 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 clone 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 unittest
+from queue import Empty
+from threading import Thread
+from unittest.mock import patch
+
+import pytest
+
+from transformers import (
+ AsyncTextIteratorStreamer,
+ AutoTokenizer,
+ TextIteratorStreamer,
+ TextStreamer,
+ is_torch_available,
+)
+from transformers.testing_utils import CaptureStdout, require_torch, torch_device
+from transformers.utils.logging import _get_library_root_logger
+
+from ..test_modeling_common import ids_tensor
+
+
+if is_torch_available():
+ import torch
+
+ from transformers import AutoModelForCausalLM
+
+
+@require_torch
+class StreamerTester(unittest.TestCase):
+ def test_text_streamer_matches_non_streaming(self):
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ model.config.eos_token_id = -1
+
+ input_ids = ids_tensor((1, 5), vocab_size=model.config.vocab_size).to(torch_device)
+ greedy_ids = model.generate(input_ids, max_new_tokens=10, do_sample=False)
+ greedy_text = tokenizer.decode(greedy_ids[0])
+
+ with CaptureStdout() as cs:
+ streamer = TextStreamer(tokenizer)
+ model.generate(input_ids, max_new_tokens=10, do_sample=False, streamer=streamer)
+ # The greedy text should be printed to stdout, except for the final "\n" in the streamer
+ streamer_text = cs.out[:-1]
+
+ self.assertEqual(streamer_text, greedy_text)
+
+ def test_iterator_streamer_matches_non_streaming(self):
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ model.config.eos_token_id = -1
+
+ input_ids = ids_tensor((1, 5), vocab_size=model.config.vocab_size).to(torch_device)
+ greedy_ids = model.generate(input_ids, max_new_tokens=10, do_sample=False)
+ greedy_text = tokenizer.decode(greedy_ids[0])
+
+ streamer = TextIteratorStreamer(tokenizer)
+ generation_kwargs = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer}
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
+ thread.start()
+ streamer_text = ""
+ for new_text in streamer:
+ streamer_text += new_text
+
+ self.assertEqual(streamer_text, greedy_text)
+
+ def test_text_streamer_skip_prompt(self):
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ model.config.eos_token_id = -1
+
+ input_ids = ids_tensor((1, 5), vocab_size=model.config.vocab_size).to(torch_device)
+ greedy_ids = model.generate(input_ids, max_new_tokens=10, do_sample=False)
+ new_greedy_ids = greedy_ids[:, input_ids.shape[1] :]
+ new_greedy_text = tokenizer.decode(new_greedy_ids[0])
+
+ with CaptureStdout() as cs:
+ streamer = TextStreamer(tokenizer, skip_prompt=True)
+ model.generate(input_ids, max_new_tokens=10, do_sample=False, streamer=streamer)
+ # The greedy text should be printed to stdout, except for the final "\n" in the streamer
+ streamer_text = cs.out[:-1]
+
+ self.assertEqual(streamer_text, new_greedy_text)
+
+ def test_text_streamer_decode_kwargs(self):
+ # Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested
+ # with actual models -- the dummy models' tokenizers are not aligned with their models, and
+ # `skip_special_tokens=True` has no effect on them
+ tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
+ model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2").to(torch_device)
+ model.config.eos_token_id = -1
+
+ input_ids = torch.ones((1, 5), device=torch_device).long() * model.config.bos_token_id
+
+ root = _get_library_root_logger()
+ with patch.object(root, "propagate", False):
+ with CaptureStdout() as cs:
+ streamer = TextStreamer(tokenizer, skip_special_tokens=True)
+ model.generate(input_ids, max_new_tokens=1, do_sample=False, streamer=streamer)
+
+ # The prompt contains a special token, so the streamer should not print it. As such, the output text, when
+ # re-tokenized, must only contain one token
+ streamer_text = cs.out[:-1] # Remove the final "\n"
+ streamer_text_tokenized = tokenizer(streamer_text, return_tensors="pt")
+ self.assertEqual(streamer_text_tokenized.input_ids.shape, (1, 1))
+
+ def test_iterator_streamer_timeout(self):
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ model.config.eos_token_id = -1
+
+ input_ids = ids_tensor((1, 5), vocab_size=model.config.vocab_size).to(torch_device)
+ streamer = TextIteratorStreamer(tokenizer, timeout=0.001)
+ generation_kwargs = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer}
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
+ thread.start()
+
+ # The streamer will timeout after 0.001 seconds, so an exception will be raised
+ with self.assertRaises(Empty):
+ streamer_text = ""
+ for new_text in streamer:
+ streamer_text += new_text
+
+
+@require_torch
+@pytest.mark.asyncio(loop_scope="class")
+class AsyncStreamerTester(unittest.IsolatedAsyncioTestCase):
+ async def test_async_iterator_streamer_matches_non_streaming(self):
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ model.config.eos_token_id = -1
+
+ input_ids = ids_tensor((1, 5), vocab_size=model.config.vocab_size).to(torch_device)
+ greedy_ids = model.generate(input_ids, max_new_tokens=10, do_sample=False)
+ greedy_text = tokenizer.decode(greedy_ids[0])
+
+ streamer = AsyncTextIteratorStreamer(tokenizer)
+ generation_kwargs = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer}
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
+ thread.start()
+ streamer_text = ""
+ async for new_text in streamer:
+ streamer_text += new_text
+
+ self.assertEqual(streamer_text, greedy_text)
+
+ async def test_async_iterator_streamer_timeout(self):
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ model.config.eos_token_id = -1
+
+ input_ids = ids_tensor((1, 5), vocab_size=model.config.vocab_size).to(torch_device)
+ streamer = AsyncTextIteratorStreamer(tokenizer, timeout=0.001)
+ generation_kwargs = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer}
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
+ thread.start()
+
+ # The streamer will timeout after 0.001 seconds, so TimeoutError will be raised
+ with self.assertRaises(TimeoutError):
+ streamer_text = ""
+ async for new_text in streamer:
+ streamer_text += new_text
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_utils.py b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f662c51cfc4bb40988e9233e016cc38dca84e25c
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/generation/test_utils.py
@@ -0,0 +1,4957 @@
+# coding=utf-8
+# Copyright 2020 The HuggingFace Team Inc.
+#
+# 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 clone 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 collections
+import copy
+import datetime
+import gc
+import inspect
+import random
+import tempfile
+import unittest
+import warnings
+
+import numpy as np
+import pytest
+from packaging import version
+from parameterized import parameterized
+
+from transformers import AutoConfig, AutoProcessor, AutoTokenizer, is_torch_available, pipeline
+from transformers.testing_utils import (
+ is_flaky,
+ require_accelerate,
+ require_flash_attn,
+ require_optimum_quanto,
+ require_torch,
+ require_torch_accelerator,
+ require_torch_gpu,
+ require_torch_multi_accelerator,
+ require_torch_multi_gpu,
+ require_torch_sdpa,
+ set_config_for_less_flaky_test,
+ set_model_for_less_flaky_test,
+ set_model_tester_for_less_flaky_test,
+ slow,
+ torch_device,
+)
+from transformers.utils import is_ipex_available
+
+
+if is_torch_available():
+ import torch
+ import torch.nn.functional as F
+
+ from transformers import (
+ AutoModelForCausalLM,
+ AutoModelForSeq2SeqLM,
+ AutoModelForSpeechSeq2Seq,
+ AutoModelForVision2Seq,
+ BartForConditionalGeneration,
+ BartTokenizer,
+ GPT2LMHeadModel,
+ GPT2Tokenizer,
+ ImageGPTForCausalImageModeling,
+ SpeechEncoderDecoderModel,
+ T5ForConditionalGeneration,
+ )
+ from transformers.cache_utils import (
+ Cache,
+ DynamicCache,
+ EncoderDecoderCache,
+ HybridCache,
+ QuantoQuantizedCache,
+ StaticCache,
+ )
+ from transformers.generation import (
+ BeamSampleDecoderOnlyOutput,
+ BeamSampleEncoderDecoderOutput,
+ BeamSearchDecoderOnlyOutput,
+ BeamSearchEncoderDecoderOutput,
+ DisjunctiveConstraint,
+ GenerateBeamDecoderOnlyOutput,
+ GenerateBeamEncoderDecoderOutput,
+ GenerateDecoderOnlyOutput,
+ GenerateEncoderDecoderOutput,
+ GenerationConfig,
+ GreedySearchDecoderOnlyOutput,
+ GreedySearchEncoderDecoderOutput,
+ LogitsProcessorList,
+ MaxLengthCriteria,
+ MinLengthLogitsProcessor,
+ PhrasalConstraint,
+ PromptLookupCandidateGenerator,
+ SampleDecoderOnlyOutput,
+ SampleEncoderDecoderOutput,
+ StoppingCriteria,
+ StoppingCriteriaList,
+ SynthIDTextWatermarkingConfig,
+ WatermarkDetector,
+ WatermarkingConfig,
+ )
+ from transformers.generation.candidate_generator import (
+ AssistedCandidateGenerator,
+ AssistedCandidateGeneratorDifferentTokenizers,
+ )
+ from transformers.generation.utils import _speculative_sampling
+
+from unittest.mock import patch
+
+from transformers.utils import is_sklearn_available
+
+
+# TODO: raushan remove this when VLMs start accepting input embeds
+VLM_CLASS_NAMES = [
+ "llava",
+ "idefics2",
+ "idefics3",
+ "mllama",
+ "paligemma",
+ "emu3",
+ "gotocr2",
+ "qwen2vl",
+ "qwen2_5_vl",
+ "ayavision",
+ "gemma3",
+ "mistral3",
+]
+
+
+class GenerationTesterMixin:
+ input_name = "input_ids"
+ model_tester = None
+ max_new_tokens = 3
+
+ def prepare_config_and_inputs_for_generate(self, batch_size=2):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+
+ # We don't want a few model inputs in our model input dictionary for generation tests
+ input_keys_to_ignore = [
+ # we don't want to mask attention heads
+ "head_mask",
+ "decoder_head_mask",
+ "cross_attn_head_mask",
+ # we don't want encoder-decoder models to start from filled decoder ids
+ "decoder_input_ids",
+ "decoder_attention_mask",
+ # we'll set cache use in each test differently
+ "use_cache",
+ # Ignore labels if it is in the input dict
+ "labels",
+ # model-specific exceptions should overload/overwrite this function
+ ]
+ filtered_inputs_dict = {
+ k: v[:batch_size, ...] if isinstance(v, torch.Tensor) else v
+ for k, v in inputs_dict.items()
+ if k not in input_keys_to_ignore
+ }
+
+ # It is important set `eos_token_id` to `None` to avoid early stopping (would break for length-based checks)
+ text_gen_config = config.get_text_config(decoder=True)
+ if text_gen_config.eos_token_id is not None and text_gen_config.pad_token_id is None:
+ text_gen_config.pad_token_id = (
+ text_gen_config.eos_token_id
+ if isinstance(text_gen_config.eos_token_id, int)
+ else text_gen_config.eos_token_id[0]
+ )
+ text_gen_config.eos_token_id = None
+ text_gen_config.forced_eos_token_id = None
+
+ return config, filtered_inputs_dict
+
+ def _check_similar_generate_outputs(self, output_1, output_2, atol=1e-5, rtol=1e-5):
+ """
+ Checks whether a pair of generate outputs are similar. Two `generate` call outputs are considered similar in
+ the following siturations:
+ 1. The sequences are the same
+ 2. The sequences are different, but the scores up to (and including) the first mismatch are nearly identical
+ """
+ # scores doesn't include data regarding decoder input tokens
+ decoder_input_length = output_1.sequences.shape[1] - len(output_1.scores)
+ output_matches = output_1.sequences == output_2.sequences
+ has_matching_outputs = output_matches.all()
+ has_matching_scores = None
+ if not has_matching_outputs:
+ for batch_idx in range(output_1.sequences.shape[0]):
+ batch_matches = output_matches[batch_idx]
+ if batch_matches.all():
+ continue
+ first_mismatch_idx = batch_matches.int().argmin() # gets the index of the first False
+ first_mismatch_idx -= decoder_input_length
+ output_1_first_mismatch_scores = output_1.scores[first_mismatch_idx][batch_idx]
+ output_2_first_mismatch_scores = output_2.scores[first_mismatch_idx][batch_idx]
+ has_matching_scores = torch.allclose(
+ output_1_first_mismatch_scores, output_2_first_mismatch_scores, rtol=atol, atol=rtol
+ )
+ if not has_matching_scores:
+ break
+ self.assertTrue(has_matching_outputs or has_matching_scores)
+
+ def _get_logits_processor_kwargs(self, do_sample=False, config=None):
+ logits_processor_kwargs = {
+ "bad_words_ids": [[1, 0]],
+ "repetition_penalty": 1.2,
+ "remove_invalid_values": True,
+ }
+ if do_sample:
+ logits_processor_kwargs.update(
+ {
+ "top_k": 10,
+ "top_p": 0.7,
+ "temperature": 0.7,
+ }
+ )
+ # TODO (joao, raushan): see this comment for a long-term fix
+ # https://github.com/huggingface/transformers/pull/33593#issuecomment-2361824264)
+ # This is a band-aid for VLM models, to ensure they don't generate image/video tokens which would cause them
+ # to crash. On pretrained models this isn't a risk, as they are trained to not generate these tokens.
+ if config is not None:
+ for key in [
+ "image_token_index",
+ "image_token_id",
+ "video_token_index",
+ "video_token_id",
+ "vision_start_token_id",
+ ]:
+ token_index = getattr(config, key, None)
+ if token_index is None and hasattr(self, "model_tester"):
+ token_index = getattr(self.model_tester, key, None)
+ if token_index is not None and token_index < config.get_text_config().vocab_size:
+ logits_processor_kwargs["bad_words_ids"].append([token_index])
+
+ return logits_processor_kwargs
+
+ def _get_beam_kwargs(self, num_return_sequences=1):
+ beam_kwargs = {
+ "early_stopping": False,
+ "length_penalty": 2.0,
+ "num_beams": 2,
+ "num_return_sequences": num_return_sequences,
+ }
+ return beam_kwargs
+
+ def _get_diverse_beam_kwargs(self, num_return_sequences=1):
+ beam_kwargs = {
+ "early_stopping": False,
+ "length_penalty": 2.0,
+ "num_beams": 2,
+ "num_return_sequences": num_return_sequences,
+ "num_beam_groups": 2, # one beam per group
+ "diversity_penalty": 2.0,
+ }
+ return beam_kwargs
+
+ def _get_constrained_beam_kwargs(self, num_return_sequences=1):
+ beam_kwargs = {
+ "early_stopping": False,
+ "length_penalty": 2.0,
+ "num_beams": num_return_sequences * 4,
+ "num_return_sequences": num_return_sequences,
+ }
+ return beam_kwargs
+
+ def _greedy_generate(
+ self,
+ model,
+ inputs_dict,
+ output_scores=False,
+ output_logits=False,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict_in_generate=False,
+ use_cache=True,
+ ):
+ logits_processor_kwargs = self._get_logits_processor_kwargs(do_sample=False, config=model.config)
+ output_generate = model.generate(
+ do_sample=False,
+ num_beams=1,
+ max_new_tokens=self.max_new_tokens,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ output_scores=output_scores,
+ output_logits=output_logits,
+ return_dict_in_generate=return_dict_in_generate,
+ use_cache=use_cache,
+ **logits_processor_kwargs,
+ **inputs_dict,
+ )
+
+ return output_generate
+
+ def _sample_generate(
+ self,
+ model,
+ inputs_dict,
+ num_return_sequences,
+ output_scores=False,
+ output_logits=False,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict_in_generate=False,
+ use_cache=True,
+ ):
+ torch.manual_seed(0)
+ logits_processor_kwargs = self._get_logits_processor_kwargs(do_sample=True, config=model.config)
+ output_generate = model.generate(
+ do_sample=True,
+ num_beams=1,
+ max_new_tokens=self.max_new_tokens,
+ num_return_sequences=num_return_sequences,
+ output_scores=output_scores,
+ output_logits=output_logits,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict_in_generate=return_dict_in_generate,
+ use_cache=use_cache,
+ **logits_processor_kwargs,
+ **inputs_dict,
+ )
+
+ return output_generate
+
+ def _beam_search_generate(
+ self,
+ model,
+ inputs_dict,
+ beam_kwargs,
+ output_scores=False,
+ output_logits=False,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict_in_generate=False,
+ use_cache=True,
+ ):
+ logits_processor_kwargs = self._get_logits_processor_kwargs(do_sample=False, config=model.config)
+ output_generate = model.generate(
+ do_sample=False,
+ max_new_tokens=self.max_new_tokens,
+ output_scores=output_scores,
+ output_logits=output_logits,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict_in_generate=return_dict_in_generate,
+ use_cache=use_cache,
+ **beam_kwargs,
+ **logits_processor_kwargs,
+ **inputs_dict,
+ )
+
+ return output_generate
+
+ def _beam_sample_generate(
+ self,
+ model,
+ inputs_dict,
+ beam_kwargs,
+ output_scores=False,
+ output_logits=False,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict_in_generate=False,
+ use_cache=True,
+ ):
+ torch.manual_seed(0)
+ logits_processor_kwargs = self._get_logits_processor_kwargs(do_sample=True, config=model.config)
+ output_generate = model.generate(
+ do_sample=True,
+ max_new_tokens=self.max_new_tokens,
+ output_scores=output_scores,
+ output_logits=output_logits,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict_in_generate=return_dict_in_generate,
+ use_cache=use_cache,
+ **beam_kwargs,
+ **logits_processor_kwargs,
+ **inputs_dict,
+ )
+
+ return output_generate
+
+ def _group_beam_search_generate(
+ self,
+ model,
+ inputs_dict,
+ beam_kwargs,
+ output_scores=False,
+ output_logits=False,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict_in_generate=False,
+ use_cache=True,
+ ):
+ logits_processor_kwargs = self._get_logits_processor_kwargs(do_sample=False, config=model.config)
+ output_generate = model.generate(
+ do_sample=False,
+ max_new_tokens=self.max_new_tokens,
+ output_scores=output_scores,
+ output_logits=output_logits,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict_in_generate=return_dict_in_generate,
+ use_cache=use_cache,
+ **beam_kwargs,
+ **logits_processor_kwargs,
+ **inputs_dict,
+ )
+
+ return output_generate
+
+ def _constrained_beam_search_generate(
+ self,
+ model,
+ inputs_dict,
+ constraints,
+ beam_kwargs,
+ output_scores=False,
+ output_logits=False,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict_in_generate=False,
+ use_cache=True,
+ ):
+ logits_processor_kwargs = self._get_logits_processor_kwargs(do_sample=False, config=model.config)
+ output_generate = model.generate(
+ do_sample=False,
+ max_new_tokens=self.max_new_tokens,
+ output_scores=output_scores,
+ output_logits=output_logits,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict_in_generate=return_dict_in_generate,
+ constraints=constraints,
+ use_cache=use_cache,
+ **beam_kwargs,
+ **logits_processor_kwargs,
+ **inputs_dict,
+ )
+
+ return output_generate
+
+ def _contrastive_generate(
+ self,
+ model,
+ inputs_dict,
+ output_scores=False,
+ output_logits=False,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict_in_generate=False,
+ use_cache=True,
+ ):
+ contrastive_search_kwargs = {
+ "penalty_alpha": 0.6,
+ "top_k": 5,
+ }
+
+ logits_processor_kwargs = self._get_logits_processor_kwargs(do_sample=False, config=model.config)
+ output_generate = model.generate(
+ do_sample=False,
+ num_beams=1,
+ max_new_tokens=self.max_new_tokens,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ output_scores=output_scores,
+ output_logits=output_logits,
+ return_dict_in_generate=return_dict_in_generate,
+ use_cache=use_cache,
+ **logits_processor_kwargs,
+ **contrastive_search_kwargs,
+ **inputs_dict,
+ )
+
+ return output_generate
+
+ @pytest.mark.generate
+ def test_greedy_generate(self):
+ for model_class in self.all_generative_model_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+
+ model = model_class(config).to(torch_device).eval()
+ output_generate = self._greedy_generate(model=model, inputs_dict=inputs_dict)
+
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + 1)
+ else:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1])
+
+ @pytest.mark.generate
+ def test_greedy_generate_dict_outputs(self):
+ for model_class in self.all_generative_model_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+ if self.has_attentions:
+ config._attn_implementation = "eager" # can't output attentions otherwise
+
+ model = model_class(config).to(torch_device).eval()
+ output_generate = self._greedy_generate(
+ model=model,
+ inputs_dict=inputs_dict,
+ output_scores=True,
+ output_logits=True,
+ output_hidden_states=True,
+ output_attentions=self.has_attentions,
+ return_dict_in_generate=True,
+ use_cache=False,
+ )
+
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.sequences.shape[-1] == self.max_new_tokens + 1)
+ self.assertIsInstance(output_generate, GenerateEncoderDecoderOutput)
+ # Retrocompatibility check
+ self.assertIsInstance(output_generate, GreedySearchEncoderDecoderOutput)
+ else:
+ self.assertTrue(
+ output_generate.sequences.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1]
+ )
+ self.assertIsInstance(output_generate, GenerateDecoderOnlyOutput)
+ # Retrocompatibility check
+ self.assertIsInstance(output_generate, GreedySearchDecoderOnlyOutput)
+
+ self._check_generate_outputs(output_generate, model.config)
+
+ @pytest.mark.generate
+ def test_greedy_generate_dict_outputs_use_cache(self):
+ for model_class in self.all_generative_model_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+ if self.has_attentions:
+ config._attn_implementation = "eager" # can't output attentions otherwise
+
+ if not hasattr(config.get_text_config(), "use_cache"):
+ self.skipTest(reason=f"{model_class.__name__} doesn't support caching")
+ if any(model_name in model_class.__name__.lower() for model_name in ["rwkv"]):
+ self.skipTest(reason="Won't fix: model with non-standard dictionary output shapes")
+
+ config.is_decoder = True
+ model = model_class(config).to(torch_device).eval()
+ output_generate = self._greedy_generate(
+ model=model,
+ inputs_dict=inputs_dict,
+ output_scores=True,
+ output_logits=True,
+ output_hidden_states=True,
+ output_attentions=self.has_attentions,
+ return_dict_in_generate=True,
+ use_cache=True, # Enable cache
+ )
+
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.sequences.shape[-1] == self.max_new_tokens + 1)
+ else:
+ self.assertTrue(
+ output_generate.sequences.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1]
+ )
+
+ self._check_generate_outputs(output_generate, model.config, use_cache=True)
+
+ @pytest.mark.generate
+ def test_sample_generate(self):
+ for model_class in self.all_generative_model_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+
+ model = model_class(config).to(torch_device).eval()
+ output_generate = self._sample_generate(model=model, inputs_dict=inputs_dict, num_return_sequences=1)
+
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + 1)
+ else:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1])
+
+ @pytest.mark.generate
+ def test_sample_generate_dict_output(self):
+ for model_class in self.all_generative_model_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+ if self.has_attentions:
+ config._attn_implementation = "eager" # can't output attentions otherwise
+
+ model = model_class(config).to(torch_device).eval()
+ output_generate = self._sample_generate(
+ model=model,
+ inputs_dict=inputs_dict,
+ num_return_sequences=2,
+ output_scores=True,
+ output_logits=True,
+ output_hidden_states=True,
+ output_attentions=self.has_attentions,
+ return_dict_in_generate=True,
+ use_cache=False,
+ )
+
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.sequences.shape[-1] == self.max_new_tokens + 1)
+ self.assertIsInstance(output_generate, GenerateEncoderDecoderOutput)
+ # Retrocompatibility check
+ self.assertIsInstance(output_generate, SampleEncoderDecoderOutput)
+ else:
+ self.assertTrue(
+ output_generate.sequences.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1]
+ )
+ self.assertIsInstance(output_generate, GenerateDecoderOnlyOutput)
+ # Retrocompatibility check
+ self.assertIsInstance(output_generate, SampleDecoderOnlyOutput)
+
+ self._check_generate_outputs(output_generate, model.config, num_return_sequences=2)
+
+ @pytest.mark.generate
+ def test_beam_search_generate(self):
+ for model_class in self.all_generative_model_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+
+ model = model_class(config).to(torch_device).eval()
+
+ beam_kwargs = self._get_beam_kwargs()
+ output_generate = self._beam_search_generate(model=model, inputs_dict=inputs_dict, beam_kwargs=beam_kwargs)
+
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + 1)
+ else:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1])
+
+ @pytest.mark.generate
+ def test_beam_search_generate_dict_output(self):
+ for model_class in self.all_generative_model_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+ if self.has_attentions:
+ config._attn_implementation = "eager" # can't output attentions otherwise
+
+ model = model_class(config).to(torch_device).eval()
+ beam_kwargs = self._get_beam_kwargs()
+ output_generate = self._beam_search_generate(
+ model=model,
+ inputs_dict=inputs_dict,
+ beam_kwargs=beam_kwargs,
+ output_scores=True,
+ output_logits=True,
+ output_hidden_states=True,
+ output_attentions=self.has_attentions,
+ return_dict_in_generate=True,
+ use_cache=False,
+ )
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.sequences.shape[-1] == self.max_new_tokens + 1)
+ self.assertIsInstance(output_generate, GenerateBeamEncoderDecoderOutput)
+ # Retrocompatibility check
+ self.assertIsInstance(output_generate, BeamSearchEncoderDecoderOutput)
+ else:
+ self.assertTrue(
+ output_generate.sequences.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1]
+ )
+ self.assertIsInstance(output_generate, GenerateBeamDecoderOnlyOutput)
+ # Retrocompatibility check
+ self.assertIsInstance(output_generate, BeamSearchDecoderOnlyOutput)
+
+ self._check_generate_outputs(
+ output_generate,
+ model.config,
+ num_return_sequences=beam_kwargs["num_return_sequences"],
+ num_beams=beam_kwargs["num_beams"],
+ )
+
+ @pytest.mark.generate
+ def test_beam_search_generate_dict_outputs_use_cache(self):
+ for model_class in self.all_generative_model_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+
+ if not hasattr(config.get_text_config(), "use_cache"):
+ self.skipTest(reason=f"{model_class.__name__} doesn't support caching")
+ if any(model_name in model_class.__name__.lower() for model_name in ["rwkv"]):
+ self.skipTest(reason="Won't fix: model with non-standard dictionary output shapes")
+
+ if self.has_attentions:
+ config._attn_implementation = "eager" # can't output attentions otherwise
+ model = model_class(config).to(torch_device).eval()
+ beam_kwargs = self._get_beam_kwargs()
+
+ config.is_decoder = True
+ model = model_class(config).to(torch_device).eval()
+ output_generate = self._beam_search_generate(
+ model=model,
+ inputs_dict=inputs_dict,
+ beam_kwargs=beam_kwargs,
+ output_scores=True,
+ output_logits=True,
+ output_hidden_states=True,
+ output_attentions=self.has_attentions,
+ return_dict_in_generate=True,
+ use_cache=True, # Enable cache
+ )
+
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.sequences.shape[-1] == self.max_new_tokens + 1)
+ else:
+ self.assertTrue(
+ output_generate.sequences.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1]
+ )
+
+ self._check_generate_outputs(
+ output_generate,
+ model.config,
+ use_cache=True,
+ num_return_sequences=beam_kwargs["num_return_sequences"],
+ num_beams=beam_kwargs["num_beams"],
+ )
+
+ @require_accelerate
+ @require_torch_multi_accelerator
+ @pytest.mark.generate
+ def test_model_parallel_beam_search(self):
+ if "xpu" in torch_device:
+ if not (is_ipex_available("2.5") or version.parse(torch.__version__) >= version.parse("2.6")):
+ self.skipTest(reason="device_map='auto' does not work with XPU devices")
+
+ for model_class in self.all_generative_model_classes:
+ if model_class._no_split_modules is None:
+ continue
+
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+
+ model = model_class(config).eval()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ model.cpu().save_pretrained(tmp_dir)
+ new_model = model_class.from_pretrained(tmp_dir, device_map="auto")
+
+ new_model.generate(
+ max_new_tokens=self.max_new_tokens,
+ num_beams=2,
+ **inputs_dict,
+ )
+
+ @pytest.mark.generate
+ def test_beam_sample_generate(self):
+ for model_class in self.all_generative_model_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+
+ model = model_class(config).to(torch_device).eval()
+ beam_kwargs = self._get_beam_kwargs()
+ output_generate = self._beam_sample_generate(
+ model=model,
+ inputs_dict=inputs_dict,
+ beam_kwargs=beam_kwargs,
+ )
+
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + 1)
+ else:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1])
+
+ @pytest.mark.generate
+ def test_beam_sample_generate_dict_output(self):
+ for model_class in self.all_generative_model_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+ if self.has_attentions:
+ config._attn_implementation = "eager" # can't output attentions otherwise
+
+ model = model_class(config).to(torch_device).eval()
+ beam_kwargs = self._get_beam_kwargs()
+
+ output_generate = self._beam_sample_generate(
+ model=model,
+ inputs_dict=inputs_dict,
+ beam_kwargs=beam_kwargs,
+ output_scores=True,
+ output_logits=True,
+ output_hidden_states=True,
+ output_attentions=self.has_attentions,
+ return_dict_in_generate=True,
+ use_cache=False,
+ )
+
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.sequences.shape[-1] == self.max_new_tokens + 1)
+ self.assertIsInstance(output_generate, GenerateBeamEncoderDecoderOutput)
+ # Retrocompatibility check
+ self.assertIsInstance(output_generate, BeamSampleEncoderDecoderOutput)
+ else:
+ self.assertTrue(
+ output_generate.sequences.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1]
+ )
+ self.assertIsInstance(output_generate, GenerateBeamDecoderOnlyOutput)
+ # Retrocompatibility check
+ self.assertIsInstance(output_generate, BeamSampleDecoderOnlyOutput)
+
+ self._check_generate_outputs(
+ output_generate,
+ model.config,
+ num_return_sequences=beam_kwargs["num_return_sequences"],
+ num_beams=beam_kwargs["num_beams"],
+ )
+
+ @pytest.mark.generate
+ def test_generate_without_input_ids(self):
+ config, _ = self.prepare_config_and_inputs_for_generate()
+
+ # if no bos token id => cannot generate from None
+ if config.bos_token_id is None:
+ self.skipTest(reason="bos_token_id is None")
+
+ # hack in case they are equal, otherwise the attn mask will be [0]
+ if config.bos_token_id == config.pad_token_id:
+ config.pad_token_id = None
+
+ for model_class in self.all_generative_model_classes:
+ model = model_class(config).to(torch_device)
+ model.eval()
+
+ output_ids_generate = model.generate(
+ do_sample=False, max_new_tokens=self.max_new_tokens, remove_invalid_values=True
+ )
+ self.assertIsNotNone(output_ids_generate)
+
+ @pytest.mark.generate
+ def test_group_beam_search_generate(self):
+ for model_class in self.all_generative_model_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+
+ model = model_class(config).to(torch_device).eval()
+ # check `generate()` and `group_beam_search()` are equal
+ beam_kwargs = self._get_diverse_beam_kwargs()
+ output_generate = self._group_beam_search_generate(
+ model=model,
+ inputs_dict=inputs_dict,
+ beam_kwargs=beam_kwargs,
+ )
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + 1)
+ else:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1])
+
+ # check `group_beam_search` for higher than 1 `num_return_sequences`
+ num_return_sequences = 2
+ beam_kwargs = self._get_diverse_beam_kwargs(num_return_sequences=num_return_sequences)
+ output_generate = self._group_beam_search_generate(
+ model=model,
+ inputs_dict=inputs_dict,
+ beam_kwargs=beam_kwargs,
+ )
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + 1)
+ else:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1])
+
+ @pytest.mark.generate
+ def test_group_beam_search_generate_dict_output(self):
+ for model_class in self.all_generative_model_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+ if self.has_attentions:
+ config._attn_implementation = "eager" # can't output attentions otherwise
+
+ model = model_class(config).to(torch_device).eval()
+ beam_kwargs = self._get_diverse_beam_kwargs()
+ output_generate = self._group_beam_search_generate(
+ model=model,
+ inputs_dict=inputs_dict,
+ beam_kwargs=beam_kwargs,
+ output_scores=True,
+ output_logits=True,
+ output_hidden_states=True,
+ output_attentions=self.has_attentions,
+ return_dict_in_generate=True,
+ use_cache=False,
+ )
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.sequences.shape[-1] == self.max_new_tokens + 1)
+ self.assertIsInstance(output_generate, GenerateBeamEncoderDecoderOutput)
+ # Retrocompatibility check
+ self.assertIsInstance(output_generate, BeamSearchEncoderDecoderOutput)
+ else:
+ self.assertTrue(
+ output_generate.sequences.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1]
+ )
+ self.assertIsInstance(output_generate, GenerateBeamDecoderOnlyOutput)
+ # Retrocompatibility check
+ self.assertIsInstance(output_generate, BeamSearchDecoderOnlyOutput)
+
+ self._check_generate_outputs(
+ output_generate,
+ model.config,
+ num_return_sequences=beam_kwargs["num_return_sequences"],
+ num_beams=beam_kwargs["num_beams"],
+ )
+
+ # TODO: @gante check why it is flaky
+ @is_flaky()
+ @pytest.mark.generate
+ def test_constrained_beam_search_generate(self):
+ for model_class in self.all_generative_model_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+
+ model = model_class(config).to(torch_device).eval()
+
+ # Sample constraints
+ min_id = 3
+ max_id = config.get_text_config(decoder=True).vocab_size
+
+ force_tokens = torch.randint(min_id, max_id, (1, 2)).tolist()[0]
+ constraints = [
+ PhrasalConstraint(force_tokens),
+ ]
+
+ beam_kwargs = self._get_constrained_beam_kwargs()
+ output_generate = self._constrained_beam_search_generate(
+ model=model,
+ inputs_dict=inputs_dict,
+ constraints=constraints,
+ beam_kwargs=beam_kwargs,
+ )
+
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + 1)
+ else:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1])
+
+ for generation_output in output_generate:
+ self._check_sequence_inside_sequence(force_tokens, generation_output)
+
+ # check`constrained_beam_search` for higher than 1 `num_return_sequences`
+ # Sample constraints
+ force_tokens = torch.randint(min_id, max_id, (1, 2)).tolist()[0]
+ constraints = [
+ PhrasalConstraint(force_tokens),
+ ]
+
+ beam_kwargs = self._get_constrained_beam_kwargs(num_return_sequences=2)
+
+ output_generate = self._constrained_beam_search_generate(
+ model=model,
+ inputs_dict=inputs_dict,
+ constraints=constraints,
+ beam_kwargs=beam_kwargs,
+ )
+
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + 1)
+ else:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1])
+
+ for generation_output in output_generate:
+ self._check_sequence_inside_sequence(force_tokens, generation_output)
+
+ @pytest.mark.generate
+ def test_constrained_beam_search_generate_dict_output(self):
+ for model_class in self.all_generative_model_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+ if self.has_attentions:
+ config._attn_implementation = "eager" # can't output attentions otherwise
+
+ model = model_class(config).to(torch_device).eval()
+
+ # Sample constraints
+ min_id = 3
+ max_id = model.config.get_text_config(decoder=True).vocab_size
+ force_tokens = torch.randint(min_id, max_id, (1, 2)).tolist()[0]
+ constraints = [
+ PhrasalConstraint(force_tokens),
+ ]
+
+ beam_kwargs = self._get_constrained_beam_kwargs()
+ output_generate = self._constrained_beam_search_generate(
+ model=model,
+ inputs_dict=inputs_dict,
+ constraints=constraints,
+ beam_kwargs=beam_kwargs,
+ output_scores=True,
+ output_logits=True,
+ output_hidden_states=True,
+ output_attentions=self.has_attentions,
+ return_dict_in_generate=True,
+ use_cache=False,
+ )
+
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.sequences.shape[-1] == self.max_new_tokens + 1)
+ self.assertIsInstance(output_generate, GenerateBeamEncoderDecoderOutput)
+ # Retrocompatibility check
+ self.assertIsInstance(output_generate, BeamSearchEncoderDecoderOutput)
+ else:
+ self.assertTrue(
+ output_generate.sequences.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1]
+ )
+ self.assertIsInstance(output_generate, GenerateBeamDecoderOnlyOutput)
+ # Retrocompatibility check
+ self.assertIsInstance(output_generate, BeamSearchDecoderOnlyOutput)
+
+ self._check_generate_outputs(
+ output_generate,
+ model.config,
+ num_return_sequences=beam_kwargs["num_return_sequences"],
+ num_beams=beam_kwargs["num_beams"],
+ )
+
+ @pytest.mark.generate
+ def test_contrastive_generate(self):
+ for model_class in self.all_generative_model_classes:
+ if model_class._is_stateful:
+ self.skipTest(reason="Stateful models don't support contrastive search generation")
+
+ # won't fix: FSMT and Reformer have a different cache variable type (and format).
+ if any(model_name in model_class.__name__.lower() for model_name in ["fsmt", "reformer"]):
+ self.skipTest(reason="Won't fix: old model with different cache format")
+
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+
+ # NOTE: contrastive search only works with cache on at the moment.
+ if not hasattr(config.get_text_config(), "use_cache"):
+ self.skipTest(reason=f"{model_class.__name__} doesn't support caching")
+ config.is_decoder = True
+
+ # test old generation output for backwards compatibility
+ model = model_class(config).to(torch_device).eval()
+ output_generate = self._contrastive_generate(
+ model=model,
+ inputs_dict=inputs_dict,
+ use_cache=True, # Enable cache
+ )
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + 1)
+ else:
+ self.assertTrue(output_generate.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1])
+
+ @pytest.mark.generate
+ def test_contrastive_generate_dict_outputs_use_cache(self):
+ for model_class in self.all_generative_model_classes:
+ if model_class._is_stateful:
+ self.skipTest(reason="Stateful models don't support contrastive search generation")
+
+ # won't fix: FSMT and Reformer have a different cache variable type (and format).
+ if any(model_name in model_class.__name__.lower() for model_name in ["fsmt", "reformer"]):
+ self.skipTest(reason="Won't fix: old model with different cache format")
+
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+
+ # NOTE: contrastive search only works with cache on at the moment.
+ if not hasattr(config.get_text_config(), "use_cache"):
+ self.skipTest(reason=f"{model_class.__name__} doesn't support caching")
+ config.is_decoder = True
+ if self.has_attentions:
+ config._attn_implementation = "eager" # can't output attentions otherwise
+
+ model = model_class(config).to(torch_device).eval()
+ output_generate = self._contrastive_generate(
+ model=model,
+ inputs_dict=inputs_dict,
+ output_scores=True,
+ output_logits=True,
+ output_hidden_states=True,
+ output_attentions=self.has_attentions,
+ return_dict_in_generate=True,
+ use_cache=True, # Enable cache
+ )
+
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.sequences.shape[-1] == self.max_new_tokens + 1)
+ else:
+ self.assertTrue(
+ output_generate.sequences.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1]
+ )
+
+ self._check_generate_outputs(output_generate, model.config, use_cache=True)
+
+ @pytest.mark.generate
+ def test_contrastive_generate_low_memory(self):
+ # Check that choosing 'low_memory' does not change the model output
+ for model_class in self.all_generative_model_classes:
+ if model_class._is_stateful:
+ self.skipTest(reason="Stateful models don't support contrastive search generation")
+
+ if any(model_name in model_class.__name__.lower() for model_name in ["fsmt", "reformer", "speech2text"]):
+ self.skipTest(reason="Won't fix: old model with different cache format")
+ if any(model_name in model_class.__name__.lower() for model_name in ["gptbigcode"]):
+ self.skipTest(reason="TODO: fix me")
+
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate(batch_size=1)
+
+ # NOTE: contrastive search only works with cache on at the moment.
+ if not hasattr(config.get_text_config(), "use_cache"):
+ self.skipTest(reason=f"{model_class.__name__} doesn't support caching")
+
+ config.is_decoder = True
+
+ # test output equality of low versus high memory
+ model = model_class(config).to(torch_device).eval()
+
+ low_output = model.generate(
+ top_k=4,
+ penalty_alpha=0.6,
+ low_memory=True,
+ max_new_tokens=self.max_new_tokens,
+ **inputs_dict,
+ use_cache=True,
+ )
+
+ high_output = model.generate(
+ top_k=4,
+ penalty_alpha=0.6,
+ low_memory=False,
+ max_new_tokens=self.max_new_tokens,
+ **inputs_dict,
+ use_cache=True,
+ )
+ self.assertListEqual(low_output.tolist(), high_output.tolist())
+
+ @pytest.mark.generate
+ def test_beam_search_low_memory(self):
+ # Check that choosing 'low_memory' does not change the model output
+ for model_class in self.all_generative_model_classes:
+ if model_class._is_stateful:
+ self.skipTest(reason="May fix in the future: need custom cache handling")
+ if any(model_name in model_class.__name__.lower() for model_name in ["fsmt", "reformer"]):
+ self.skipTest(reason="Won't fix: old model with different cache format")
+ if any(
+ model_name in model_class.__name__.lower()
+ for model_name in [
+ "ctrl",
+ "gptbigcode",
+ "transo_xl",
+ "xlnet",
+ "cpm",
+ "jamba",
+ ]
+ ):
+ self.skipTest(reason="May fix in the future: need model-specific fixes")
+
+ set_model_tester_for_less_flaky_test(self)
+
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+ set_config_for_less_flaky_test(config)
+ # batch_size=1 is ok, but batch_size>1 will cause non-identical output
+
+ config.use_cache = True
+ config.is_decoder = True
+
+ # test output equality of low versus high memory
+ model = model_class(config).to(torch_device).eval()
+ set_model_for_less_flaky_test(model)
+
+ logits_processor_kwargs = self._get_logits_processor_kwargs(config=model.config)
+
+ low_output = model.generate(
+ **inputs_dict,
+ max_new_tokens=8,
+ num_beams=5,
+ early_stopping=True,
+ low_memory=True,
+ use_cache=True,
+ output_scores=True,
+ output_logits=True,
+ return_dict_in_generate=True,
+ **logits_processor_kwargs,
+ )
+
+ high_output = model.generate(
+ **inputs_dict,
+ max_new_tokens=8,
+ num_beams=5,
+ early_stopping=True,
+ low_memory=False,
+ use_cache=True,
+ output_scores=True,
+ output_logits=True,
+ return_dict_in_generate=True,
+ **logits_processor_kwargs,
+ )
+ # The two outputs must match and their shape must be as expected
+ self._check_similar_generate_outputs(low_output, high_output)
+
+ @pytest.mark.generate
+ @parameterized.expand([("random",), ("same",)])
+ def test_assisted_decoding_matches_greedy_search(self, assistant_type):
+ # This test ensures that the assisted generation does not introduce output changes over greedy search.
+ # See https://github.com/huggingface/transformers/issues/25420#issuecomment-1775317535 for more info.
+ # NOTE: It breaks the pattern in the tests above, for multiple reasons:
+ # - assisted_decoding, contrarily to the other methods, can't be called on its own (e.g. needs to
+ # prepare the assistant encoder outputs in the main generate body);
+ # - assisted_decoding does not support `use_cache = False`
+ # - assisted_decoding does not support `batch_size > 1`
+
+ for model_class in self.all_generative_model_classes:
+ if model_class._is_stateful:
+ self.skipTest(reason="Stateful models don't support assisted generation")
+ if any(model_name in model_class.__name__.lower() for model_name in ["fsmt", "reformer"]):
+ self.skipTest(reason="Won't fix: old model with different cache format")
+ if any(
+ model_name in model_class.__name__.lower()
+ for model_name in [
+ "bigbirdpegasus",
+ "led",
+ "mega",
+ "moshi",
+ "speech2text",
+ "git",
+ "prophetnet",
+ "seamlessm4t",
+ "clvp",
+ "mllama", # special cache sizes
+ "blip2", # overridden `generate()`
+ "instructblip",
+ "instructblipvideo",
+ ]
+ ):
+ self.skipTest(reason="May fix in the future: need model-specific fixes")
+
+ # enable cache
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate(batch_size=1)
+
+ # NOTE: assisted generation only works with cache on at the moment.
+ if not hasattr(config.get_text_config(), "use_cache"):
+ self.skipTest(reason=f"{model_class.__name__} doesn't support caching")
+
+ config.is_decoder = True
+ model = model_class(config).to(torch_device).eval()
+ # Sets assisted generation arguments such that:
+ # a) no EOS is generated, to ensure generation doesn't break early
+ # b) the assistant model always generates two tokens when it is called, to ensure the input preparation of
+ # the assistant model is correct
+ # c) there are at least two forward passes in the main model, to ensure the input preparation of
+ # the main model is correct
+ generation_kwargs = {
+ "eos_token_id": -1, # see a)
+ "max_new_tokens": 4, # see c)
+ "num_beams": 1,
+ "do_sample": False,
+ "output_scores": True,
+ "output_logits": True,
+ "output_hidden_states": True,
+ "output_attentions": self.has_attentions,
+ "return_dict_in_generate": True,
+ "use_cache": True,
+ }
+ logits_processor_kwargs = self._get_logits_processor_kwargs(config=model.config)
+
+ output_greedy = model.generate(**generation_kwargs, **inputs_dict, **logits_processor_kwargs)
+
+ # test with the same assistant model or randomly init one
+ # in the first case all candidate tokens are accepted, in the second none is accepted
+ # case when some are accepted and some not is hard to reproduce, so let's hope this catches most errors :)
+ if assistant_type == "random":
+ assistant_model = model_class(config).to(torch_device).eval()
+ else:
+ assistant_model = model
+ assistant_model.generation_config.num_assistant_tokens = 2 # see b)
+ assistant_model.generation_config.num_assistant_tokens_schedule = "constant" # see b)
+ generation_kwargs.update({"assistant_model": assistant_model})
+ output_assisted = model.generate(**generation_kwargs, **inputs_dict, **logits_processor_kwargs)
+
+ # The two outputs must match and their shape must be as expected
+ self._check_similar_generate_outputs(output_greedy, output_assisted)
+ for output in (output_greedy, output_assisted):
+ self._check_generate_outputs(output, model.config, use_cache=True)
+
+ @pytest.mark.generate
+ def test_prompt_lookup_decoding_matches_greedy_search(self):
+ # This test ensures that the prompt lookup generation does not introduce output changes over greedy search.
+ # This test is mostly a copy of test_assisted_decoding_matches_greedy_search
+
+ for model_class in self.all_generative_model_classes:
+ if model_class._is_stateful:
+ self.skipTest(reason="Stateful models don't support assisted generation")
+ if any(model_name in model_class.__name__.lower() for model_name in ["fsmt", "reformer"]):
+ self.skipTest(reason="Won't fix: old model with different cache format")
+ if any(
+ model_name in model_class.__name__.lower()
+ for model_name in [
+ "bigbirdpegasus",
+ "led",
+ "mega",
+ "moshi",
+ "speech2text",
+ "git",
+ "prophetnet",
+ "seamlessm4t",
+ "clvp",
+ "fuyu",
+ "mllama", # special cache sizes
+ "blip2", # overridden `generate()`
+ "instructblip",
+ "instructblipvideo",
+ *VLM_CLASS_NAMES, # shouldn't suggest image tokens
+ ]
+ ):
+ self.skipTest(reason="May fix in the future: need model-specific fixes")
+
+ # enable cache
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate(batch_size=1)
+
+ # NOTE: assisted generation only works with cache on at the moment.
+ if not hasattr(config.get_text_config(), "use_cache"):
+ self.skipTest(reason=f"{model_class.__name__} doesn't support caching")
+
+ config.is_decoder = True
+ model = model_class(config).to(torch_device).eval()
+ # Sets assisted generation arguments such that:
+ # a) no EOS is generated, to ensure generation doesn't break early
+ # b) the prompt lookup tries to give the model 2 tokens, to ensure the input preparation of
+ # prompt lookup is correct
+ # c) there are at least two forward passes in the main model, to ensure the input preparation of
+ # the main model is correct
+ generation_kwargs = {
+ "eos_token_id": -1, # see a)
+ "max_new_tokens": 4, # see c)
+ "num_beams": 1,
+ "do_sample": False,
+ "output_scores": True,
+ "output_logits": True,
+ "output_hidden_states": True,
+ "output_attentions": self.has_attentions,
+ "return_dict_in_generate": True,
+ "use_cache": True,
+ }
+
+ output_greedy = model.generate(**generation_kwargs, **inputs_dict)
+
+ generation_kwargs.update({"prompt_lookup_num_tokens": 2}) # see b)
+ output_prompt_lookup = model.generate(**generation_kwargs, **inputs_dict)
+
+ # The two outputs must match and their shape must be as expected
+ self._check_similar_generate_outputs(output_greedy, output_prompt_lookup)
+ for output in (output_greedy, output_prompt_lookup):
+ self._check_generate_outputs(output, model.config, use_cache=True)
+
+ @pytest.mark.generate
+ def test_dola_decoding_sample(self):
+ # TODO (joao): investigate skips, try to reduce incompatibilities
+ for model_class in self.all_generative_model_classes:
+ if model_class._is_stateful:
+ self.skipTest(reason="Stateful models don't support DoLa decoding")
+
+ if any(model_name in model_class.__name__.lower() for model_name in ["reformer"]):
+ self.skipTest("Skip Reformer as the lm_head input size is 2 * hidden size, adopted from Rev Nets.")
+
+ if any(model_name in model_class.__name__.lower() for model_name in ["marian", "mbart", "pegasus"]):
+ self.skipTest("DoLa is not supported for models that don't return layerwise hidden states")
+
+ if any(model_name == model_class.__name__ for model_name in ["LlavaNextVideoForConditionalGeneration"]):
+ self.skipTest(f"DoLa is failing for {model_class.__name__}")
+
+ # enable cache if the model is not openai-gpt, xlnet, cpm, or xlm
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+
+ # Encoder-decoder models are not supported
+ if config.is_encoder_decoder:
+ self.skipTest("DoLa is not supported for encoder-decoder models")
+ config.is_decoder = True
+ model = model_class(config).to(torch_device).eval()
+
+ if model.get_output_embeddings() is None:
+ self.skipTest("DoLa is not supported for models that don't have output embeddings")
+
+ logits_processor_kwargs = self._get_logits_processor_kwargs(do_sample=True, config=model.config)
+
+ # Sets dola generation arguments such that:
+ # a) no EOS is generated, to ensure generation doesn't break early
+ # b) there are at least two forward passes in the main model, to ensure the input preparation of
+ # the main model is correct
+ generation_kwargs = {
+ "eos_token_id": -1, # see a)
+ "max_new_tokens": 4, # see b)
+ "num_beams": 1,
+ "do_sample": True,
+ "output_scores": True,
+ "output_logits": True,
+ "output_hidden_states": True,
+ "output_attentions": self.has_attentions,
+ "return_dict_in_generate": True,
+ "use_cache": getattr(config, "use_cache", False), # Some models don't support the cache
+ "dola_layers": "low",
+ }
+ output_dola = model.generate(**generation_kwargs, **logits_processor_kwargs, **inputs_dict)
+ self._check_generate_outputs(output_dola, model.config, use_cache=getattr(config, "use_cache", False))
+
+ @pytest.mark.generate
+ def test_assisted_decoding_sample(self):
+ # In this test we don't check assisted vs non-assisted output -- seeded assisted decoding with sample will not
+ # match sample for the same seed, as the forward pass does not return the exact same logits (due to matmul with
+ # different shapes, see https://github.com/huggingface/transformers/issues/25420#issuecomment-1775317535).
+ for model_class in self.all_generative_model_classes:
+ if model_class._is_stateful:
+ self.skipTest(reason="Stateful models don't support assisted generation")
+ if any(model_name in model_class.__name__.lower() for model_name in ["fsmt", "reformer"]):
+ self.skipTest(reason="Won't fix: old model with different cache format")
+ if any(
+ model_name in model_class.__name__.lower()
+ for model_name in [
+ "bigbirdpegasus",
+ "led",
+ "mega",
+ "moshi",
+ "speech2text",
+ "git",
+ "prophetnet",
+ "seamlessm4t",
+ "clvp",
+ "mllama", # special cache sizes
+ "blip2", # overridden `generate()`
+ "instructblip",
+ "instructblipvideo",
+ ]
+ ):
+ self.skipTest(reason="May fix in the future: need model-specific fixes")
+
+ # enable cache
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate(batch_size=1)
+
+ # NOTE: assisted generation only works with cache on at the moment.
+ if not hasattr(config.get_text_config(), "use_cache"):
+ self.skipTest(reason=f"{model_class.__name__} doesn't support caching")
+
+ config.is_decoder = True
+ model = model_class(config).to(torch_device).eval()
+ # Sets assisted generation arguments such that:
+ # a) no EOS is generated, to ensure generation doesn't break early
+ # b) the assistant model always generates two tokens when it is called, to ensure the input preparation of
+ # the assistant model is correct
+ # c) there are at least two forward passes in the main model, to ensure the input preparation of
+ # the main model is correct
+ assistant_model = model
+ assistant_model.generation_config.num_assistant_tokens = 2 # see b)
+ assistant_model.generation_config.num_assistant_tokens_schedule = "constant" # see b)
+ generation_kwargs = {
+ "eos_token_id": -1, # see a)
+ "max_new_tokens": 4, # see c)
+ "num_beams": 1,
+ "do_sample": True,
+ "assistant_model": assistant_model,
+ "output_scores": True,
+ "output_logits": True,
+ "output_hidden_states": True,
+ "output_attentions": self.has_attentions,
+ "return_dict_in_generate": True,
+ "use_cache": True,
+ }
+ logits_processor_kwargs = self._get_logits_processor_kwargs(config=model.config)
+ output_assisted = model.generate(**generation_kwargs, **inputs_dict, **logits_processor_kwargs)
+
+ self._check_generate_outputs(output_assisted, config, use_cache=True)
+
+ @pytest.mark.generate
+ def test_prompt_lookup_decoding_stops_at_eos(self):
+ # This test ensures that the prompt lookup generation stops at eos token and does not suggest more tokens
+ # (see https://github.com/huggingface/transformers/pull/31301)
+
+ # The main idea is to have an ngram (unigram in our case) that is repeated twice in the input ids.
+ # First time at the very end, so input ends with the unigrams, and second any arbitrary location.
+ # Also, we need an EOS token which will be injected just after the arbitrary located ngram.
+ # We verify that PLD will not copy and propose candidated that contain an EOS token, even if there are overlapping ngrams
+ # in input ids. Otherwise a proposed EOS along with the trailing (ngrams-1) tokens might be accepted by the target model.
+ # That seems as if the model "generated" and EOS but didn't stop from user's perspective
+
+ input_ids = torch.randint(1, 50, (1, 10), device=torch_device) # generate inputs in range from 1-50
+ arbitrary_ngram = 51 # this is the arbitrary ngram, specifically chosen OOV to prevent flaky tests
+ input_ids[:, 3] = arbitrary_ngram # set pre-eos to arbitrary_ngram which is for sure not present in inputs
+ input_ids[:, -1] = arbitrary_ngram # put arbitrary_ngram in the end for the necessary match to happen
+
+ eos_token_id = torch.tensor([0], device=torch_device)
+ input_ids[:, 4] = eos_token_id # inject eos-token-id in input ids so that it is located after arbitrary_ngram
+
+ # init cand geenerator with max_matching_ngram_size=1 to match per-token
+ candidate_generator = PromptLookupCandidateGenerator(
+ eos_token_id=eos_token_id, num_output_tokens=4, max_matching_ngram_size=1
+ )
+ output_prompt_lookup = candidate_generator.get_candidates(input_ids)[0]
+
+ # PLD shouldn't propose any new tokens based on eos-match
+ self.assertTrue(output_prompt_lookup.shape[-1] == 10)
+
+ @pytest.mark.generate
+ def test_generate_with_head_masking(self):
+ """Test designed for encoder-decoder models to ensure the attention head masking is used."""
+ attention_names = ["encoder_attentions", "decoder_attentions", "cross_attentions"]
+ for model_class in self.all_generative_model_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+ text_config = config.get_text_config()
+ if self.has_attentions:
+ config._attn_implementation = "eager" # can't output attentions otherwise
+
+ # We want to test only encoder-decoder models
+ if not text_config.is_encoder_decoder:
+ continue
+ model = model_class(config).to(torch_device)
+
+ head_masking = {
+ "head_mask": torch.zeros(
+ text_config.encoder_layers, text_config.encoder_attention_heads, device=torch_device
+ ),
+ "decoder_head_mask": torch.zeros(
+ text_config.decoder_layers, text_config.decoder_attention_heads, device=torch_device
+ ),
+ "cross_attn_head_mask": torch.zeros(
+ text_config.decoder_layers, text_config.decoder_attention_heads, device=torch_device
+ ),
+ }
+
+ signature = inspect.signature(model.forward)
+ # We want to test only models where encoder/decoder head masking is implemented
+ if not set(head_masking.keys()) < {*signature.parameters.keys()}:
+ continue
+
+ for attn_name, (name, mask) in zip(attention_names, head_masking.items()):
+ out = model.generate(
+ num_beams=1,
+ output_attentions=self.has_attentions,
+ return_dict_in_generate=True,
+ remove_invalid_values=True,
+ **{name: mask},
+ **inputs_dict,
+ )
+ # We check the state of decoder_attentions and cross_attentions just from the last step
+ attn_weights = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1]
+ self.assertEqual(sum([w.sum().item() for w in attn_weights]), 0.0)
+
+ @pytest.mark.generate
+ def test_left_padding_compatibility(self):
+ # NOTE: left-padding results in small numerical differences. This is expected.
+ # See https://github.com/huggingface/transformers/issues/25420#issuecomment-1775317535
+
+ # First, filter out models that don't support left padding
+ # - The model must have generative capabilities
+ if len(self.all_generative_model_classes) == 0:
+ self.skipTest(reason="No generative architecture available for this model.")
+
+ # - The model must support padding
+ if not self.has_attentions:
+ self.skipTest(reason="This model doesn't support padding.")
+
+ # - The model must be a decoder-only architecture (encoder-based architectures use right-padding)
+ decoder_only_classes = []
+ for model_class in self.all_generative_model_classes:
+ config, _ = self.prepare_config_and_inputs_for_generate()
+ if config.is_encoder_decoder:
+ continue
+ else:
+ decoder_only_classes.append(model_class)
+ if len(decoder_only_classes) == 0:
+ self.skipTest(reason="No decoder-only architecture available for this model.")
+
+ # - Decoder-only architectures derived from encoder-decoder models could support it in theory, but we haven't
+ # added support for it yet. We skip these models for now.
+ has_encoder_attributes = any(
+ attr_name
+ for attr_name in config.to_dict().keys()
+ if attr_name.startswith("encoder") and attr_name != "encoder_no_repeat_ngram_size"
+ )
+ if has_encoder_attributes:
+ self.skipTest(
+ reason="The decoder-only derived from encoder-decoder models are not expected to support left-padding."
+ )
+
+ # Then, test left-padding
+ def _prepare_model_kwargs(input_ids, attention_mask, signature):
+ model_kwargs = {"input_ids": input_ids, "attention_mask": attention_mask}
+ if "position_ids" in signature:
+ position_ids = torch.cumsum(attention_mask, dim=-1) - 1
+ position_ids.masked_fill_(attention_mask == 0, 1)
+ model_kwargs["position_ids"] = position_ids
+ if "cache_position" in signature:
+ cache_position = torch.arange(input_ids.shape[-1], device=torch_device)
+ model_kwargs["cache_position"] = cache_position
+ return model_kwargs
+
+ for model_class in decoder_only_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+ input_ids = inputs_dict["input_ids"]
+ attention_mask = inputs_dict.get("attention_mask")
+ if attention_mask is None:
+ attention_mask = torch.ones_like(input_ids)
+
+ model = model_class(config).to(torch_device).eval()
+ signature = inspect.signature(model.forward).parameters.keys()
+
+ # no cache as some models require special cache classes to be init outside forward
+ model.generation_config.use_cache = False
+
+ # Without padding
+ model_kwargs = _prepare_model_kwargs(input_ids, attention_mask, signature)
+ next_logits_wo_padding = model(**model_kwargs).logits[:, -1, :]
+
+ # With left-padding (length 32)
+ # can hardcode pad_token to be 0 as we'll do attn masking anyway
+ pad_token_id = (
+ config.get_text_config().pad_token_id if config.get_text_config().pad_token_id is not None else 0
+ )
+ pad_size = (input_ids.shape[0], 32)
+ padding = torch.ones(pad_size, dtype=input_ids.dtype, device=torch_device) * pad_token_id
+ padded_input_ids = torch.cat((padding, input_ids), dim=1)
+ padded_attention_mask = torch.cat((torch.zeros_like(padding), attention_mask), dim=1)
+ model_kwargs = _prepare_model_kwargs(padded_input_ids, padded_attention_mask, signature)
+ next_logits_with_padding = model(**model_kwargs).logits[:, -1, :]
+
+ # They should result in very similar logits
+ torch.testing.assert_close(next_logits_wo_padding, next_logits_with_padding, rtol=1e-5, atol=1e-5)
+
+ @pytest.mark.generate
+ def test_past_key_values_format(self):
+ # Test that the KV cache is formatted correctly. Exceptions need to explicitly overwrite this test. Having a
+ # standard KV cache format is important for a consistent API (and for advanced generation methods).
+ for model_class in self.all_generative_model_classes:
+ config, inputs = self.model_tester.prepare_config_and_inputs_for_common()
+
+ # If it doesn't support cache, pass the test
+ if not hasattr(config.get_text_config(), "use_cache"):
+ self.skipTest(reason=f"{model_class.__name__} doesn't support caching")
+
+ model = model_class(config).to(torch_device)
+ if "use_cache" not in inputs:
+ inputs["use_cache"] = True
+ outputs = model(**inputs)
+
+ # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format)
+ if "past_key_values" not in outputs:
+ self.skipTest(reason="This model doesn't return `past_key_values`")
+
+ text_config = config.get_text_config()
+ num_hidden_layers = (
+ getattr(text_config, "decoder_layers", None)
+ or getattr(text_config, "num_decoder_layers", None)
+ or text_config.num_hidden_layers
+ )
+ num_attention_heads = getattr(text_config, "decoder_attention_heads", text_config.num_attention_heads)
+ embed_dim = getattr(text_config, "d_model", text_config.hidden_size)
+ per_head_embed_dim = embed_dim // num_attention_heads
+
+ # some models have diffent num-head for query vs key/value so we need to assign correct value
+ # BUT only after `per_head_embed_dim` is set
+ num_attention_heads = (
+ text_config.num_key_value_heads
+ if getattr(text_config, "num_key_value_heads", None) is not None
+ else num_attention_heads
+ )
+
+ past_kv = outputs["past_key_values"]
+ self.assertEqual(len(past_kv), num_hidden_layers)
+
+ # Encoder-Decoder checks
+ if config.is_encoder_decoder:
+ # encoder-decoder models usually don't have text config
+ # below is needed only for Pix2Struct which we cannot modify now due to BC
+ config = config.get_text_config()
+ encoder_num_attention_heads = (
+ config.encoder_attention_heads
+ if hasattr(config, "encoder_attention_heads")
+ else config.num_attention_heads
+ )
+ encoder_per_head_embed_dim = embed_dim // encoder_num_attention_heads
+ batch_size, seq_length = inputs["decoder_input_ids"].shape
+ for i in range(num_hidden_layers):
+ self.assertEqual(len(past_kv[i]), 4) # K V for the decoder + K V for the encoder = 4
+ self.assertEqual(
+ past_kv[i][0].shape, (batch_size, num_attention_heads, seq_length, per_head_embed_dim)
+ )
+ self.assertEqual(
+ past_kv[i][1].shape, (batch_size, num_attention_heads, seq_length, per_head_embed_dim)
+ )
+ # The sequence length for the encoder K V depends on the model. Since it is not manipulated in
+ # autoregressive generation, I'm keeping the test general and not checking the 3rd dim
+ self.assertEqual(
+ (past_kv[i][2].shape[0], past_kv[i][2].shape[1], past_kv[i][2].shape[3]),
+ (batch_size, encoder_num_attention_heads, encoder_per_head_embed_dim),
+ )
+ self.assertEqual(
+ (past_kv[i][3].shape[0], past_kv[i][3].shape[1], past_kv[i][3].shape[3]),
+ (batch_size, encoder_num_attention_heads, encoder_per_head_embed_dim),
+ )
+
+ # Decoder-only checks
+ else:
+ # TODO: this line is only needed because of imagegpt, where "pixel_values" = "input_ids". Fix the
+ # tests in imagegpt such that `prepare_config_and_inputs_for_common` returns the later (and the other
+ # tests use it)
+ key = "input_ids" if "input_ids" in inputs else "pixel_values"
+ batch_size, seq_length = inputs[key].shape
+ for i in range(num_hidden_layers):
+ self.assertEqual(len(past_kv[0]), 2) # K V for the decoder = 2
+ self.assertEqual(
+ past_kv[i][0].shape, (batch_size, num_attention_heads, seq_length, per_head_embed_dim)
+ )
+ self.assertEqual(
+ past_kv[i][1].shape, (batch_size, num_attention_heads, seq_length, per_head_embed_dim)
+ )
+
+ @pytest.mark.generate
+ @parameterized.expand([("greedy", 1), ("beam search", 2)])
+ def test_generate_from_inputs_embeds(self, _, num_beams):
+ """Tests that we can generate from `inputs_embeds` instead of `input_ids` in LLMs, VLMs, etc"""
+ # When supported, tests that the decoder model can generate from `inputs_embeds` instead of `input_ids`
+ # if fails, you should probably update the `prepare_inputs_for_generation` function
+ for model_class in self.all_generative_model_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+
+ # This test is for decoder-only models (encoder-decoder models have native input embeddings support in the
+ # decoder)
+ if config.is_encoder_decoder:
+ continue
+ config.is_decoder = True
+
+ # Skip models without explicit support
+ model = model_class(config).to(torch_device).eval()
+ if "inputs_embeds" not in inspect.signature(model.prepare_inputs_for_generation).parameters.keys():
+ continue
+
+ # There are a few exception patterns in this test:
+ # 1 - Some models can't generate without `input_ids`, when `inputs_embeds` are passed
+ requires_inputs_ids = any(model_name in model_class.__name__.lower() for model_name in ["idefics"])
+ # 2 - Complex `inputs_embeds` computation, i.e. the correct computation of inputs embeds is more complex
+ # than calling the embedding layer with `input_ids`. Subcases of this exception:
+ # 2.A - Ignore `scale_embedding`, if the model supports it (it is controlled by a model-dependent flag)
+ if hasattr(config, "scale_embedding"):
+ config.scale_embedding = False
+ # 2.B - Some VLMs assume `inputs_embeds` and `pixel_values` are mutually exclusive AND fall in the
+ # exception above (complex `inputs_embeds` computation). Popping `pixel_values` allow us to run the
+ # checks without adding test complexity. Ditto for `pixel_values_videos` and `pixel_values_images`
+ pixel_values_is_mutually_exclusive = any(
+ model_name in model_class.__name__.lower() for model_name in VLM_CLASS_NAMES
+ )
+ if pixel_values_is_mutually_exclusive:
+ inputs_dict.pop("pixel_values", None)
+ inputs_dict.pop("pixel_values_videos", None)
+ inputs_dict.pop("pixel_values_images", None)
+ # 2.C - No easy fix, let's skip the check that compares the outputs from `input_ids` and `inputs_embeds`
+ has_complex_embeds_computation = any(
+ model_name in model_class.__name__.lower() for model_name in ["moshi"]
+ )
+ # 3 - `inputs_dict` doesn't contain `attention_mask`. When `attention_mask` is not passed to generate,
+ # we infer it from `input_ids`. The last test case will fail if there is a pad token in the original input.
+ missing_attention_mask = "attention_mask" not in inputs_dict
+
+ # Traditional way of generating text
+ input_ids = inputs_dict.pop("input_ids")
+ generation_kwargs = {
+ "return_dict_in_generate": True,
+ "output_scores": True,
+ "num_beams": num_beams,
+ "do_sample": False,
+ "max_new_tokens": 5,
+ "min_new_tokens": 5, # generate exactly 5 tokens
+ }
+ outputs_from_ids = model.generate(input_ids, **generation_kwargs, **inputs_dict)
+ self.assertEqual(outputs_from_ids.sequences.shape, (input_ids.shape[0], input_ids.shape[1] + 5))
+
+ # Same thing, but from input embeddings (`input_ids` is passed so the prompt is present in the output).
+ # The output of the two calls should be the same.
+ inputs_embeds = model.get_input_embeddings()(input_ids)
+ outputs_from_embeds = model.generate(
+ input_ids, inputs_embeds=inputs_embeds, **generation_kwargs, **inputs_dict
+ )
+ if not has_complex_embeds_computation:
+ self._check_similar_generate_outputs(outputs_from_ids, outputs_from_embeds)
+
+ # If we pass different inputs_embeds, we should get different outputs (the output text may be the
+ # same, but the logits will almost surely be different)
+ random_embeds = torch.rand_like(inputs_embeds)
+ outputs_from_rand_embeds = model.generate(
+ input_ids, inputs_embeds=random_embeds, **generation_kwargs, **inputs_dict
+ )
+ for i in range(len(outputs_from_rand_embeds.scores)):
+ self.assertFalse(torch.allclose(outputs_from_embeds.scores[i], outputs_from_rand_embeds.scores[i]))
+
+ # input_ids is not a required input on most models -- if we don't pass it, the newly generated tokens will
+ # be the same
+ if not (requires_inputs_ids or missing_attention_mask):
+ outputs_from_embeds_wo_ids = model.generate(
+ inputs_embeds=inputs_embeds, **generation_kwargs, **inputs_dict
+ )
+ outputs_from_embeds.sequences = outputs_from_embeds.sequences[:, inputs_embeds.shape[1] :]
+ self._check_similar_generate_outputs(outputs_from_embeds_wo_ids, outputs_from_embeds)
+
+ @pytest.mark.generate
+ def test_generate_from_inputs_embeds_with_static_cache(self):
+ """
+ Test that StaticCache can generate from inputs_embeds and calculates max_cache_length
+ correctly in `generate()`. We force the model to not stop generation until max-length is reached
+ to verify that the cache length is indeed set correctly and we don't run out of index when slicing the cache.
+ """
+ for model_class in self.all_generative_model_classes:
+ if not model_class._supports_static_cache:
+ self.skipTest(reason="This model does not support the static cache format")
+
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+
+ if config.is_encoder_decoder:
+ self.skipTest(reason="This model is encoder-decoder and has Encoder-Decoder Cache")
+
+ model = model_class(config).to(torch_device).eval()
+ if "inputs_embeds" not in inspect.signature(model.prepare_inputs_for_generation).parameters.keys():
+ self.skipTest(reason="This model does not support `inputs_embeds` in generation")
+
+ # Some VLMs assume `inputs_embeds` and `pixel_values` are mutually exclusive AND fall in the
+ # exception above (complex `inputs_embeds` computation). Popping `pixel_values` allow us to run the
+ # checks without adding test complexity. Ditto for `pixel_values_videos` and `pixel_values_images`
+ pixel_values_is_mutually_exclusive = any(
+ model_name in model_class.__name__.lower() for model_name in VLM_CLASS_NAMES
+ )
+ if pixel_values_is_mutually_exclusive:
+ inputs_dict.pop("pixel_values", None)
+ inputs_dict.pop("pixel_values_videos", None)
+ inputs_dict.pop("pixel_values_images", None)
+
+ input_ids = inputs_dict.pop("input_ids")
+
+ model.config.use_cache = True
+ model.config.is_decoder = True
+ batch_size = input_ids.shape[0]
+ max_new_tokens = 10
+
+ # here we force to not stop at eos and go until max-length
+ model.generation_config.eos_token_id = model.config.get_text_config().eos_token_id = -1
+ generation_kwargs = {
+ "max_new_tokens": max_new_tokens,
+ "cache_implementation": "static",
+ "return_dict_in_generate": True, # Required to return `past_key_values`
+ }
+
+ text_config = model.config.get_text_config()
+ head_dim = (
+ text_config.head_dim
+ if hasattr(text_config, "head_dim")
+ else text_config.hidden_size // text_config.num_attention_heads
+ )
+ num_key_value_heads = (
+ text_config.num_attention_heads
+ if getattr(text_config, "num_key_value_heads", None) is None
+ else text_config.num_key_value_heads
+ )
+ num_hidden_layers = text_config.num_hidden_layers
+
+ inputs_embeds = model.get_input_embeddings()(input_ids)
+ outputs = model.generate(inputs_embeds=inputs_embeds, **generation_kwargs, **inputs_dict)
+
+ # we should get `max_length - 1` in shape, not `max_length - embeds_length`.
+ # -1 because the last generated token isn't yet in the cache.
+ max_length = max_new_tokens + inputs_embeds.shape[1] - 1
+ cache_shape = [batch_size, num_key_value_heads, max_length, head_dim]
+ self.assertIsInstance(outputs.past_key_values, StaticCache)
+ self.assertEqual(len(outputs.past_key_values.key_cache), num_hidden_layers)
+ self.assertListEqual(list(outputs.past_key_values.key_cache[0].shape), cache_shape)
+
+ @pytest.mark.generate
+ def test_generate_continue_from_past_key_values(self):
+ # Tests that we can continue generating from past key values, returned from a previous `generate` call
+ for model_class in self.all_generative_model_classes:
+ if any(model_name in model_class.__name__.lower() for model_name in ["imagegpt", "mllama"]):
+ self.skipTest(reason="Won't fix: old model with unique inputs/caches/other")
+ if any(model_name in model_class.__name__.lower() for model_name in ["umt5"]):
+ self.skipTest(reason="TODO: needs modeling or test input preparation fixes for compatibility")
+
+ config, inputs = self.model_tester.prepare_config_and_inputs_for_common()
+
+ if not hasattr(config.get_text_config(), "use_cache"):
+ self.skipTest(reason=f"{model_class.__name__} doesn't support caching")
+
+ # Let's make it always:
+ # 1. use cache (for obvious reasons)
+ # 2. generate to max length (which can be achieved by setting the eos token to an invalid value), which
+ # would make the test flaky (e.g. EOS is generated on iteration 1 on both generations, but the
+ # continuation would force it to generate beyond an EOS token)
+ # 3. ignore `token_type_ids` for simplicity
+ # 4. ignore `forced_eos_token_id`, which requires further manipulation of the continuation inputs and is
+ # active by default on some models
+ # 5. ignore `encoder_no_repeat_ngram_size`, which is set by default in some encoder-decoder models. When
+ # we use their decoder as a stand-alone model, `encoder_no_repeat_ngram_size` actually prevents
+ # repetition exclusively from the prompt. This test relies on comparing one call vs 2 calls
+ # with cache, what is considered a prompt is different in the two cases.
+
+ if "token_type_ids" in inputs:
+ del inputs["token_type_ids"]
+
+ model = model_class(config).to(torch_device)
+ model.eval()
+ model.generation_config.pad_token_id = model.generation_config.eos_token_id = -1
+ model.generation_config.forced_eos_token_id = None
+ model.generation_config.encoder_no_repeat_ngram_size = 0
+ model.generation_config.use_cache = True
+
+ # If "past_key_values" is not returned, skip the test (e.g. RWKV uses a different cache name and format)
+ outputs = model(**inputs)
+ if "past_key_values" not in outputs:
+ self.skipTest(reason="This model doesn't return `past_key_values`")
+
+ # Traditional way of generating text, with `return_dict_in_generate` to return the past key values
+ outputs = model.generate(**inputs, do_sample=False, max_new_tokens=4, return_dict_in_generate=True)
+
+ # Let's generate again, but passing the past key values in between (3 + 1 = 4 tokens). Note that the
+ # inputs may need to be tweaked across `generate` calls (like the attention mask).
+ outputs_cached = model.generate(**inputs, do_sample=False, max_new_tokens=3, return_dict_in_generate=True)
+
+ # Continue from the tokens generated above, preparing the inputs accordingly
+ inputs["past_key_values"] = outputs_cached.past_key_values
+ new_attention_len = outputs_cached.sequences.shape[-1]
+ if config.is_encoder_decoder:
+ inputs["decoder_input_ids"] = outputs_cached.sequences
+ if "decoder_attention_mask" in inputs:
+ inputs["decoder_attention_mask"] = torch.nn.functional.pad(
+ inputs["decoder_attention_mask"],
+ (0, new_attention_len - inputs["decoder_attention_mask"].shape[1]),
+ mode="constant",
+ value=1,
+ )
+ else:
+ inputs["input_ids"] = outputs_cached.sequences
+ if "attention_mask" in inputs:
+ inputs["attention_mask"] = torch.nn.functional.pad(
+ inputs["attention_mask"],
+ (0, new_attention_len - inputs["attention_mask"].shape[1]),
+ mode="constant",
+ value=1,
+ )
+ outputs_cached = model.generate(**inputs, do_sample=False, max_new_tokens=1, return_dict_in_generate=True)
+
+ # The two sets of generated text and past kv should be equal to each other
+ self.assertListEqual(outputs.sequences.tolist(), outputs_cached.sequences.tolist())
+ for layer_idx in range(len(outputs_cached.past_key_values)):
+ for kv_idx in range(len(outputs_cached.past_key_values[layer_idx])):
+ self.assertTrue(
+ torch.allclose(
+ outputs.past_key_values[layer_idx][kv_idx],
+ outputs_cached.past_key_values[layer_idx][kv_idx],
+ )
+ )
+
+ @pytest.mark.generate
+ def test_generate_continue_from_inputs_embeds(self):
+ """Tests that we can continue generation from `inputs_embeds` and past key values returned from a previous `generate` call."""
+ for model_class in self.all_generative_model_classes:
+ if any(model_name in model_class.__name__.lower() for model_name in ["imagegpt"]):
+ self.skipTest(reason="Won't fix: old model with unique inputs/caches/other")
+ if any(model_name in model_class.__name__.lower() for model_name in ["umt5"]):
+ self.skipTest(reason="TODO: needs modeling or test input preparation fixes for compatibility")
+
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+
+ if "token_type_ids" in inputs_dict:
+ del inputs_dict["token_type_ids"]
+
+ if config.is_encoder_decoder:
+ self.skipTest(reason="This model is encoder-decoder")
+ if not hasattr(config, "use_cache"):
+ self.skipTest(reason=f"{model_class.__name__} doesn't support caching")
+
+ model = model_class(config).to(torch_device).eval()
+
+ if "inputs_embeds" not in inspect.signature(model.prepare_inputs_for_generation).parameters.keys():
+ self.skipTest(reason="This model does not support `inputs_embeds` in generation")
+
+ # If "past_key_values" is not returned, skip the test (e.g. RWKV uses a different cache name and format)
+ outputs = model(**inputs_dict)
+ if "past_key_values" not in outputs:
+ self.skipTest(reason="This model doesn't return `past_key_values`")
+
+ pixel_values_is_mutually_exclusive = any(
+ model_name in model_class.__name__.lower() for model_name in VLM_CLASS_NAMES
+ )
+ if pixel_values_is_mutually_exclusive:
+ inputs_dict.pop("pixel_values", None)
+ inputs_dict.pop("pixel_values_videos", None)
+ inputs_dict.pop("pixel_values_images", None)
+
+ input_ids = inputs_dict.pop("input_ids")
+
+ model.generation_config.pad_token_id = model.generation_config.eos_token_id = -1
+ model.generation_config.forced_eos_token_id = None
+ model.config.is_decoder = True
+ model.generation_config.use_cache = True
+
+ generation_kwargs = {
+ "return_dict_in_generate": True,
+ "do_sample": False,
+ }
+
+ # Traditional way of generating text, with `return_dict_in_generate` to return the past key values.
+ input_embeds = model.get_input_embeddings()(input_ids)
+ outputs = model.generate(inputs_embeds=input_embeds, max_new_tokens=4, **generation_kwargs)
+
+ # Let's generate again, but passing the past key values in between (3 + 1 = 4 tokens)
+ initial_output = model.generate(inputs_embeds=input_embeds, max_new_tokens=3, **generation_kwargs)
+ continued_embeds = torch.cat([input_embeds, model.get_input_embeddings()(initial_output.sequences)], dim=1)
+ cached_output = model.generate(
+ inputs_embeds=continued_embeds,
+ max_new_tokens=1,
+ past_key_values=initial_output.past_key_values,
+ **generation_kwargs,
+ )
+
+ # Combine the (3 + 1) generated tokens and verify it matches with full generation.
+ combined_output_sequences = torch.concat([initial_output.sequences, cached_output.sequences], axis=1)
+ self.assertListEqual(outputs.sequences.tolist(), combined_output_sequences.tolist())
+ # The two sets of past kv should be equal to each other
+ for layer_idx in range(len(cached_output.past_key_values)):
+ for kv_idx in range(len(cached_output.past_key_values[layer_idx])):
+ self.assertTrue(
+ torch.allclose(
+ outputs.past_key_values[layer_idx][kv_idx],
+ cached_output.past_key_values[layer_idx][kv_idx],
+ )
+ )
+
+ @parameterized.expand([("offloaded",)]) # ("offloaded_static",) TODO: @raushan fixme in some models (eg T5)
+ @require_torch_gpu
+ @pytest.mark.generate
+ def test_offloaded_cache_implementation(self, cache_implementation):
+ """Tests we can generate by indicating `cache_implementation` for each possible cache class"""
+ for model_class in self.all_generative_model_classes:
+ if not model_class._supports_cache_class:
+ self.skipTest(reason="This model does not support the new cache format")
+
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+
+ model = model_class(config).to(torch_device).eval()
+ generation_kwargs = {
+ "max_new_tokens": 5,
+ "use_cache": True,
+ "cache_implementation": cache_implementation,
+ }
+
+ legacy_results = model.generate(**generation_kwargs, **inputs_dict)
+
+ # Most cache classes have their own tests except for some that are tested here
+ # The ones here do not need special treatment when passing `cache_implementation`
+ # and are not bound to specific models only
+ new_results = model.generate(**generation_kwargs, **inputs_dict)
+ self.assertListEqual(legacy_results.tolist(), new_results.tolist())
+
+ @pytest.mark.generate
+ def test_generate_with_static_cache(self):
+ """
+ Tests that generating with static cache give almost same results as with dynamic cache, and the output cache
+ has the expected shapes
+ """
+ set_model_tester_for_less_flaky_test(self)
+ for model_class in self.all_generative_model_classes:
+ if not model_class._supports_static_cache:
+ self.skipTest(reason="This model does not support the static cache format")
+
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+ set_config_for_less_flaky_test(config)
+ main_input = inputs_dict[model_class.main_input_name]
+
+ if config.is_encoder_decoder:
+ self.skipTest(reason="This model is encoder-decoder and has Encoder-Decoder Cache")
+
+ config.is_decoder = True
+ batch_size = main_input.shape[0]
+ seq_length = self.model_tester.seq_length
+ max_new_tokens = 20
+
+ for dtype in (torch.float32, torch.float16):
+ model = model_class(config).to(torch_device).to(dtype).eval()
+ inputs_dict = {
+ k: v.to(dtype) if isinstance(v, torch.Tensor) and torch.is_floating_point(v) else v
+ for k, v in inputs_dict.items()
+ }
+ set_model_for_less_flaky_test(model)
+
+ generation_kwargs = {
+ "max_new_tokens": max_new_tokens,
+ "return_dict_in_generate": True, # Required to return `past_key_values`
+ "output_scores": True,
+ "use_cache": True,
+ }
+
+ static_cache_generation = model.generate(
+ **generation_kwargs, **inputs_dict, cache_implementation="static"
+ )
+
+ # Check 1: The cache shapes must match the expected shapes
+ max_cache_len = seq_length + max_new_tokens - 1 # cache len = gen len - 1, the last token has no cache
+ text_config = config.text_config if hasattr(config, "text_config") else config
+ head_dim = (
+ text_config.head_dim
+ if hasattr(text_config, "head_dim")
+ else text_config.hidden_size // text_config.num_attention_heads
+ )
+ num_key_value_heads = (
+ text_config.num_attention_heads
+ if getattr(text_config, "num_key_value_heads", None) is None
+ else text_config.num_key_value_heads
+ )
+ num_hidden_layers = text_config.num_hidden_layers
+ cache_shape = (batch_size, num_key_value_heads, max_cache_len, head_dim)
+ self.assertTrue(isinstance(static_cache_generation.past_key_values, StaticCache))
+ self.assertTrue(len(static_cache_generation.past_key_values.key_cache) == num_hidden_layers)
+ self.assertTrue(static_cache_generation.past_key_values.key_cache[0].shape == cache_shape)
+
+ # Check 2: The outputs must be similar to the case with dynamic cache
+ dynamic_cache_generation = model.generate(**generation_kwargs, **inputs_dict)
+ self._check_similar_generate_outputs(dynamic_cache_generation, static_cache_generation)
+
+ @require_optimum_quanto
+ @pytest.mark.generate
+ def test_generate_with_quant_cache(self):
+ for model_class in self.all_generative_model_classes:
+ if not model_class._supports_quantized_cache:
+ self.skipTest(reason="This model does not support the quantized cache format")
+
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+ config.is_decoder = True
+
+ model = model_class(config).to(torch_device).eval()
+ generation_kwargs = {
+ "max_new_tokens": 5,
+ "cache_implementation": "quantized",
+ # careful with group size, should be divisor of model's hidden size
+ "cache_config": {"backend": "quanto", "nbits": 2, "q_group_size": 8, "residual_length": 128},
+ "return_dict_in_generate": True, # Required to return `past_key_values`
+ "use_cache": True,
+ }
+
+ results = model.generate(**generation_kwargs, **inputs_dict)
+ self.assertTrue(isinstance(results.past_key_values, QuantoQuantizedCache))
+
+ # passing past key values of different type should raise Error
+ with self.assertRaises(ValueError):
+ model.generate(past_key_valyes=DynamicCache(), **generation_kwargs, **inputs_dict)
+
+ # setting incorrect cache_config args should raise an Error, i.e. nbits=60 does not make sense
+ generation_kwargs["cache_config"] = {"nbits": 60, "q_group_size": 8, "residual_length": 128}
+ with self.assertRaises(ValueError):
+ model.generate(**generation_kwargs, **inputs_dict)
+
+ @pytest.mark.generate
+ def test_generate_compile_model_forward(self):
+ """
+ Tests that `.generate` is compatible with torch.compile without graph breaks, keeping the same results.
+ ⚠️ Runs two sequential generations to ensure the cache doesn't get stuck after the first compiled run! ⚠️
+ """
+ # Monkey-patching the HybridCache at test-time to continue testing compilation support
+ HybridCache.is_compileable = True
+
+ for model_class in self.all_generative_model_classes:
+ if not model_class._supports_static_cache:
+ self.skipTest("This model doesn't support static cache (= no expectations of compilation support)")
+
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate(batch_size=4)
+
+ model = model_class(config).to(torch_device)
+ model.eval() # otherwise `self.training` is `True` -- this flag is used at attn mask creation time
+
+ main_input = inputs_dict[model.main_input_name].to(torch_device)
+ # creates two sets of *different* inputs with the same shape
+ half_batch_size = main_input.shape[0] // 2
+ input_1 = {}
+ input_2 = {}
+ for key, value in inputs_dict.items():
+ if isinstance(value, torch.Tensor):
+ input_1[key] = value[:half_batch_size, :].to(torch_device)
+ input_2[key] = value[half_batch_size : half_batch_size * 2, :].to(torch_device)
+ else:
+ input_1[key] = value
+ input_2[key] = value
+ model_input_sets = [input_1, input_2]
+ self.assertTrue(
+ model_input_sets[0][model.main_input_name].shape == model_input_sets[1][model.main_input_name].shape
+ )
+
+ # compilation-specific setup
+ torch.compiler.reset() # prevent cached compilation from being used in the test
+ has_defined_cache_implementation = model.generation_config.cache_implementation is not None
+
+ # BLIP is the only exception with custom generate which call `self.lm.generate()`
+ # We should avoid such calls in all subsequent multimodal models and try to make `generate()`
+ # compatible with multimodality
+ if "blip" in model.__class__.__name__.lower():
+ model.language_model.generation_config.compile_config._compile_all_devices = True
+ else:
+ # force compilation (e.g. fast CI, CPU
+ model.generation_config.compile_config._compile_all_devices = True
+
+ generation_kwargs = {
+ "do_sample": False,
+ "max_new_tokens": 5,
+ "return_dict_in_generate": True,
+ "output_scores": True,
+ }
+
+ # get eager + dynamic cache results for future comparison
+ dynamic_outputs = []
+ for model_inputs in model_input_sets:
+ gen_out = model.generate(**model_inputs, **generation_kwargs)
+ dynamic_outputs.append(gen_out)
+ # sanity checks for the default cache implementation
+ if not has_defined_cache_implementation:
+ decoder_cache = (
+ gen_out.past_key_values.self_attention_cache
+ if config.is_encoder_decoder
+ else gen_out.past_key_values
+ )
+ self.assertTrue(isinstance(decoder_cache, DynamicCache))
+ self.assertFalse(decoder_cache.is_compileable)
+ self.assertFalse(hasattr(model, "_compiled_call")) # our auto compile should NOT have been called
+
+ # get compiled results -- relies on the automatic compilation triggered by specific "cache_implementation"
+ if not has_defined_cache_implementation:
+ generation_kwargs["cache_implementation"] = "static"
+
+ compiled_outputs = []
+ for model_inputs in model_input_sets:
+ gen_out = model.generate(**model_inputs, **generation_kwargs)
+ compiled_outputs.append(gen_out)
+ # sanity checks
+ decoder_cache = (
+ gen_out.past_key_values.self_attention_cache
+ if config.is_encoder_decoder
+ else gen_out.past_key_values
+ )
+ self.assertFalse(isinstance(decoder_cache, DynamicCache))
+ self.assertTrue(decoder_cache.is_compileable)
+
+ # BLIP is the only exception with custom generate which call `self.lm.generate()`
+ # We should avoid such calls in all subsequent multimodal models and try to make `generate()`
+ # compatible with multimodality
+ if "blip" in model.__class__.__name__.lower():
+ self.assertTrue(hasattr(model.language_model, "_compiled_call"))
+ else:
+ self.assertTrue(hasattr(model, "_compiled_call")) # our auto compile should have been called
+
+ for dynamic_result, compiled_result in zip(dynamic_outputs, compiled_outputs):
+ self._check_similar_generate_outputs(dynamic_result, compiled_result)
+
+ @pytest.mark.generate
+ def test_generate_compilation_all_outputs(self):
+ """
+ Tests that all optional outputs are behaving as expected when compilation is triggered.
+ In essence, it's the same as `test_greedy_generate_dict_outputs`, but with automatic compilation triggered.
+ """
+ # Monkey-patching the HybridCache at test-time to continue testing compilation support
+ HybridCache.is_compileable = True
+
+ for model_class in self.all_generative_model_classes:
+ if not model_class._supports_static_cache:
+ self.skipTest("This model doesn't support static cache (= no expectations of compilation support)")
+
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+ if self.has_attentions:
+ config._attn_implementation = "eager" # can't output attentions otherwise
+ model = model_class(config).to(torch_device).eval()
+
+ # compilation-specific setup
+ torch.compiler.reset() # prevent cached compilation from being used in the test
+ has_defined_cache_implementation = model.generation_config.cache_implementation is not None
+
+ # BLIP is the only exception with custom generate which call `self.lm.generate()`
+ # We should avoid such calls in all subsequent multimodal models and try to make `generate()`
+ # compatible with multimodality
+ if "blip" in model.__class__.__name__.lower():
+ model.language_model.generation_config.compile_config._compile_all_devices = True
+ if not has_defined_cache_implementation:
+ model.language_model.generation_config.cache_implementation = "static"
+ else:
+ # force compilation (e.g. fast CI, CPU)
+ model.generation_config.compile_config._compile_all_devices = True
+ if not has_defined_cache_implementation:
+ model.generation_config.cache_implementation = "static"
+
+ logits_processor_kwargs = self._get_logits_processor_kwargs(do_sample=False, config=model.config)
+ output_generate = model.generate(
+ do_sample=False,
+ num_beams=1,
+ max_new_tokens=self.max_new_tokens,
+ min_new_tokens=self.max_new_tokens,
+ output_attentions=True,
+ output_hidden_states=True,
+ output_scores=True,
+ output_logits=True,
+ return_dict_in_generate=True,
+ use_cache=True,
+ **logits_processor_kwargs,
+ **inputs_dict,
+ )
+
+ if "blip" in model.__class__.__name__.lower():
+ self.assertTrue(hasattr(model.language_model, "_compiled_call"))
+ else:
+ self.assertTrue(hasattr(model, "_compiled_call")) # our auto compile should have been called
+
+ if model.config.is_encoder_decoder:
+ self.assertTrue(output_generate.sequences.shape[-1] == self.max_new_tokens + 1)
+ self.assertIsInstance(output_generate, GenerateEncoderDecoderOutput)
+ else:
+ self.assertTrue(
+ output_generate.sequences.shape[-1] == self.max_new_tokens + inputs_dict["input_ids"].shape[-1]
+ )
+ self.assertIsInstance(output_generate, GenerateDecoderOnlyOutput)
+
+ self._check_generate_outputs(output_generate, model.config, use_cache=True)
+
+ @pytest.mark.generate
+ def test_generate_methods_with_logits_to_keep(self):
+ for model_class in self.all_generative_model_classes:
+ if "logits_to_keep" not in set(inspect.signature(model_class.forward).parameters.keys()):
+ self.skipTest(reason="This model does not support `logits_to_keep` argument.")
+
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+ config.use_cache = True
+ config.is_decoder = True
+
+ model = model_class(config).to(torch_device).eval()
+ # All generation methods (except assisted decoding) rely on always extracting the last token logits of the
+ # full logits matrix, so testing out only greedy search and assisted decoding is enough (if it works,
+ # other methods will work as well)
+ generation_kwargs = {
+ "max_new_tokens": 10,
+ "do_sample": False,
+ }
+
+ # Setting logits_to_keep at 0 keeps all logits (old behavior)
+ with_all_logits = model.generate(**generation_kwargs, **inputs_dict, logits_to_keep=0)
+ # By default, logits_to_keep is automatically set to 1 if not provided (new behavior)
+ without_all_logits = model.generate(**inputs_dict, **generation_kwargs)
+ self.assertEqual(with_all_logits.tolist(), without_all_logits.tolist())
+
+ @pytest.mark.generate
+ def test_inherits_generation_mixin(self):
+ """
+ Tests that the model class directly inherits `GenerationMixin`, as opposed to relying on `PreTrainedModel`
+ to inherit it.
+ """
+ for model_class in self.all_generative_model_classes:
+ self.assertTrue("GenerationMixin" in str(model_class.__bases__))
+
+ def _test_attention_implementation(self, attn_implementation):
+ """
+ Compares the output of generate with the eager attention implementation against other implementations.
+ NOTE: despite the test logic being the same, different implementations actually need diferent decorators, hence
+ this separate function.
+ """
+ max_new_tokens = 30
+ support_flag = {
+ "sdpa": "_supports_sdpa",
+ "flash_attention_2": "_supports_flash_attn_2",
+ }
+
+ for model_class in self.all_generative_model_classes:
+ if not getattr(model_class, support_flag[attn_implementation]):
+ self.skipTest(f"{model_class.__name__} does not support `attn_implementation={attn_implementation}`")
+
+ config, original_inputs_dict = self.prepare_config_and_inputs_for_generate()
+ inputs_dict = {}
+ for input_name, input_data in original_inputs_dict.items():
+ if isinstance(input_data, torch.Tensor) and input_data.dtype in [torch.float32, torch.bfloat16]:
+ inputs_dict[input_name] = input_data.to(torch.float16)
+ else:
+ inputs_dict[input_name] = input_data
+ main_input = inputs_dict[model_class.main_input_name]
+
+ # make sure that all models have enough positions for generation
+ if hasattr(config, "max_position_embeddings"):
+ config.max_position_embeddings = max_new_tokens + main_input.shape[1] + 1
+
+ model = model_class(config)
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ model.save_pretrained(tmpdirname)
+ del model
+ gc.collect()
+
+ generate_kwargs = {
+ "max_new_tokens": max_new_tokens,
+ "do_sample": False,
+ "return_dict_in_generate": True,
+ "output_scores": True,
+ "use_cache": True,
+ }
+
+ model_eager = model_class.from_pretrained(
+ tmpdirname,
+ torch_dtype=torch.float16,
+ low_cpu_mem_usage=True,
+ attn_implementation="eager",
+ ).to(torch_device)
+ res_eager = model_eager.generate(**inputs_dict, **generate_kwargs)
+ del model_eager
+ gc.collect()
+
+ model_attn = model_class.from_pretrained(
+ tmpdirname,
+ torch_dtype=torch.float16,
+ low_cpu_mem_usage=True,
+ attn_implementation=attn_implementation,
+ ).to(torch_device)
+ res_attn = model_attn.generate(**inputs_dict, **generate_kwargs)
+ del model_attn
+ gc.collect()
+
+ self._check_similar_generate_outputs(res_eager, res_attn, atol=1e-3, rtol=1e-3)
+
+ @pytest.mark.generate
+ @require_torch_sdpa
+ @slow
+ def test_eager_matches_sdpa_generate(self):
+ """Tests that generate has equivalent outputs with SDPA and eager attention implementations."""
+ self._test_attention_implementation("sdpa")
+
+ @pytest.mark.flash_attn_test
+ @require_flash_attn
+ @require_torch_gpu
+ @slow
+ def test_eager_matches_fa2_generate(self):
+ """Tests that generate has equivalent outputs with FA2 and eager attention implementations."""
+ # TODO (@joao @raushan) -- this test is failing the output checks on most models, investigate. After fixing,
+ # check whether we still need the overwrites
+ self._test_attention_implementation("flash_attention_2")
+
+ def _check_generate_outputs(self, output, config, use_cache=False, num_return_sequences=1, num_beams=1):
+ input_batch_size = int(output.sequences.shape[0] / num_return_sequences)
+ internal_batch_size = (
+ input_batch_size * num_beams if num_beams > 1 else input_batch_size * num_return_sequences
+ )
+
+ prompt_length = getattr(self.model_tester, "seq_length", None)
+ prompt_length = getattr(self.model_tester, "encoder_seq_length", prompt_length)
+ prompt_length = getattr(self.model_tester, "text_seq_length", prompt_length)
+
+ config = config.text_config if hasattr(config, "text_config") else config
+
+ generated_length = (
+ output.sequences.shape[-1] - 1 if config.is_encoder_decoder else output.sequences.shape[-1] - prompt_length
+ )
+ decoder_past_key_values = getattr(output, "past_key_values", None)
+ if config.is_encoder_decoder and isinstance(decoder_past_key_values, EncoderDecoderCache):
+ decoder_past_key_values = decoder_past_key_values.self_attention_cache
+
+ # in some models we subsample the sequence length in inner layers
+ if hasattr(self.model_tester, "get_subsampled_output_lengths"):
+ prompt_length = self.model_tester.get_subsampled_output_lengths(prompt_length)
+
+ # scores
+ self._check_scores(
+ batch_size=internal_batch_size, scores=output.scores, generated_length=generated_length, config=config
+ )
+
+ # unprocessed logits
+ self._check_logits(batch_size=internal_batch_size, logits=output.logits, config=config)
+
+ # Attentions
+ if self.has_attentions:
+ if config.is_encoder_decoder:
+ # encoder
+ self._check_encoder_attention_for_generate(
+ attentions=output.encoder_attentions,
+ batch_size=input_batch_size,
+ config=config,
+ prompt_length=prompt_length,
+ )
+ # decoder
+ self._check_attentions_for_generate(
+ batch_size=internal_batch_size,
+ attentions=output.decoder_attentions,
+ prompt_length=1, # the BOS token
+ output_length=output.sequences.shape[-1],
+ config=config,
+ decoder_past_key_values=decoder_past_key_values,
+ )
+ else:
+ self._check_attentions_for_generate(
+ batch_size=internal_batch_size,
+ attentions=output.attentions,
+ prompt_length=prompt_length,
+ output_length=output.sequences.shape[-1],
+ config=config,
+ decoder_past_key_values=decoder_past_key_values,
+ )
+
+ # Hidden States
+ if config.is_encoder_decoder:
+ # encoder
+ self._check_encoder_hidden_states_for_generate(
+ hidden_states=output.encoder_hidden_states,
+ batch_size=input_batch_size,
+ config=config,
+ prompt_length=prompt_length,
+ )
+ # decoder
+ self._check_hidden_states_for_generate(
+ batch_size=internal_batch_size,
+ hidden_states=output.decoder_hidden_states,
+ prompt_length=1, # the BOS token
+ output_length=output.sequences.shape[-1],
+ config=config,
+ use_cache=use_cache,
+ )
+ else:
+ self._check_hidden_states_for_generate(
+ batch_size=internal_batch_size,
+ hidden_states=output.hidden_states,
+ prompt_length=prompt_length,
+ output_length=output.sequences.shape[-1],
+ config=config,
+ use_cache=use_cache,
+ )
+
+ # Past Key Value States -- a few notes here:
+ # 1. Its inner sequence length is with respect to the inputs of the latest forward pass, hence the "-1"
+ # 2. We ignore models that have unique cache structures (e.g. mamba) or are in need of refatoring to match the
+ # standard cache format (e.g.gptbigcode )
+ models_without_standard_cache = (
+ "bamba",
+ "ctrl",
+ "fsmt",
+ "gptbigcode",
+ "mega",
+ "reformer",
+ "jamba",
+ "mamba",
+ "xlnet",
+ "zamba",
+ "zamba2",
+ )
+ has_standard_cache = not any(
+ model_name in config.__class__.__name__.lower() for model_name in models_without_standard_cache
+ )
+ if has_standard_cache:
+ if use_cache:
+ cache_length = output.sequences.shape[-1] - 1
+ self._check_past_key_values_for_generate(
+ batch_size=internal_batch_size,
+ decoder_past_key_values=decoder_past_key_values,
+ cache_length=cache_length,
+ config=config,
+ )
+ elif use_cache is False:
+ self.assertTrue(decoder_past_key_values is None)
+
+ def _check_scores(self, batch_size, scores, generated_length, config):
+ vocab_size = config.get_text_config(decoder=True).vocab_size
+ expected_shape = (batch_size, vocab_size)
+ self.assertIsInstance(scores, tuple)
+ self.assertEqual(len(scores), generated_length)
+ self.assertListEqual([iter_scores.shape for iter_scores in scores], [expected_shape] * len(scores))
+
+ def _check_logits(self, batch_size, logits, config):
+ vocab_size = config.get_text_config(decoder=True).vocab_size
+ self.assertIsInstance(logits, tuple)
+ self.assertListEqual([iter_logits.shape[0] for iter_logits in logits], [batch_size] * len(logits))
+ # vocabulary difference equal to one (imagegptmodel?) or zero (all other models)
+ vocab_diff = vocab_size - logits[0].shape[-1]
+ self.assertTrue(vocab_diff in [0, 1])
+ self.assertListEqual([vocab_size - score.shape[-1] for score in logits], [vocab_diff] * len(logits))
+
+ def _check_attentions_for_generate(
+ self, batch_size, attentions, prompt_length, output_length, config, decoder_past_key_values
+ ):
+ self.assertIsInstance(attentions, tuple)
+ self.assertListEqual(
+ [isinstance(iter_attentions, tuple) for iter_attentions in attentions], [True] * len(attentions)
+ )
+ self.assertEqual(len(attentions), (output_length - prompt_length))
+
+ use_cache = decoder_past_key_values is not None
+ has_static_cache = isinstance(decoder_past_key_values, (StaticCache, HybridCache))
+
+ # When `output_attentions=True`, each iteration of generate appends the attentions corresponding to the new
+ # token(s)
+ # NOTE: `HybridCache` may have different lengths on different layers, if this test starts failing add more
+ # elaborate checks
+ for generated_length, iter_attentions in enumerate(attentions):
+ # regardless of using cache, the first forward pass will have the full prompt as input
+ if use_cache and generated_length > 0:
+ model_input_length = 1
+ else:
+ model_input_length = prompt_length + generated_length
+ query_length = (
+ prompt_length + generated_length
+ if not has_static_cache
+ else decoder_past_key_values.get_max_cache_shape()
+ )
+
+ expected_shape = (
+ batch_size,
+ config.num_attention_heads,
+ model_input_length,
+ query_length,
+ )
+ # check attn size
+ self.assertListEqual(
+ [layer_attention.shape for layer_attention in iter_attentions], [expected_shape] * len(iter_attentions)
+ )
+
+ def _check_encoder_attention_for_generate(self, attentions, batch_size, config, prompt_length):
+ encoder_expected_shape = (batch_size, config.num_attention_heads, prompt_length, prompt_length)
+ self.assertIsInstance(attentions, tuple)
+ self.assertListEqual(
+ [layer_attentions.shape for layer_attentions in attentions],
+ [encoder_expected_shape] * len(attentions),
+ )
+
+ def _check_hidden_states_for_generate(
+ self, batch_size, hidden_states, prompt_length, output_length, config, use_cache=False
+ ):
+ self.assertIsInstance(hidden_states, tuple)
+ self.assertListEqual(
+ [isinstance(iter_hidden_states, tuple) for iter_hidden_states in hidden_states],
+ [True] * len(hidden_states),
+ )
+ self.assertEqual(len(hidden_states), (output_length - prompt_length))
+
+ # When `output_hidden_states=True`, each iteration of generate appends the hidden states corresponding to the
+ # new token(s)
+ # NOTE: `HybridCache` may have different lengths on different layers, if this test starts failing add more
+ # elaborate checks
+ for generated_length, iter_hidden_states in enumerate(hidden_states):
+ # regardless of using cache, the first forward pass will have the full prompt as input
+ if use_cache and generated_length > 0:
+ model_input_length = 1
+ else:
+ model_input_length = prompt_length + generated_length
+ expected_shape = (batch_size, model_input_length, config.hidden_size)
+ # check hidden size
+ self.assertListEqual(
+ [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states],
+ [expected_shape] * len(iter_hidden_states),
+ )
+
+ def _check_encoder_hidden_states_for_generate(self, hidden_states, batch_size, config, prompt_length):
+ encoder_expected_shape = (batch_size, prompt_length, config.hidden_size)
+ self.assertIsInstance(hidden_states, tuple)
+ self.assertListEqual(
+ [layer_hidden_states.shape for layer_hidden_states in hidden_states],
+ [encoder_expected_shape] * len(hidden_states),
+ )
+
+ def _check_past_key_values_for_generate(self, batch_size, decoder_past_key_values, cache_length, config):
+ self.assertIsInstance(decoder_past_key_values, (tuple, Cache))
+
+ # (batch, head, seq_length, head_features)
+ expected_shape = (
+ batch_size,
+ config.num_key_value_heads if hasattr(config, "num_key_value_heads") else config.num_attention_heads,
+ cache_length,
+ config.hidden_size // config.num_attention_heads,
+ )
+
+ if isinstance(decoder_past_key_values, Cache):
+ self.assertListEqual(
+ [key_tensor.shape for key_tensor in decoder_past_key_values.key_cache],
+ [expected_shape] * len(decoder_past_key_values.key_cache),
+ )
+ self.assertListEqual(
+ [value_tensor.shape for value_tensor in decoder_past_key_values.value_cache],
+ [expected_shape] * len(decoder_past_key_values.value_cache),
+ )
+
+ # Legacy cache format checks. This branch should be removed when all models use `Cache` by default
+ else:
+ self.assertListEqual(
+ [isinstance(iter_past_key_values, tuple) for iter_past_key_values in decoder_past_key_values],
+ [True] * len(decoder_past_key_values),
+ )
+ # check shape key, value
+ self.assertListEqual(
+ [layer_past_key_values[0].shape for layer_past_key_values in decoder_past_key_values],
+ [expected_shape] * len(decoder_past_key_values),
+ )
+ self.assertListEqual(
+ [layer_past_key_values[1].shape for layer_past_key_values in decoder_past_key_values],
+ [expected_shape] * len(decoder_past_key_values),
+ )
+
+ def _check_sequence_inside_sequence(self, tensor_1, tensor_2):
+ # check if tensor_1 inside tensor_2 or tensor_2 inside tensor_1.
+ # set to same device. we don't care what device.
+
+ if not isinstance(tensor_1, list):
+ tensor_1 = tensor_1.cpu().tolist()
+ if not isinstance(tensor_2, list):
+ tensor_2 = tensor_2.cpu().tolist()
+
+ in_order = len(tensor_1) <= len(tensor_2)
+ longer = tensor_2 if in_order else tensor_1
+ shorter = tensor_1 if in_order else tensor_2
+
+ flag = False
+ chunk_size = len(shorter)
+ for chunk_idx in range(len(longer) - chunk_size + 1):
+ subseq = longer[chunk_idx : chunk_idx + chunk_size]
+ if subseq == shorter:
+ flag = True
+ break
+
+ self.assertTrue(flag)
+
+
+@require_torch
+class UtilsFunctionsTest(unittest.TestCase):
+ def test_speculative_sampling(self):
+ # assume vocab size 10, input length 5 + 3 generated candidates
+ candidate_input_ids = torch.tensor([[8, 0, 3, 9, 8, 1, 4, 5]]) # input tokens
+ candidate_logits = torch.tensor(
+ [
+ [
+ [-10.0, 10.0, -10.0, -10.0, -10.0, -10.0, -10.0, -10.0, -10.0, -10.0], # generated 1
+ [-10.0, -10.0, -10.0, -10.0, 10.0, -10.0, -10.0, -10.0, -10.0, -10.0], # generated 4
+ [-10.0, -10.0, -10.0, -10.0, -10.0, 10.0, -10.0, -10.0, -10.0, -10.0], # generated 5
+ ]
+ ]
+ )
+ candidate_length = 3
+ inf = float("inf")
+ new_logits = torch.tensor(
+ [
+ [
+ [-10.0, 10.0, -10.0, -10.0, -10.0, -10.0, -10.0, -10.0, -10.0, -10.0], # accepts 1
+ [-10.0, -10.0, -10.0, -10.0, 10.0, -10.0, -10.0, -10.0, -10.0, -10.0], # accepts 4
+ [-inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, 10.0, -inf], # rejects 5, accepts 8
+ [-10.0, -10.0, -10.0, -10.0, -10.0, -10.0, -10.0, -10.0, -10.0, -10.0], # N/A
+ ]
+ ]
+ )
+ last_assistant_token_is_eos = False
+ validated_tokens, n_matches = _speculative_sampling(
+ candidate_input_ids,
+ candidate_logits,
+ candidate_length,
+ new_logits,
+ last_assistant_token_is_eos,
+ )
+ self.assertTrue(n_matches.item() == 2)
+ self.assertTrue(validated_tokens.tolist()[0] == [1, 4, 8])
+
+ def test_speculative_sampling_target_distribution(self):
+ """
+ Asserts that the target distribution is preserved.
+ Should help with catching issues like #32867.
+ """
+ # assume vocab size 10, input length 5 + 3 generated candidates
+ candidate_input_ids = torch.tensor([[8, 0, 3, 9, 8, 1, 4, 5]]) # input tokens
+ candidate_logits = torch.tensor(
+ [
+ [
+ [-10.0, 10.0, -10.0, -10.0, -10.0, -10.0, -10.0, -10.0, -10.0, -10.0], # generated 1
+ [-10.0, -10.0, -10.0, -10.0, 10.0, -10.0, -10.0, -10.0, -10.0, -10.0], # generated 4
+ [-10.0, -10.0, -10.0, -10.0, -10.0, 10.0, -10.0, -10.0, -10.0, -10.0], # generated 5
+ ]
+ ]
+ )
+ candidate_length = 3
+ inf = float("inf")
+ new_logits = torch.tensor(
+ [
+ [
+ # accepts 1:
+ [-inf, 10.0, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf],
+ # accepts 4:
+ [-inf, -inf, -inf, -inf, 10.0, -inf, -inf, -inf, -inf, -inf],
+ # most likely to be 1 or 8, less likely to be 3, then 7, and should never be any other value:
+ [-inf, 2.0, -inf, 1.0, -inf, -inf, -inf, -0.01, 2.0, -inf],
+ # N/A:
+ [-inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf],
+ ]
+ ]
+ )
+ last_assistant_token_is_eos = False
+ last_validated_token = []
+ for _ in range(10_000):
+ validated_tokens, n_matches = _speculative_sampling(
+ candidate_input_ids,
+ candidate_logits,
+ candidate_length,
+ new_logits,
+ last_assistant_token_is_eos,
+ )
+ self.assertTrue(n_matches.item() == 2)
+ self.assertTrue(validated_tokens.tolist()[0][0] == 1)
+ self.assertTrue(validated_tokens.tolist()[0][1] == 4)
+ self.assertTrue(validated_tokens.tolist()[0][2] in [1, 3, 7, 8])
+ last_validated_token.append(validated_tokens.tolist()[0][2])
+ # check that the most likely tokens are selected more often than the less likely ones
+ last_token_counts = collections.Counter(last_validated_token)
+ self.assertTrue(last_token_counts[1] > last_token_counts[3] > last_token_counts[7] > 0)
+ self.assertTrue(last_token_counts[8] > last_token_counts[3])
+
+
+global_rng = random.Random()
+
+
+# Copied from tests.test_modeling_common.ids_tensor
+def ids_tensor(shape, vocab_size, rng=None, name=None):
+ # Creates a random int32 tensor of the shape within the vocab size
+ if rng is None:
+ rng = global_rng
+
+ total_dims = 1
+ for dim in shape:
+ total_dims *= dim
+
+ values = []
+ for _ in range(total_dims):
+ values.append(rng.randint(0, vocab_size - 1))
+
+ return torch.tensor(data=values, dtype=torch.long, device=torch_device).view(shape).contiguous()
+
+
+# Copied from tests.test_modeling_common.floats_tensor
+def floats_tensor(shape, scale=1.0, rng=None, name=None):
+ """Creates a random float32 tensor"""
+ if rng is None:
+ rng = global_rng
+
+ total_dims = 1
+ for dim in shape:
+ total_dims *= dim
+
+ values = []
+ for _ in range(total_dims):
+ values.append(rng.random() * scale)
+
+ return torch.tensor(data=values, dtype=torch.float, device=torch_device).view(shape).contiguous()
+
+
+@pytest.mark.generate
+@require_torch
+class GenerationIntegrationTests(unittest.TestCase):
+ @slow
+ def test_diverse_beam_search(self):
+ article = """Justin Timberlake and Jessica Biel, welcome to parenthood.
+ The celebrity couple announced the arrival of their son, Silas Randall Timberlake, in statements to People.
+ "Silas was the middle name of Timberlake's maternal grandfather Bill Bomar, who died in 2012, while Randall is the musician's own middle name, as well as his father's first," People reports.
+ The couple announced the pregnancy in January, with an Instagram post. It is the first baby for both."""
+
+ bart_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")
+ bart_model = BartForConditionalGeneration.from_pretrained("facebook/bart-large-cnn").to(torch_device)
+ input_ids = bart_tokenizer(article, return_tensors="pt").input_ids.to(torch_device)
+
+ outputs = bart_model.generate(
+ input_ids,
+ num_beams=4,
+ num_return_sequences=2,
+ num_beam_groups=4,
+ diversity_penalty=2.0,
+ remove_invalid_values=True,
+ )
+
+ generated_text = bart_tokenizer.batch_decode(outputs, skip_special_tokens=True)
+
+ self.assertListEqual(
+ generated_text,
+ [
+ "The couple announced the birth of their son, Silas Randall Timberlake, in a statement. Silas was the"
+ " middle name of Timberlake's maternal grandfather Bill Bomar. Randall is the musician's own middle"
+ " name, as well as his father's first. It is the first baby for both of them.",
+ "Justin Timberlake and Jessica Biel have a son. The baby is named Silas Randall Timberlake. It is the"
+ " first child for both. The couple announced the pregnancy in January. The name Silas is the middle"
+ " name of Timberlake's maternal grandfather. It's also his own middle name.",
+ ],
+ )
+
+ def test_max_length_if_input_embeds(self):
+ article = "Today a dragon flew over Paris."
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ input_ids = tokenizer(article, return_tensors="pt").input_ids.to(torch_device)
+ inputs_embeds = model.get_input_embeddings()(input_ids)
+
+ max_length = 20
+ input_len = input_ids.shape[-1]
+ out_gen = model.generate(input_ids=input_ids, max_length=max_length)
+ out_gen_embeds = model.generate(inputs_embeds=inputs_embeds, max_length=max_length)
+ self.assertEqual(out_gen.shape[-1], input_len + out_gen_embeds.shape[-1])
+
+ def test_min_length_if_input_embeds(self):
+ article = "Today a dragon flew over Paris."
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ input_ids = tokenizer(article, return_tensors="pt").input_ids.to(torch_device)
+ inputs_embeds = model.get_input_embeddings()(input_ids)
+
+ min_length = 10
+ input_len = input_ids.shape[-1]
+ out_gen = model.generate(input_ids=input_ids, min_length=min_length)
+ out_gen_embeds = model.generate(inputs_embeds=inputs_embeds, min_length=min_length)
+ self.assertEqual(out_gen.shape[-1], input_len + out_gen_embeds.shape[-1])
+
+ def test_custom_stopping_criteria_overload_error(self):
+ article = """Justin Timberlake and Jessica Biel, welcome to parenthood."""
+ bart_tokenizer = BartTokenizer.from_pretrained("sshleifer/bart-tiny-random")
+ bart_model = BartForConditionalGeneration.from_pretrained("sshleifer/bart-tiny-random").to(torch_device)
+
+ input_ids = bart_tokenizer(article, return_tensors="pt").input_ids.to(torch_device)
+ stopping_criteria = StoppingCriteriaList()
+ stopping_criteria.append(MaxLengthCriteria(max_length=42))
+ with self.assertRaises(ValueError):
+ bart_model.generate(input_ids, stopping_criteria=stopping_criteria)
+ with self.assertRaises(ValueError):
+ bart_model.generate(input_ids, stopping_criteria=stopping_criteria, max_length=32)
+
+ def test_custom_stopping_criteria(self):
+ article = """Justin Timberlake and Jessica Biel, welcome to parenthood."""
+ bart_tokenizer = BartTokenizer.from_pretrained("sshleifer/bart-tiny-random")
+ bart_model = BartForConditionalGeneration.from_pretrained("sshleifer/bart-tiny-random").to(torch_device)
+ input_ids = bart_tokenizer(article, return_tensors="pt").input_ids.to(torch_device)
+
+ class DummyCriteria(StoppingCriteria):
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
+ return input_ids.shape[-1] >= 20
+
+ stopping_criteria = StoppingCriteriaList()
+ stopping_criteria.append(DummyCriteria())
+
+ self.assertEqual(
+ list(bart_model.generate(input_ids, stopping_criteria=stopping_criteria, max_length=22).shape),
+ [1, 20],
+ )
+ self.assertEqual(
+ list(bart_model.generate(input_ids, stopping_criteria=stopping_criteria, max_length=18).shape),
+ [1, 18],
+ )
+
+ # TODO (joao): replace `stop_sequence` in the pipeline by the more recent `generate` functionality
+ def test_stop_sequence_stopping_criteria(self):
+ prompt = """Hello I believe in"""
+ generator = pipeline("text-generation", model="hf-internal-testing/tiny-random-bart")
+ output = generator(prompt)
+ self.assertEqual(
+ output,
+ [{"generated_text": ("Hello I believe in we we we we we we we we we")}],
+ )
+
+ output = generator(prompt, stop_sequence=" we")
+ self.assertEqual(output, [{"generated_text": "Hello I believe in we"}])
+
+ def test_generate_non_nlp_input_ids_as_kwarg(self):
+ model = ImageGPTForCausalImageModeling.from_pretrained(
+ "hf-internal-testing/tiny-random-imagegpt", max_length=10
+ ).to(torch_device)
+ input_ids = ids_tensor((3, 5), vocab_size=10)
+
+ output_sequences_kwargs = model.generate(input_ids=input_ids).cpu()
+ output_sequences = model.generate(input_ids).cpu()
+
+ self.assertListEqual(output_sequences.tolist(), output_sequences_kwargs.tolist())
+ self.assertEqual(output_sequences.shape, (3, 10))
+
+ def test_generate_input_values_as_encoder_kwarg(self):
+ input_values = floats_tensor((2, 250))
+ model = SpeechEncoderDecoderModel.from_pretrained("hf-internal-testing/tiny-random-speech-encoder-decoder")
+ model = model.to(torch_device)
+ output_sequences_kwargs = model.generate(input_values=input_values, max_length=5).cpu()
+ output_sequences = model.generate(input_values, max_length=5).cpu()
+
+ self.assertListEqual(output_sequences.tolist(), output_sequences_kwargs.tolist())
+ self.assertEqual(output_sequences.shape, (2, 5))
+
+ def test_transition_scores_group_beam_search_encoder_decoder(self):
+ articles = [
+ "Justin Timberlake and Jessica Biel, welcome to parenthood.",
+ "Michael Phelps is arguably the most decorated Olympian of all time.",
+ ]
+ tokenizer = BartTokenizer.from_pretrained("hf-internal-testing/tiny-random-bart")
+ model = BartForConditionalGeneration.from_pretrained(
+ "hf-internal-testing/tiny-random-bart",
+ max_length=10,
+ num_beams=2,
+ num_beam_groups=2,
+ num_return_sequences=2,
+ diversity_penalty=1.0,
+ eos_token_id=None,
+ return_dict_in_generate=True,
+ output_scores=True,
+ length_penalty=0.0,
+ )
+ model = model.to(torch_device)
+
+ input_ids = tokenizer(articles, return_tensors="pt", padding=True).input_ids.to(torch_device)
+ outputs = model.generate(input_ids=input_ids)
+
+ transition_scores = model.compute_transition_scores(outputs.sequences, outputs.scores, outputs.beam_indices)
+ transition_scores_sum = transition_scores.sum(-1)
+
+ torch.testing.assert_close(transition_scores_sum, outputs.sequences_scores, rtol=1e-3, atol=1e-3)
+
+ def test_beam_search_low_memory(self):
+ tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
+ model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
+ tokenizer.pad_token_id = tokenizer.eos_token_id
+ model_inputs = tokenizer("I", return_tensors="pt")["input_ids"]
+
+ low_output = model.generate(model_inputs, max_new_tokens=40, num_beams=5, early_stopping=True, low_memory=True)
+
+ high_output = model.generate(
+ model_inputs, max_new_tokens=40, num_beams=5, early_stopping=True, low_memory=False
+ )
+ self.assertListEqual(low_output.tolist(), high_output.tolist())
+
+ @slow
+ def test_green_red_watermark_generation(self):
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ tokenizer.pad_token_id = tokenizer.eos_token_id
+ model_inputs = tokenizer("I will be", return_tensors="pt").to(torch_device)
+ input_len = model_inputs["input_ids"].shape[-1]
+
+ # generation should work with both input types: WatermarkingConfig or Dict, so let's check it here :)
+ watermark_config = WatermarkingConfig(bias=2.5, seeding_scheme="selfhash")
+ _ = model.generate(**model_inputs, watermarking_config=watermark_config, do_sample=False, max_length=15)
+
+ # We will not check watermarked text, since we check it in `logits_processors` tests
+ # Checking if generated ids are as expected fails on different hardware
+ args = {
+ "bias": 2.0,
+ "context_width": 1,
+ "seeding_scheme": "selfhash",
+ "greenlist_ratio": 0.25,
+ "hashing_key": 15485863,
+ }
+ output = model.generate(**model_inputs, do_sample=False, max_length=15)
+ output_selfhash = model.generate(**model_inputs, watermarking_config=args, do_sample=False, max_length=15)
+
+ # Check that the detector is detecting watermarked text
+ detector = WatermarkDetector(model_config=model.config, device=torch_device, watermarking_config=args)
+ detection_out_watermarked = detector(output_selfhash[:, input_len:], return_dict=True)
+ detection_out = detector(output[:, input_len:], return_dict=True)
+
+ self.assertListEqual(detection_out_watermarked.prediction.tolist(), [True])
+ self.assertListEqual(detection_out.prediction.tolist(), [False])
+
+ """Check the mean bias inserted by the watermarking algorithm."""
+
+ @slow
+ def test_synthid_text_watermark_generation_mean_expected_bias(self):
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ tokenizer.pad_token_id = tokenizer.eos_token_id
+ model_inputs = tokenizer("I will be", return_tensors="pt").to(torch_device)
+ input_len = 5
+ batch_size = 200
+
+ # generation should work with both input types: WatermarkingConfig or Dict, so let's check it here :)
+ watermark_config = SynthIDTextWatermarkingConfig(keys=[10, 20], ngram_len=5, debug_mode=True)
+ logits_processor = watermark_config.construct_processor(model.config.vocab_size, torch_device)
+ mean_g_values_repeats = []
+ for _ in range(40):
+ input_ids = torch.zeros(
+ (batch_size, input_len),
+ dtype=torch.int64,
+ device=torch_device,
+ )
+ model_inputs = {
+ "input_ids": input_ids,
+ "attention_mask": torch.ones_like(input_ids, device=torch_device),
+ }
+ output = model.generate(
+ **model_inputs, watermarking_config=watermark_config, do_sample=True, max_length=500, top_k=1000
+ )
+ g_values = logits_processor.compute_g_values(input_ids=output[:, input_len:])
+ context_repetition_mask = logits_processor.compute_context_repetition_mask(
+ input_ids=output[:, input_len:],
+ ).unsqueeze(dim=2)
+
+ mean_g_values = torch.masked.mean(
+ g_values,
+ mask=context_repetition_mask,
+ dim=0,
+ keepdim=True,
+ dtype=torch.float64,
+ )
+ mean_g_values_repeats.append(mean_g_values)
+
+ mean_g_values = torch.concat(mean_g_values_repeats, dim=0).mean(dim=0)
+ expected_mean_g_value = logits_processor.expected_mean_g_value(
+ vocab_size=model.config.vocab_size,
+ )
+ atol = 0.03
+ is_close = torch.isclose(
+ mean_g_values,
+ torch.tensor(expected_mean_g_value, dtype=torch.float64),
+ atol=atol,
+ rtol=0,
+ )
+ self.assertTrue(torch.all(is_close))
+
+ @slow
+ def test_beam_search_example_integration(self):
+ # exactly the example provided in the docstrings of beam search, which previously
+ # failed after directly copying from it. Refer to PR #15555
+ tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-base")
+ model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-base")
+
+ encoder_input_str = "translate English to German: How old are you?"
+ encoder_input_ids = tokenizer(encoder_input_str, return_tensors="pt").input_ids
+
+ # lets run beam search using 3 beams
+ num_beams = 3
+ # define decoder start token ids
+ input_ids = torch.ones((1, 1), device=model.device, dtype=torch.long)
+ input_ids = input_ids * model.config.decoder_start_token_id
+
+ # add encoder_outputs to model keyword arguments
+ model_kwargs = {"encoder_outputs": model.get_encoder()(encoder_input_ids, return_dict=True)}
+
+ outputs = model.generate(
+ input_ids, num_beams=num_beams, min_length=5, eos_token_id=model.config.eos_token_id, **model_kwargs
+ )
+ outputs = tokenizer.batch_decode(outputs, skip_special_tokens=True)
+
+ self.assertListEqual(outputs, ["Wie alt bist du?"])
+
+ @slow
+ def test_constrained_beam_search(self):
+ model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2").to(torch_device)
+ tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
+
+ force_tokens = tokenizer("scared", add_prefix_space=True, add_special_tokens=False).input_ids
+ force_tokens_2 = tokenizer("big weapons", add_prefix_space=True, add_special_tokens=False).input_ids
+
+ constraints = [
+ PhrasalConstraint(force_tokens),
+ PhrasalConstraint(force_tokens_2),
+ ]
+
+ starting_text = ["The soldiers were not prepared and"]
+
+ input_ids = tokenizer(starting_text, return_tensors="pt").input_ids.to(torch_device)
+
+ outputs = model.generate(
+ input_ids,
+ constraints=constraints,
+ num_beams=10,
+ num_return_sequences=1,
+ no_repeat_ngram_size=1,
+ max_length=30,
+ remove_invalid_values=True,
+ )
+
+ generated_text = tokenizer.batch_decode(outputs, skip_special_tokens=True)
+
+ self.assertListEqual(
+ generated_text,
+ [
+ "The soldiers were not prepared and didn't know what to do. They had no idea how they would react if"
+ " the enemy attacked them, big weapons scared"
+ ],
+ )
+
+ @slow
+ def test_constrained_beam_search_mixed(self):
+ model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2").to(torch_device)
+ tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
+
+ force_phrase = tokenizer("scared", add_prefix_space=True, add_special_tokens=False).input_ids
+ flexible_phrases = tokenizer(
+ ["scream", "screams", "screaming", "screamed"], add_prefix_space=True, add_special_tokens=False
+ ).input_ids
+
+ constraints = [
+ PhrasalConstraint(force_phrase),
+ DisjunctiveConstraint(flexible_phrases),
+ ]
+
+ starting_text = ["The soldiers", "The child"]
+
+ input_ids = tokenizer(starting_text, return_tensors="pt").input_ids.to(torch_device)
+
+ outputs = model.generate(
+ input_ids,
+ constraints=constraints,
+ num_beams=10,
+ num_return_sequences=1,
+ no_repeat_ngram_size=1,
+ # max_length=20,
+ remove_invalid_values=True,
+ )
+
+ generated_text = tokenizer.batch_decode(outputs, skip_special_tokens=True)
+
+ self.assertListEqual(
+ generated_text,
+ [
+ "The soldiers, who had been stationed at the base for more than a year before being evacuated"
+ " screaming scared",
+ "The child was taken to a local hospital where he died.\n 'I don't think screaming scared",
+ ],
+ )
+
+ @slow
+ def test_constrained_beam_search_mixed_mixin(self):
+ model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2").to(torch_device)
+ tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
+
+ force_word = "scared"
+ force_flexible = ["scream", "screams", "screaming", "screamed"]
+
+ force_words_ids = [
+ tokenizer([force_word], add_prefix_space=True, add_special_tokens=False).input_ids,
+ tokenizer(force_flexible, add_prefix_space=True, add_special_tokens=False).input_ids,
+ ]
+
+ starting_text = ["The soldiers", "The child"]
+
+ input_ids = tokenizer(starting_text, return_tensors="pt").input_ids.to(torch_device)
+
+ outputs = model.generate(
+ input_ids,
+ force_words_ids=force_words_ids,
+ num_beams=10,
+ num_return_sequences=1,
+ no_repeat_ngram_size=1,
+ remove_invalid_values=True,
+ )
+
+ generated_text = tokenizer.batch_decode(outputs, skip_special_tokens=True)
+
+ self.assertListEqual(
+ generated_text,
+ [
+ "The soldiers, who had been stationed at the base for more than a year before being evacuated"
+ " screaming scared",
+ "The child was taken to a local hospital where he died.\n 'I don't think screaming scared",
+ ],
+ )
+
+ @slow
+ def test_cfg_mixin(self):
+ model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2").to(torch_device)
+ tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
+
+ input = tokenizer(["The dragon flew over Paris,"], return_tensors="pt", return_attention_mask=True)
+ input["input_ids"] = input["input_ids"].to(torch_device)
+ input["attention_mask"] = input["attention_mask"].to(torch_device)
+
+ outputs = model.generate(**input, max_new_tokens=32, guidance_scale=1.5)
+ generated_text = tokenizer.batch_decode(outputs, skip_special_tokens=True)
+
+ self.assertListEqual(
+ generated_text,
+ [
+ "The dragon flew over Paris, landing in the Rue de la Bastille. The crowd was so excited "
+ 'that they had to leave the city.\n\n"We\'re going to Paris!"\n'
+ ],
+ )
+
+ neg = tokenizer(["France,"], return_tensors="pt", return_attention_mask=True)
+ neg["input_ids"] = neg["input_ids"].to(torch_device)
+ neg["attention_mask"] = neg["attention_mask"].to(torch_device)
+ outputs = model.generate(
+ **input,
+ max_new_tokens=32,
+ guidance_scale=1.5,
+ negative_prompt_ids=neg["input_ids"],
+ negative_prompt_attention_mask=neg["attention_mask"],
+ )
+ generated_text = tokenizer.batch_decode(outputs, skip_special_tokens=True)
+
+ self.assertListEqual(
+ generated_text,
+ [
+ 'The dragon flew over Paris, landing on the pavement.\n\n"Paris!"\n\n"Paris!"\n\n"'
+ 'Paris!"\n\n"Paris!"\n\n"Paris!"\n\n'
+ ],
+ )
+
+ @slow
+ def test_constrained_beam_search_example_translation_mixin(self):
+ tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-base")
+ model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-base")
+
+ encoder_input_str = "translate English to German: How old are you?"
+ force_words = ["sind"]
+
+ input_ids = tokenizer(encoder_input_str, return_tensors="pt").input_ids
+ force_words_ids = tokenizer(force_words, add_special_tokens=False).input_ids
+
+ outputs = model.generate(
+ input_ids,
+ force_words_ids=force_words_ids,
+ num_beams=10,
+ num_return_sequences=1,
+ no_repeat_ngram_size=1,
+ remove_invalid_values=True,
+ )
+
+ outputs = tokenizer.batch_decode(outputs, skip_special_tokens=True)
+
+ self.assertListEqual(outputs, ["Wie alt sind Sie?"])
+
+ @slow
+ def test_constrained_beam_search_example_integration(self):
+ tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-base")
+ model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-base")
+
+ encoder_input_str = "translate English to German: How old are you?"
+ encoder_input_ids = tokenizer(encoder_input_str, return_tensors="pt").input_ids
+
+ # lets run beam search using 5 beams
+ num_beams = 5
+ # define decoder start token ids
+ input_ids = torch.ones((1, 1), device=model.device, dtype=torch.long)
+ input_ids = input_ids * model.config.decoder_start_token_id
+
+ # add encoder_outputs to model keyword arguments
+ model_kwargs = {"encoder_outputs": model.get_encoder()(encoder_input_ids, return_dict=True)}
+
+ constraint_str = "sind"
+ constraint_token_ids = tokenizer.encode(constraint_str)[:-1] # remove eos token
+
+ outputs = model.generate(
+ input_ids,
+ num_beams=num_beams,
+ force_words_ids=[constraint_token_ids],
+ min_length=5,
+ eos_token_id=model.config.eos_token_id,
+ **model_kwargs,
+ )
+ outputs = tokenizer.batch_decode(outputs, skip_special_tokens=True)
+
+ self.assertListEqual(outputs, ["Wie alt sind Sie?"])
+
+ @slow
+ def test_per_row_stopping_criteria(self):
+ text = [
+ "They completed the challenging puzzle, revealing the hidden",
+ "Today a dragon flew over France",
+ "The aroma of freshly baked pizza filled the kitchen",
+ ]
+ stop_strings = ["secrets"]
+
+ model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2").to(torch_device)
+ tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
+ tokenizer.padding_side = "left"
+ tokenizer.pad_token_id = tokenizer.eos_token_id
+ input_ids = tokenizer(text, return_tensors="pt", padding="longest", add_special_tokens=False).input_ids.to(
+ torch_device
+ )
+
+ # normal generation with one stopping criteria
+ out = model.generate(input_ids, max_length=15)
+ out_text = tokenizer.batch_decode(out)
+ expected_out = [
+ "They completed the challenging puzzle, revealing the hidden secrets of the world.\n",
+ "<|endoftext|><|endoftext|><|endoftext|>Today a dragon flew over France and the French government was forced",
+ "The aroma of freshly baked pizza filled the kitchen with a sense of freshness",
+ ]
+ self.assertListEqual(out_text, expected_out)
+
+ # generation should stop at "secrets" for first batch only, filling the rest with eos tokens
+ out = model.generate(input_ids, max_length=15, stop_strings=stop_strings, tokenizer=tokenizer)
+ out_text = tokenizer.batch_decode(out)
+ expected_out = [
+ "They completed the challenging puzzle, revealing the hidden secrets<|endoftext|><|endoftext|><|endoftext|><|endoftext|><|endoftext|>",
+ "<|endoftext|><|endoftext|><|endoftext|>Today a dragon flew over France and the French government was forced",
+ "The aroma of freshly baked pizza filled the kitchen with a sense of freshness",
+ ]
+ self.assertListEqual(out_text, expected_out)
+
+ def test_constrained_beam_search_mixin_type_checks(self):
+ tokenizer = AutoTokenizer.from_pretrained("patrickvonplaten/t5-tiny-random")
+ model = AutoModelForSeq2SeqLM.from_pretrained("patrickvonplaten/t5-tiny-random")
+
+ encoder_input_str = "translate English to German: How old are you?"
+ input_ids = tokenizer(encoder_input_str, return_tensors="pt").input_ids
+
+ with self.assertRaises(ValueError):
+ force_words = ["sind"]
+ force_words_ids = tokenizer(force_words, return_tensors="pt").input_ids
+ model.generate(
+ input_ids,
+ force_words_ids=force_words_ids,
+ num_beams=10,
+ num_return_sequences=1,
+ no_repeat_ngram_size=1,
+ remove_invalid_values=True,
+ )
+
+ with self.assertRaises(ValueError):
+ force_words = ["sind"]
+ force_words_ids = [tokenizer(force_words, return_tensors="pt").input_ids]
+ model.generate(
+ input_ids,
+ force_words_ids=force_words_ids,
+ num_beams=10,
+ num_return_sequences=1,
+ no_repeat_ngram_size=1,
+ remove_invalid_values=True,
+ )
+
+ with self.assertRaises(ValueError):
+ model.generate(input_ids, force_words_ids=[])
+
+ with self.assertRaises(ValueError):
+ model.generate(input_ids, force_words_ids=[[-1]])
+
+ with self.assertRaises(ValueError):
+ model.generate(input_ids, force_words_ids=[[[-1]]])
+
+ def test_batched_decoder_start_id(self):
+ articles = [
+ "Justin Timberlake and Jessica Biel, welcome to parenthood.",
+ "Michael Phelps is arguably the most decorated Olympian of all time.",
+ ]
+ bart_tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bart")
+ bart_model = BartForConditionalGeneration.from_pretrained("hf-internal-testing/tiny-random-bart").to(
+ torch_device
+ )
+ input_ids = bart_tokenizer(articles, return_tensors="pt", padding=True).input_ids.to(torch_device)
+ decoder_start_token_id = bart_model.generation_config.decoder_start_token_id
+ decoder_start_token_id_batch = [decoder_start_token_id] * input_ids.shape[0]
+
+ outputs = bart_model.generate(input_ids, decoder_start_token_id=decoder_start_token_id)
+
+ outputs_batched_ids = bart_model.generate(input_ids, decoder_start_token_id=decoder_start_token_id_batch)
+
+ self.assertListEqual(outputs.tolist(), outputs_batched_ids.tolist())
+
+ def test_decoder_start_id_from_config(self):
+ # Refer to: (#30899)
+ articles = [
+ "Justin Timberlake and Jessica Biel, welcome to parenthood.",
+ "Michael Phelps is arguably the most decorated Olympian of all time.",
+ ]
+ bart_tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bart")
+ bart_model = BartForConditionalGeneration.from_pretrained("hf-internal-testing/tiny-random-bart").to(
+ torch_device
+ )
+ input_ids = bart_tokenizer(articles, return_tensors="pt", padding=True).input_ids.to(torch_device)
+ decoder_start_token_id = bart_model.generation_config.decoder_start_token_id
+
+ # we should be able to take `decoder_start_token_id` from model's generation config if user passes a `GenerationConfig` type
+ outputs = bart_model.generate(input_ids, generation_config=GenerationConfig(do_sample=False))
+
+ # If the generatoin config has no `decoder_start_token_id` or `bos_token_id`, we will raise an error unless user passes it in config
+ bart_model.generation_config.decoder_start_token_id = None
+ bart_model.generation_config.bos_token_id = None
+ outputs_with_user_id = bart_model.generate(
+ input_ids,
+ generation_config=GenerationConfig(do_sample=False, decoder_start_token_id=decoder_start_token_id),
+ )
+
+ self.assertListEqual(outputs.tolist(), outputs_with_user_id.tolist())
+
+ with self.assertRaises(ValueError):
+ outputs = bart_model.generate(input_ids, generation_config=GenerationConfig(do_sample=False))
+
+ def test_contrastive_search_batched(self):
+ # Tests that contrastive search works with batched inputs (i.e. has the same output as for non-batched inputs)
+ articles = ["Foo", "Bar Baz"]
+ tokenizer = BartTokenizer.from_pretrained("hf-internal-testing/tiny-random-bart")
+ model = BartForConditionalGeneration.from_pretrained("hf-internal-testing/tiny-random-bart").to(torch_device)
+
+ model.config.eos_token_id = None
+ input_ids_batched = tokenizer(articles, padding=True, return_tensors="pt").input_ids.to(torch_device)
+ input_ids = tokenizer(articles[1], return_tensors="pt").input_ids.to(torch_device)
+
+ output_sequences_batched = model.generate(
+ input_ids=input_ids_batched, penalty_alpha=0.6, top_k=4, return_dict_in_generate=True, output_scores=True
+ )
+ output_sequences = model.generate(
+ input_ids=input_ids, penalty_alpha=0.6, top_k=4, return_dict_in_generate=True, output_scores=True
+ )
+
+ batched_out = tokenizer.decode(output_sequences_batched.sequences[1], skip_special_tokens=True)
+ out = tokenizer.decode(output_sequences.sequences[0], skip_special_tokens=True)
+ self.assertEqual(batched_out, out)
+
+ # output_sequences_batched.scores[0][1] -> 1st set of logits, 2nd sequence
+ max_score_diff = (output_sequences_batched.scores[0][1] - output_sequences.scores[0][0]).abs().max()
+ self.assertTrue(max_score_diff < 1e-5)
+
+ def test_logits_processor_not_inplace(self):
+ article = "Today a dragon flew over Paris."
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ input_ids = tokenizer(article, return_tensors="pt").input_ids.to(torch_device)
+
+ out = model.generate(input_ids, output_logits=True, output_scores=True, return_dict_in_generate=True)
+ out_with_temp = model.generate(
+ input_ids,
+ temperature=0.5,
+ do_sample=True,
+ output_logits=True,
+ output_scores=True,
+ return_dict_in_generate=True,
+ )
+
+ # if no logits processor is used, scores == logits. Otherwise, the processor has to modify the scores
+ self.assertListEqual(out.logits[-1].tolist(), out.scores[-1].tolist())
+ self.assertNotEqual(out_with_temp.logits[-1].tolist(), out_with_temp.scores[-1].tolist())
+
+ def test_eos_token_id_int_and_list_top_k_top_sampling(self):
+ # Has TF equivalent: this test relies on random sampling
+ generation_kwargs = {
+ "do_sample": True,
+ "num_beams": 1,
+ "top_p": 0.7,
+ "top_k": 10,
+ "temperature": 0.7,
+ }
+ expectation = 20
+
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ text = """Hello, my dog is cute and"""
+ tokens = tokenizer(text, return_tensors="pt").to(torch_device)
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+
+ # Only some seeds will work both on CPU/GPU for a fixed `expectation` value.
+ # The selected seed is not guaranteed to work on all torch versions.
+ torch.manual_seed(1)
+ eos_token_id = 846
+ generated_tokens = model.generate(**tokens, eos_token_id=eos_token_id, **generation_kwargs)
+ self.assertTrue(expectation == len(generated_tokens[0]))
+
+ torch.manual_seed(1)
+ eos_token_id = [846, 198]
+ generated_tokens = model.generate(**tokens, eos_token_id=eos_token_id, **generation_kwargs)
+ self.assertTrue(expectation == len(generated_tokens[0]))
+
+ def test_model_kwarg_encoder_signature_filtering(self):
+ # Has TF equivalent: ample use of framework-specific code
+ bart_tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bart")
+ article = """Hugging Face is a technology company based in New York and Paris."""
+ input_ids = bart_tokenizer(article, return_tensors="pt").input_ids.to(torch_device)
+ bart_model = BartForConditionalGeneration.from_pretrained("hf-internal-testing/tiny-random-bart").to(
+ torch_device
+ )
+ output = bart_model.generate(input_ids).cpu().numpy()
+
+ # Let's create a fake model that has a different signature. In particular, this fake model accepts "foo" as an
+ # argument. Because "foo" is not in the encoder signature and doesn't start with "decoder_", it will be part of
+ # the encoder kwargs prior to signature filtering, which would lead to an exception. But filtering kicks in and
+ # saves the day.
+ class FakeBart(BartForConditionalGeneration):
+ def forward(self, input_ids, foo=None, **kwargs):
+ return super().forward(input_ids, **kwargs)
+
+ bart_model = FakeBart.from_pretrained("hf-internal-testing/tiny-random-bart").to(torch_device)
+ fake_output = bart_model.generate(input_ids, foo="bar").cpu().numpy()
+ self.assertTrue(np.array_equal(output, fake_output))
+
+ # Encoder signature filtering only kicks in if it doesn't accept wildcard kwargs. The following test will fail
+ # because it doesn't do signature filtering.
+ class FakeEncoder(bart_model.model.encoder.__class__):
+ def forward(self, input_ids, **kwargs):
+ return super().forward(input_ids, **kwargs)
+
+ fake_encoder = FakeEncoder(bart_model.config, bart_model.model.shared).to(torch_device)
+ bart_model.model.encoder = fake_encoder
+
+ # Normal generation still works (the output will be different because the encoder weights are different)
+ fake_output = bart_model.generate(input_ids).cpu().numpy()
+ with self.assertRaises(TypeError):
+ # FakeEncoder.forward() accepts **kwargs -> no filtering -> type error due to unexpected input "foo"
+ bart_model.generate(input_ids, foo="bar")
+
+ def test_default_max_length_warning(self):
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ model.generation_config.pad_token_id = tokenizer.eos_token_id
+
+ text = "Hello world"
+ tokenized_inputs = tokenizer([text], return_tensors="pt")
+ input_ids = tokenized_inputs.input_ids.to(torch_device)
+
+ # Default generation config value of 20 -> emits warning
+ with self.assertWarns(UserWarning):
+ model.generate(input_ids)
+
+ # Explicitly setting max_length to 20 -> no warning
+ with warnings.catch_warnings(record=True) as warning_list:
+ model.generate(input_ids, max_length=20)
+ self.assertEqual(len(warning_list), 0)
+
+ # Generation config max_length != 20 -> no warning
+ with warnings.catch_warnings(record=True) as warning_list:
+ # generation_config is modified -> legacy mode is disabled = generation_config takes precedence
+ model.generation_config.max_length = 10
+ model.generate(input_ids)
+ self.assertEqual(len(warning_list), 0)
+
+ def test_length_warning_assisted_generation(self):
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ assistant = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ model.generation_config.pad_token_id = tokenizer.eos_token_id
+ assistant.generation_config.pad_token_id = tokenizer.eos_token_id
+
+ text = "Hello world"
+ tokenized_inputs = tokenizer([text], return_tensors="pt")
+ input_ids = tokenized_inputs.input_ids.to(torch_device)
+
+ # This should not raise any warning that min length is not feasible in candidate generation
+ with warnings.catch_warnings(record=True) as warning_list:
+ model.generate(
+ input_ids,
+ assistant_model=assistant,
+ min_new_tokens=10,
+ max_length=20,
+ )
+ self.assertEqual(len(warning_list), 0)
+
+ def test_default_assisted_generation(self):
+ # Initialize the GenerationConfig object
+ config = GenerationConfig()
+
+ # Check the default values
+ self.assertEqual(config.num_assistant_tokens, 20)
+ self.assertEqual(config.num_assistant_tokens_schedule, "constant")
+ self.assertEqual(config.assistant_confidence_threshold, 0.4)
+ self.assertEqual(config.is_assistant, False)
+
+ def test_generated_length_assisted_generation(self):
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ assistant = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ model.generation_config.pad_token_id = tokenizer.eos_token_id
+ assistant.generation_config.pad_token_id = tokenizer.eos_token_id
+
+ text = "Hello world"
+ tokenized_inputs = tokenizer([text], return_tensors="pt")
+ input_ids = tokenized_inputs.input_ids.to(torch_device)
+ input_length = input_ids.shape[-1]
+
+ out = model.generate(
+ input_ids,
+ assistant_model=assistant,
+ min_new_tokens=10,
+ max_new_tokens=20,
+ )
+ self.assertTrue((10 + input_length) <= out.shape[-1] <= (20 + input_length))
+
+ out = model.generate(
+ input_ids,
+ assistant_model=assistant,
+ min_new_tokens=10,
+ )
+ self.assertTrue((input_length + 10) <= out.shape[-1])
+
+ out = model.generate(
+ input_ids,
+ assistant_model=assistant,
+ max_new_tokens=7,
+ )
+ self.assertTrue(out.shape[-1] <= (input_length + 7))
+
+ def test_model_kwarg_assisted_decoding_decoder_only(self):
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ model.generation_config.pad_token_id = tokenizer.eos_token_id
+
+ text = "Hello world"
+ tokenized_inputs = tokenizer([text], return_tensors="pt")
+ input_ids = tokenized_inputs.input_ids.to(torch_device)
+
+ # Traditional way of generating text
+ outputs_normal = model.generate(input_ids)
+ self.assertEqual(outputs_normal.shape, (1, 20))
+
+ # Should be different with token_type_ids
+ outputs_tti = model.generate(
+ input_ids,
+ token_type_ids=torch.zeros(input_ids.shape, dtype=torch.long).to(torch_device),
+ )
+ with self.assertRaises(AssertionError):
+ self.assertListEqual(outputs_tti.tolist(), outputs_normal.tolist())
+
+ # Assistant model
+ assistant = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+ assistant.config.pad_token_id = tokenizer.eos_token_id
+
+ # If assisted generation passes model_kwargs correctly, should be same as previous
+ outputs_assisted = model.generate(
+ input_ids,
+ token_type_ids=torch.zeros(input_ids.shape, dtype=torch.long).to(torch_device),
+ assistant_model=assistant,
+ )
+ self.assertListEqual(outputs_assisted.tolist(), outputs_tti.tolist())
+
+ def test_assisted_decoding_num_assistant_tokens_heuristic_schedule(self):
+ # This test ensures that the assisted generation num_assistant_tokens 'heuristic' schedule works properly.
+
+ prompt = "Alice and Bob"
+ checkpoint = "EleutherAI/pythia-160m-deduped"
+ tokenizer = AutoTokenizer.from_pretrained(checkpoint)
+ inputs = tokenizer(prompt, return_tensors="pt")
+
+ model = AutoModelForCausalLM.from_pretrained(checkpoint)
+
+ assistant_model = model
+ assistant_model.generation_config.num_assistant_tokens = 5
+ assistant_model.generation_config.num_assistant_tokens_schedule = "heuristic"
+ generation_kwargs = {
+ "eos_token_id": -1,
+ "max_new_tokens": 5,
+ "do_sample": False,
+ "assistant_model": assistant_model,
+ }
+ model.generate(**inputs, **generation_kwargs)
+ # update_candidate_strategy is called only once and therefore, assistant_model.generation_config.num_assistant_tokens should be either 4 or 7
+ self.assertTrue(assistant_model.generation_config.num_assistant_tokens in (4, 7))
+
+ def test_assisted_decoding_num_assistant_tokens_heuristic_transient_schedule(self):
+ # This test ensures that the assisted generation num_assistant_tokens 'heuristic' schedule works properly.
+
+ prompt = "Alice and Bob"
+ checkpoint = "EleutherAI/pythia-160m-deduped"
+ tokenizer = AutoTokenizer.from_pretrained(checkpoint)
+ inputs = tokenizer(prompt, return_tensors="pt")
+
+ model = AutoModelForCausalLM.from_pretrained(checkpoint)
+
+ assistant_model = model
+ assistant_model.generation_config.num_assistant_tokens = 5
+ assistant_model.generation_config.num_assistant_tokens_schedule = "heuristic_transient"
+ generation_kwargs = {
+ "eos_token_id": -1,
+ "max_new_tokens": 5,
+ "do_sample": False,
+ "assistant_model": assistant_model,
+ }
+ model.generate(**inputs, **generation_kwargs)
+ # update_candidate_strategy is called once but assistant_model.generation_config.num_assistant_tokens should stay 5
+ self.assertEqual(assistant_model.generation_config.num_assistant_tokens, 5)
+
+ @slow
+ def test_validate_assistant(self):
+ # Generate a random sample:
+ inputs = np.random.rand(160000)
+
+ # Load a main encoder-decoder model:
+ model_id = "openai/whisper-large-v2"
+ processor = AutoProcessor.from_pretrained(model_id)
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
+ model_id,
+ low_cpu_mem_usage=True,
+ use_safetensors=True,
+ )
+ model.to(torch_device)
+
+ # process the input:
+ features = processor(inputs, return_tensors="pt").to(torch_device)
+
+ # Load an encoder-decoder assistant with same encoder as the main model:
+ assistant_distil_model_id = "distil-whisper/distil-large-v2"
+ assistant_seq_to_seq = AutoModelForSpeechSeq2Seq.from_pretrained(
+ assistant_distil_model_id,
+ use_safetensors=True,
+ ).to(torch_device)
+ self.assertTrue(model.generate(**features, assistant_model=assistant_seq_to_seq).sum())
+
+ # Load its decoder only version:
+ assistant_causal_lm = AutoModelForCausalLM.from_pretrained(
+ assistant_distil_model_id,
+ low_cpu_mem_usage=True,
+ use_safetensors=True,
+ ).to(torch_device)
+ self.assertTrue(model.generate(**features, assistant_model=assistant_causal_lm).sum())
+
+ # Load an encoder-decoder assistant with a different encoder than the main model:
+ assistant_distil_model_id = "openai/whisper-tiny"
+ assistant_seq_to_seq = AutoModelForSpeechSeq2Seq.from_pretrained(
+ assistant_distil_model_id,
+ use_safetensors=True,
+ ).to(torch_device)
+ self.assertTrue(model.generate(**features, assistant_model=assistant_seq_to_seq).sum())
+
+ # Load its decoder only version:
+ assistant_causal_lm = AutoModelForCausalLM.from_pretrained(
+ assistant_distil_model_id,
+ low_cpu_mem_usage=True,
+ use_safetensors=True,
+ ).to(torch_device)
+ # It will raise an error as the encoder of the main and assistant model are not compatible:
+ with self.assertRaises(ValueError):
+ model.generate(**features, assistant_model=assistant_causal_lm)
+
+ # Load an encoder-decoder model with a different tokenizer than the main model:
+ assistant_distil_model_id = "hf-internal-testing/tiny-random-SeamlessM4Tv2ForSpeechToText"
+ assistant_seq_to_seq = AutoModelForSpeechSeq2Seq.from_pretrained(
+ assistant_distil_model_id,
+ ).to(torch_device)
+ # This should raise an error as the main and assistant model don't use the same tokenizer:
+ with self.assertRaises(ValueError):
+ model.generate(**features, assistant_model=assistant_seq_to_seq)
+
+ def test_compare_unprocessed_logit_scores(self):
+ # Get unprocessed logit scores back from model generate function.
+ # Assert that unprocessed logits from generate() are same as those from modal eval()
+
+ # tell model to generate text and return unprocessed/unwarped logit scores
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ text = "generate yes or no: "
+ input_ids = tokenizer([text], return_tensors="pt").input_ids.to(torch_device)
+
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+
+ with torch.no_grad():
+ # Get logits for the next token from fwd pass
+ logits_fwd = model(input_ids).logits[:, -1, :][0]
+
+ # Get logits for the next token from generate function
+ outputs = model.generate(
+ input_ids=input_ids,
+ return_dict_in_generate=True,
+ output_logits=True,
+ max_new_tokens=1,
+ do_sample=True,
+ )
+ logits_gen = outputs.logits[0][0]
+
+ # assert that unprocessed logits from generate() are same as those from modal eval()
+ self.assertListEqual(logits_fwd.tolist(), logits_gen.tolist())
+
+ def test_return_unprocessed_logit_scores(self):
+ # tell model to generate text and return unprocessed/unwarped logit scores
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ text = "generate yes or no: "
+ input_ids = tokenizer([text], return_tensors="pt").input_ids.to(torch_device)
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2").to(torch_device)
+
+ outputs = model.generate(
+ input_ids=input_ids, return_dict_in_generate=True, output_logits=True, max_new_tokens=3
+ )
+
+ # perform dummy check if unpreprocessed logits make sense.
+ # do preselection on high probabilities; find scores of y and n tokens
+ probs_all = torch.nn.functional.softmax(outputs.logits[2][0], dim=-1)
+ indices = torch.argwhere(probs_all > 0.001)
+ indices = indices[:, -1]
+ tokens_max = tokenizer.batch_decode(indices, skip_special_tokens=True)
+ probs_max = probs_all[probs_all > 0.001]
+
+ self.assertTrue(len(indices) >= 2)
+ next_token_dict = {str(t): p for t, p in zip(tokens_max, probs_max)}
+ self.assertTrue("n" in next_token_dict)
+ self.assertTrue("y" in next_token_dict)
+ y_prob = next_token_dict["y"]
+ n_prob = next_token_dict["n"]
+
+ self.assertTrue(y_prob > 0.001 and n_prob > 0.001)
+ self.assertTrue(y_prob <= 1.0 and n_prob <= 1.0)
+
+ @slow
+ @require_torch_multi_gpu
+ def test_assisted_decoding_in_different_gpu(self):
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-MistralForCausalLM").to("cuda:0")
+ assistant = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-MistralForCausalLM").to(
+ "cuda:1"
+ )
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-MistralForCausalLM")
+ model.config.pad_token_id = tokenizer.eos_token_id
+ assistant.config.pad_token_id = tokenizer.eos_token_id
+
+ text = "Hello world"
+ tokenized_inputs = tokenizer([text], return_tensors="pt")
+ input_ids = tokenized_inputs.input_ids.to(torch_device)
+ input_length = input_ids.shape[-1]
+
+ out = model.generate(
+ input_ids,
+ assistant_model=assistant,
+ max_new_tokens=20,
+ )
+ self.assertTrue(input_length <= out.shape[-1] <= input_length + 20)
+
+ @slow
+ @require_torch_accelerator
+ def test_assisted_decoding_model_in_gpu_assistant_in_cpu(self):
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-MistralForCausalLM").to(
+ torch_device
+ )
+ assistant = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-MistralForCausalLM").to(
+ "cpu"
+ )
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-MistralForCausalLM")
+ model.config.pad_token_id = tokenizer.eos_token_id
+ assistant.config.pad_token_id = tokenizer.eos_token_id
+
+ text = "Hello world"
+ tokenized_inputs = tokenizer([text], return_tensors="pt")
+ input_ids = tokenized_inputs.input_ids.to(torch_device)
+ input_length = input_ids.shape[-1]
+
+ out = model.generate(
+ input_ids,
+ assistant_model=assistant,
+ max_new_tokens=20,
+ )
+ self.assertTrue(input_length <= out.shape[-1] <= input_length + 20)
+
+ def test_special_tokens_fall_back_to_model_default(self):
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-MistralForCausalLM").to(
+ torch_device
+ )
+ test_bos_id = 50
+
+ # Sanity-check: the model has a BOS token set, and the first generated token is a BOS token
+ gen_output = model.generate()
+ self.assertTrue(model.generation_config.bos_token_id is not None)
+ self.assertTrue(model.generation_config.bos_token_id == gen_output[0, 0])
+
+ # If we pass a generation config **with** a BOS token, `generate` will use it
+ generation_config = GenerationConfig(bos_token_id=test_bos_id)
+ gen_output = model.generate(generation_config=generation_config)
+ self.assertFalse(model.generation_config.bos_token_id == gen_output[0, 0])
+ self.assertTrue(generation_config.bos_token_id == gen_output[0, 0])
+ self.assertTrue(test_bos_id == gen_output[0, 0])
+
+ # If we pass a generation config **without** a BOS token, `generate` will fetch the BOS token from
+ # `model.generation_config`
+ generation_config = GenerationConfig(bos_token_id=None)
+ gen_output = model.generate(generation_config=generation_config)
+ self.assertTrue(model.generation_config.bos_token_id == gen_output[0, 0])
+ self.assertFalse(test_bos_id == gen_output[0, 0])
+ self.assertTrue(generation_config.bos_token_id is None)
+
+ # Changing `model.generation_config` will affect fallback behavior
+ model.generation_config.bos_token_id = test_bos_id
+ gen_output = model.generate(generation_config=generation_config)
+ self.assertTrue(model.generation_config.bos_token_id == gen_output[0, 0])
+ self.assertTrue(test_bos_id == gen_output[0, 0])
+ self.assertTrue(generation_config.bos_token_id is None)
+
+ def test_speculative_decoding_equals_regular_decoding(self):
+ draft_name = "double7/vicuna-68m"
+ target_name = "Qwen/Qwen2-0.5B-Instruct"
+
+ draft_model = AutoModelForCausalLM.from_pretrained(draft_name)
+ target_model = AutoModelForCausalLM.from_pretrained(target_name)
+
+ assistant_tokenizer = AutoTokenizer.from_pretrained(draft_name)
+ target_tokenizer = AutoTokenizer.from_pretrained(target_name)
+
+ prompt_size = torch.randint(low=20, high=100, size=(1,))
+ max_new_tokens = torch.randint(low=10, high=50, size=(1,))
+ input_ids = (torch.rand(1, prompt_size[0]) * 100).to(int) + 50
+
+ max_new_tokens_item = max_new_tokens[0].item()
+ expected_out = target_model.generate(input_ids, do_sample=False, max_new_tokens=max_new_tokens_item)
+ predicted_out = target_model.generate(
+ input_ids,
+ do_sample=False,
+ max_new_tokens=max_new_tokens_item,
+ assistant_model=draft_model,
+ tokenizer=target_tokenizer,
+ assistant_tokenizer=assistant_tokenizer,
+ )
+
+ self.assertEqual(expected_out.shape, predicted_out.shape)
+ self.assertTrue((expected_out == predicted_out).all().item())
+
+ @pytest.mark.generate
+ @require_torch_multi_gpu
+ def test_generate_with_static_cache_multi_gpu(self):
+ """
+ Tests if the static cache has been set correctly and if generate works correctly when we are using multi-gpus.
+ """
+ # need to split manually as auto doesn't work well with unbalanced model
+ device_map = {"model.embed_tokens": 0, "model.layers.0": 0, "model.layers.1": 1, "model.norm": 1, "lm_head": 0}
+ model = AutoModelForCausalLM.from_pretrained(
+ "hf-internal-testing/tiny-random-MistralForCausalLM", device_map=device_map
+ )
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-MistralForCausalLM")
+
+ text = "Hello world"
+ tokenized_inputs = tokenizer([text], return_tensors="pt")
+ input_ids = tokenized_inputs.input_ids.to(torch_device)
+
+ generation_kwargs = {
+ "max_new_tokens": 20,
+ "cache_implementation": "static",
+ "return_dict_in_generate": True, # Required to return `past_key_values`
+ }
+
+ results = model.generate(input_ids, **generation_kwargs)
+ self.assertTrue(isinstance(results.past_key_values, StaticCache))
+
+ # check device of each layer
+ key_cache_0 = results.past_key_values.key_cache[0]
+ value_cache_0 = results.past_key_values.value_cache[0]
+ self.assertTrue(key_cache_0.device == value_cache_0.device == torch.device(0))
+
+ key_cache_1 = results.past_key_values.key_cache[1]
+ value_cache_1 = results.past_key_values.value_cache[1]
+ self.assertTrue(key_cache_1.device == value_cache_1.device == torch.device(1))
+
+ @pytest.mark.generate
+ @require_torch_multi_gpu
+ def test_init_static_cache_multi_gpu(self):
+ """
+ Tests if the static cache has been set correctly when we initialize it manually in a multi-gpu setup.
+ """
+ # need to split manually as auto doesn't work well with unbalanced model
+ device_map = {"model.embed_tokens": 0, "model.layers.0": 0, "model.layers.1": 1, "model.norm": 1, "lm_head": 0}
+ model = AutoModelForCausalLM.from_pretrained(
+ "hf-internal-testing/tiny-random-MistralForCausalLM", device_map=device_map
+ )
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-MistralForCausalLM")
+
+ text = "Hello world"
+ tokenized_inputs = tokenizer([text], return_tensors="pt")
+ input_ids = tokenized_inputs.input_ids.to(torch_device)
+
+ generation_kwargs = {
+ "max_new_tokens": 20,
+ "return_dict_in_generate": True, # Required to return `past_key_values`
+ }
+
+ # TODO: We need to raise a warning in case the cache is not set correctly
+ # with self.assertRaisesRegex(ValueError, "If you are manually initializing the cache"):
+ # past_key_values = StaticCache(
+ # config=model.config, batch_size=1, max_cache_len=30, device=torch_device, dtype=model.dtype
+ # )
+ # results = model.generate(input_ids, past_key_values=past_key_values, **generation_kwargs)
+
+ # deduced from the device_map : layer 0 on device 0 and layer 1 on device 1
+ layer_device_map = {0: 0, 1: 1}
+ past_key_values = StaticCache(
+ config=model.config,
+ batch_size=1,
+ max_cache_len=30,
+ device=torch_device,
+ dtype=model.dtype,
+ layer_device_map=layer_device_map,
+ )
+ results = model.generate(input_ids, past_key_values=past_key_values, **generation_kwargs)
+
+ # check device of each layer
+ key_cache_0 = results.past_key_values.key_cache[0]
+ value_cache_0 = results.past_key_values.value_cache[0]
+ self.assertTrue(key_cache_0.device == value_cache_0.device == torch.device(0))
+
+ key_cache_1 = results.past_key_values.key_cache[1]
+ value_cache_1 = results.past_key_values.value_cache[1]
+ self.assertTrue(key_cache_1.device == value_cache_1.device == torch.device(1))
+
+ @slow
+ def test_padding_input_contrastive_search_gpt2(self):
+ # Load the pre-trained GPT-2 model and tokenizer
+ model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2")
+ model.to(torch_device)
+ tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2", clean_up_tokenization_spaces=True)
+
+ # Set the tokenizer to left-pad the sequences
+ tokenizer.padding_side = "left"
+
+ # Define the PAD token as the EOS token
+ tokenizer.pad_token = tokenizer.eos_token
+ model.generation_config.pad_token_id = model.generation_config.eos_token_id
+
+ # Define the input prompt
+ prompt_text = "The whispered legends of the haunted mansion spoke"
+
+ # Tokenize the input prompt
+ encoded_prompt = tokenizer(prompt_text, return_tensors="pt", padding=True)
+ input_ids = encoded_prompt.input_ids.to(torch_device)
+ attention_mask = encoded_prompt.attention_mask.to(torch_device)
+
+ # Define the contrastive search params
+ penalty_alpha = 0.6
+ top_k = 4
+
+ # Define the padding length to add to the input IDs and attention mask
+ padding_length = 10
+
+ # Generate text without padding
+ outputs = model.generate(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ do_sample=False,
+ penalty_alpha=penalty_alpha,
+ top_k=top_k,
+ max_new_tokens=64,
+ )
+ generated_text_no_padding = tokenizer.decode(outputs[0], skip_special_tokens=True)
+
+ # Pad the input IDs and attention mask on the left
+ padded_input_ids = F.pad(
+ input_ids, (padding_length, 0), "constant", value=model.generation_config.pad_token_id
+ )
+ padded_attention_mask = F.pad(attention_mask, (padding_length, 0), "constant", value=0)
+
+ # Generate text with padded inputs
+ outputs_with_padding = model.generate(
+ input_ids=padded_input_ids,
+ attention_mask=padded_attention_mask,
+ do_sample=False,
+ penalty_alpha=penalty_alpha,
+ top_k=top_k,
+ max_new_tokens=64,
+ )
+ generated_text_with_padding = tokenizer.decode(outputs_with_padding[0], skip_special_tokens=True)
+
+ # Assert that the generated texts are identical for padded and non-padded inputs
+ self.assertEqual(generated_text_no_padding, generated_text_with_padding)
+ self.assertEqual(
+ generated_text_with_padding,
+ 'The whispered legends of the haunted mansion spoke of the "souls of the dead" who were "falling '
+ 'out of the sky" and "falling into the sea."\n\nThe ghostly apparitions were said to have been '
+ 'created by the spirits of the dead, who were "falling out of the sky" and "falling into the sea',
+ )
+
+ @slow
+ def test_padding_input_contrastive_search_t5(self):
+ # Load the pre-trained T5 model and tokenizer
+ model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small")
+ model.to(torch_device)
+ tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small", clean_up_tokenization_spaces=True)
+
+ # Define the input prompt
+ prompt_text = "translate English to German: I need to finish this task before the end of the day."
+
+ # Tokenize the input prompt
+ encoded_prompt = tokenizer(prompt_text, return_tensors="pt")
+ input_ids = encoded_prompt.input_ids.to(torch_device)
+ attention_mask = encoded_prompt.attention_mask.to(torch_device)
+
+ # Define the decoder prompt
+ decoder_prompt_text = "Ich muss diese Aufgabe"
+ encoded_decoder_prompt = tokenizer(decoder_prompt_text, add_special_tokens=False, return_tensors="pt")
+ decoder_input_ids = encoded_decoder_prompt.input_ids.to(torch_device)
+ decoder_attention_mask = encoded_decoder_prompt.attention_mask.to(torch_device)
+
+ # Define the contrastive search params
+ penalty_alpha = 0.6
+ top_k = 4
+
+ # Generate text without padding
+ outputs = model.generate(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ decoder_input_ids=decoder_input_ids,
+ decoder_attention_mask=decoder_attention_mask,
+ do_sample=False,
+ penalty_alpha=penalty_alpha,
+ top_k=top_k,
+ max_new_tokens=64,
+ )
+ generated_text_no_padding = tokenizer.decode(outputs[0], skip_special_tokens=True)
+
+ # Define the padding length to add to the input IDs and attention mask
+ padding_length = 10
+
+ # Pad the decoder input IDs and attention mask on the left
+ padded_decoder_input_ids = F.pad(
+ decoder_input_ids, (padding_length, 0), "constant", value=model.generation_config.pad_token_id
+ )
+ padded_decoder_attention_mask = F.pad(decoder_attention_mask, (padding_length, 0), "constant", value=0)
+ # Since the decoder_start_token_id is the same as the pad_token_id,
+ # the last padded token represents the decoder start token.
+ # Set the attention mask for the decoder_start_token_id to True (1).
+ padded_decoder_attention_mask[:, padding_length - 1] = 1
+ # Generate text with padded inputs
+ outputs_with_padding = model.generate(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ decoder_input_ids=padded_decoder_input_ids,
+ decoder_attention_mask=padded_decoder_attention_mask,
+ do_sample=False,
+ penalty_alpha=penalty_alpha,
+ top_k=top_k,
+ max_new_tokens=64,
+ )
+ generated_text_with_padding = tokenizer.decode(outputs_with_padding[0], skip_special_tokens=True)
+
+ # Assert that the generated texts are identical for padded and non-padded inputs
+ self.assertEqual(generated_text_no_padding, generated_text_with_padding)
+ self.assertEqual(generated_text_no_padding, "Ich muss diese Aufgabe vor Ende des Tages beenden.")
+
+ def test_prepare_inputs_for_generation_decoder_llm(self):
+ """Tests GenerationMixin.prepare_inputs_for_generation against expected usage with decoder-only llms."""
+
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-LlamaForCausalLM")
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-LlamaForCausalLM")
+ model = model.to(torch_device)
+
+ # 1. Sanity check: the model's `prepare_inputs_for_generation` comes from `GenerationMixin`
+ self.assertTrue("GenerationMixin" in str(model.prepare_inputs_for_generation))
+
+ # 2. If we pass input ids by themselves, we should get back the same input ids
+ input_ids = torch.tensor([[1, 2, 3], [4, 5, 6]]).to(torch_device)
+ model_inputs = model.prepare_inputs_for_generation(input_ids)
+ self.assertTrue(torch.all(model_inputs["input_ids"] == input_ids))
+
+ # 3. If we pass the attention mask too, we will get back the attention mask and position ids built from it
+ attention_mask = torch.tensor([[1, 1, 1], [1, 1, 1]]).to(torch_device)
+ model_inputs = model.prepare_inputs_for_generation(input_ids, attention_mask=attention_mask)
+ self.assertTrue(torch.all(model_inputs["attention_mask"] == attention_mask))
+ self.assertTrue(model_inputs["position_ids"].shape == input_ids.shape)
+
+ # 4. `use_cache` (and other kwargs) are forwarded
+ self.assertFalse("use_cache" in model_inputs) # From the previous input, there is no `use_cache`
+ model_inputs = model.prepare_inputs_for_generation(input_ids, use_cache=True, foo="bar")
+ self.assertTrue(model_inputs["use_cache"] is True)
+ self.assertTrue(model_inputs["foo"] == "bar")
+
+ # 5. When we pass a cache, we discard data related to already seen tokens in some tensors. We are now also
+ # forced to pass a correctly prepared `cache_positions` to slice the data accordingly.
+ init_input_ids = input_ids[:, :2]
+ dynamic_cache = DynamicCache()
+ dynamic_cache = model(init_input_ids, past_key_values=dynamic_cache).past_key_values
+ with self.assertRaises(AttributeError): # past_key_values + no cache_position -> exception
+ model_inputs = model.prepare_inputs_for_generation(input_ids, past_key_values=dynamic_cache)
+
+ cache_position = torch.arange(input_ids.shape[-1], dtype=torch.long).to(torch_device)
+ cache_position = cache_position[dynamic_cache.get_seq_length() :]
+ model_inputs = model.prepare_inputs_for_generation(
+ input_ids, past_key_values=dynamic_cache, cache_position=cache_position, attention_mask=attention_mask
+ )
+ self.assertTrue("past_key_values" in model_inputs)
+ self.assertTrue(torch.all(model_inputs["cache_position"] == cache_position))
+ self.assertTrue(model_inputs["input_ids"].shape[-1] == 1) # 1 = 3 fed tokens - 2 tokens in the cache
+ self.assertTrue(model_inputs["position_ids"].shape[-1] == 1)
+ self.assertTrue(model_inputs["attention_mask"].shape[-1] == 3) # we still need the full attention mask!
+
+ # 6. If we pass a `static_cache`, the attention mask will be prepared as a static shape 4D mask
+ max_cache_len = 10
+ batch_size = 2
+ query_length = input_ids.shape[-1] - init_input_ids.shape[-1]
+ static_cache = StaticCache(
+ config=config, batch_size=batch_size, max_cache_len=max_cache_len, device=torch_device, dtype=torch.float32
+ )
+ static_cache = model(init_input_ids, past_key_values=static_cache).past_key_values
+ model_inputs = model.prepare_inputs_for_generation(
+ input_ids, past_key_values=static_cache, cache_position=cache_position, attention_mask=attention_mask
+ )
+ self.assertTrue("past_key_values" in model_inputs)
+ self.assertTrue(list(model_inputs["attention_mask"].shape) == [batch_size, 1, query_length, max_cache_len])
+
+ # 7. We can also pass `inputs_embeds` as the embedded prompt. Because `generate` will append its result to
+ # `input_ids` and the models will only accept one of the two inputs (`input_ids` or `inputs_embeds`), we
+ # a) must use the cache b) must expect `input_ids` after the prompt is processed
+ init_inputs_embeds = model.get_input_embeddings()(init_input_ids)
+ init_cache_positions = torch.arange(init_input_ids.shape[-1], dtype=torch.long).to(torch_device)
+ empty_cache = DynamicCache()
+
+ # Prompt processing
+ model_inputs = model.prepare_inputs_for_generation(
+ init_input_ids,
+ past_key_values=empty_cache,
+ inputs_embeds=init_inputs_embeds,
+ cache_position=init_cache_positions,
+ )
+ self.assertTrue(model_inputs["input_ids"] is None)
+ self.assertTrue(model_inputs["inputs_embeds"] is not None)
+
+ # After prompt processing
+ model_inputs = model.prepare_inputs_for_generation(
+ input_ids, past_key_values=dynamic_cache, inputs_embeds=init_inputs_embeds, cache_position=cache_position
+ )
+ self.assertTrue(model_inputs["input_ids"] is not None)
+ self.assertTrue(model_inputs["inputs_embeds"] is None)
+
+ def test_prepare_inputs_for_generation_encoder_decoder_llm(self):
+ """
+ Same as `test_prepare_inputs_for_generation_decoder_llm` but for encoder-decoder models. Main difference: we
+ should look for `decoder_input_ids`, instead of `input_ids`.
+ """
+ model = AutoModelForSeq2SeqLM.from_pretrained("hf-internal-testing/tiny-random-t5")
+ model = model.to(torch_device)
+
+ # 1. Sanity check: the model's `prepare_inputs_for_generation` comes from `GenerationMixin`
+ self.assertTrue("GenerationMixin" in str(model.prepare_inputs_for_generation))
+
+ # 2. If we pass input ids by themselves, we should get back the same input ids -- with the encoder-decoder key
+ decoder_input_ids = torch.tensor([[1, 2, 3], [4, 5, 6]]).to(torch_device)
+ model_inputs = model.prepare_inputs_for_generation(decoder_input_ids)
+ self.assertTrue(torch.all(model_inputs["decoder_input_ids"] == decoder_input_ids))
+
+ # 3. If we pass the attention mask too, we will get back the attention mask. Encoder-decoder models usually
+ # don't use `position_ids`
+ decoder_attention_mask = torch.tensor([[1, 1, 1], [1, 1, 1]]).to(torch_device)
+ model_inputs = model.prepare_inputs_for_generation(
+ decoder_input_ids, decoder_attention_mask=decoder_attention_mask
+ )
+ self.assertTrue(torch.all(model_inputs["decoder_attention_mask"] == decoder_attention_mask))
+ self.assertTrue("position_ids" not in model_inputs)
+
+ # 4. `use_cache` (and other kwargs, like the encoder outputs) are forwarded
+ self.assertFalse("use_cache" in model_inputs) # From the previous input, there is no `use_cache`
+ model_inputs = model.prepare_inputs_for_generation(decoder_input_ids, use_cache=True, encoder_outputs="foo")
+ self.assertTrue(model_inputs["use_cache"] is True)
+ self.assertTrue(model_inputs["encoder_outputs"] == "foo")
+ # See the decoder-only test for more corner cases. The code is the same, so we don't repeat it here.
+
+ def test_generate_compile_fullgraph_tiny(self):
+ """
+ Tests that we can call end-to-end generation with a tiny model (i.e. doesn't crash)
+ NOTE: this test is quite slow (~20s on a consumer desktop), but it is important that we keep it as part of the
+ non-slow tests to prevent regressions!
+ """
+ model = AutoModelForCausalLM.from_pretrained(
+ "hf-internal-testing/tiny-random-LlamaForCausalLM", torch_dtype=torch.bfloat16, device_map="auto"
+ )
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-LlamaForCausalLM")
+
+ # compile generate
+ compiled_generate = torch.compile(model.generate, fullgraph=True, mode="reduce-overhead")
+
+ # compiled generate does NOT accept parameterization except a) model inputs b) a generation config
+ generation_config = copy.deepcopy(model.generation_config)
+ generation_config.pad_token_id = model.config.eos_token_id
+
+ model_inputs = tokenizer(["Write a poem about the market crashing in summer"], return_tensors="pt")
+ model_inputs = model_inputs.to(model.device)
+ gen_out = compiled_generate(**model_inputs, generation_config=generation_config)
+ self.assertTrue(gen_out.shape[1] > model_inputs["input_ids"].shape[1]) # some text was generated
+
+ def test_assisted_generation_early_exit(self):
+ """
+ Tests that assisted generation with early exit works as expected. Under the hood, this has complex cache
+ manipulation, which will cause the test to fail if something goes wrong there.
+ """
+ expected_output = "Alice and Bob are playing a game of poker. Alice has a pair of 8s and Bob has a pair"
+
+ prompt = "Alice and Bob"
+ checkpoint = "facebook/layerskip-llama3.2-1B"
+
+ tokenizer = AutoTokenizer.from_pretrained(checkpoint)
+ inputs = tokenizer(prompt, return_tensors="pt").to(torch_device)
+
+ model = AutoModelForCausalLM.from_pretrained(checkpoint).to(torch_device)
+ original_outputs = model.generate(**inputs, do_sample=False, max_new_tokens=20)
+ original_decoded = tokenizer.batch_decode(original_outputs, skip_special_tokens=True)
+ self.assertEqual(original_decoded, [expected_output])
+
+ outputs_assisted = model.generate(**inputs, assistant_early_exit=4, do_sample=False, max_new_tokens=20)
+ decoded_assisted = tokenizer.batch_decode(outputs_assisted, skip_special_tokens=True)
+ self.assertEqual(decoded_assisted, [expected_output])
+
+ @slow
+ def test_max_time(self):
+ tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
+ model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2")
+ model.to(torch_device)
+
+ torch.manual_seed(0)
+ tokenized = tokenizer("Today is a nice day and", return_tensors="pt", return_token_type_ids=True)
+ input_ids = tokenized.input_ids.to(torch_device)
+
+ MAX_TIME = 0.1
+ MAX_LENGTH = 64
+
+ # sampling on
+ start = datetime.datetime.now()
+ model.generate(input_ids, do_sample=True, max_time=MAX_TIME, max_length=MAX_LENGTH)
+ duration = datetime.datetime.now() - start
+ self.assertGreater(duration, datetime.timedelta(seconds=MAX_TIME))
+ self.assertLess(duration, datetime.timedelta(seconds=1.5 * MAX_TIME))
+
+ # sampling off
+ start = datetime.datetime.now()
+ model.generate(input_ids, do_sample=False, max_time=MAX_TIME, max_length=MAX_LENGTH)
+ duration = datetime.datetime.now() - start
+ self.assertGreater(duration, datetime.timedelta(seconds=MAX_TIME))
+ self.assertLess(duration, datetime.timedelta(seconds=1.5 * MAX_TIME))
+
+ # beam search
+ start = datetime.datetime.now()
+ model.generate(input_ids, do_sample=False, num_beams=2, max_time=MAX_TIME, max_length=MAX_LENGTH)
+ duration = datetime.datetime.now() - start
+ self.assertGreater(duration, datetime.timedelta(seconds=MAX_TIME))
+ self.assertLess(duration, datetime.timedelta(seconds=1.5 * MAX_TIME))
+
+ # sanity check: no time limit
+ start = datetime.datetime.now()
+ model.generate(input_ids, do_sample=False, max_time=None, max_length=MAX_LENGTH)
+ duration = datetime.datetime.now() - start
+ self.assertGreater(duration, datetime.timedelta(seconds=1.5 * MAX_TIME))
+
+ def test_validate_generation_inputs(self):
+ """Tests validation of inputs to `generate`"""
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
+ model = AutoModelForSeq2SeqLM.from_pretrained("hf-internal-testing/tiny-random-t5")
+
+ encoder_input_str = "Hello world"
+ input_ids = tokenizer(encoder_input_str, return_tensors="pt").input_ids
+
+ # typos are quickly detected (the correct argument is `do_sample`)
+ with self.assertRaisesRegex(ValueError, "do_samples"):
+ model.generate(input_ids, do_samples=True)
+
+ # arbitrary arguments that will not be used anywhere are also not accepted
+ with self.assertRaisesRegex(ValueError, "foo"):
+ fake_model_kwargs = {"foo": "bar"}
+ model.generate(input_ids, **fake_model_kwargs)
+
+ # however, valid model_kwargs are accepted
+ valid_model_kwargs = {"attention_mask": torch.tensor(np.zeros_like(input_ids))}
+ model.generate(input_ids, **valid_model_kwargs)
+
+ def test_custom_logits_processor(self):
+ """Tests that custom logits processors can be used in `generate`, and that redundant arguments are caught."""
+ bart_tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bart")
+ article = """Justin Timberlake and Jessica Biel, welcome to parenthood."""
+ bart_model = AutoModelForSeq2SeqLM.from_pretrained("hf-internal-testing/tiny-random-bart", min_length=1)
+ input_ids = bart_tokenizer(article, return_tensors="pt").input_ids
+
+ logits_processor = LogitsProcessorList()
+ logits_processor.append(MinLengthLogitsProcessor(min_length=10, eos_token_id=0))
+
+ # it should not be allowed to both define `min_length` via config and `logits_processor` list
+ with self.assertRaises(ValueError):
+ bart_model.generate(input_ids, logits_processor=logits_processor, min_length=10)
+ bart_model.generate(input_ids, logits_processor=logits_processor)
+
+ def test_transition_scores_greedy_search(self):
+ """Test that `compute_transition_scores` is working as expected with gready search"""
+ articles = ["Justin Timberlake", "Michael Phelps"]
+ tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2", padding_side="left")
+ tokenizer.pad_token = tokenizer.eos_token
+
+ model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
+ model.generation_config.eos_token_id = None
+ input_ids = tokenizer(articles, return_tensors="pt", padding=True).input_ids
+ model = model.to(torch_device)
+ input_ids = input_ids.to(torch_device)
+
+ outputs = model.generate(
+ input_ids=input_ids,
+ max_new_tokens=5,
+ pad_token_id=tokenizer.eos_token_id,
+ return_dict_in_generate=True,
+ output_scores=True,
+ )
+
+ transition_scores = model.compute_transition_scores(outputs.sequences, outputs.scores)
+ transition_scores = transition_scores.cpu().numpy()
+
+ expected_scores = np.array(
+ [
+ [-57.8844, -60.45698, -70.16364, -65.50791, -66.35648],
+ [-54.417572, -60.216614, -62.661243, -58.621933, -58.298683],
+ ]
+ )
+ self.assertTrue(np.allclose(transition_scores, expected_scores, atol=1e-3))
+
+ def test_transition_scores_greedy_search_normalized(self):
+ """
+ Test that `compute_transition_scores` is working as expected with gready search, with `normalize_logits=True`
+ """
+ articles = ["Justin Timberlake", "Michael Phelps"]
+ tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2", padding_side="left")
+ tokenizer.pad_token = tokenizer.eos_token
+
+ model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
+ model.generation_config.eos_token_id = None
+ input_ids = tokenizer(articles, return_tensors="pt", padding=True).input_ids
+ model = model.to(torch_device)
+ input_ids = input_ids.to(torch_device)
+
+ outputs = model.generate(
+ input_ids=input_ids,
+ max_new_tokens=5,
+ pad_token_id=tokenizer.eos_token_id,
+ return_dict_in_generate=True,
+ output_scores=True,
+ )
+
+ transition_scores = model.compute_transition_scores(outputs.sequences, outputs.scores, normalize_logits=True)
+ transition_scores = transition_scores.cpu().numpy()
+
+ expected_scores = np.array(
+ [
+ [-2.538938, -2.2694316, -2.1580915, -1.572299, -2.6719835],
+ [-1.8826028, -2.2461371, -1.7556462, -2.9644494, -1.7996008],
+ ]
+ )
+ self.assertTrue(np.allclose(transition_scores, expected_scores, atol=1e-3))
+
+ def test_transition_scores_beam_search_encoder_decoder(self):
+ """
+ Test that `compute_transition_scores` is working as expected with beam search and encoder-decoder models
+ """
+ articles = [
+ "Justin Timberlake and Jessica Biel, welcome to parenthood.",
+ "Michael Phelps is arguably the most decorated Olympian of all time.",
+ ]
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bart")
+ model = AutoModelForSeq2SeqLM.from_pretrained("hf-internal-testing/tiny-random-bart")
+ input_ids = tokenizer(articles, return_tensors="pt", padding=True).input_ids
+ model = model.to(torch_device)
+ input_ids = input_ids.to(torch_device)
+
+ outputs = model.generate(
+ input_ids=input_ids,
+ max_length=10,
+ num_beams=4,
+ num_return_sequences=2,
+ eos_token_id=None,
+ return_dict_in_generate=True,
+ output_scores=True,
+ length_penalty=0.0,
+ )
+
+ transition_scores = model.compute_transition_scores(outputs.sequences, outputs.scores, outputs.beam_indices)
+ transition_scores = transition_scores.cpu().numpy()
+ outputs.sequences_scores = outputs.sequences_scores.cpu().numpy()
+
+ self.assertTrue(np.allclose(np.sum(transition_scores, axis=-1), outputs.sequences_scores, atol=1e-3))
+
+ def test_transition_scores_beam_search_encoder_decoder_with_eos(self):
+ """
+ Test that `compute_transition_scores` is working as expected with beam search and encoder-decoder models, when
+ an EOS token is defined
+ """
+ articles = [
+ "Justin Timberlake and Jessica Biel, welcome to parenthood.",
+ "Michael Phelps is arguably the most decorated Olympian of all time.",
+ ]
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bart")
+
+ model = AutoModelForSeq2SeqLM.from_pretrained("hf-internal-testing/tiny-random-bart")
+ input_ids = tokenizer(articles, return_tensors="pt", padding=True).input_ids
+ model = model.to(torch_device)
+ input_ids = input_ids.to(torch_device)
+
+ outputs = model.generate(
+ input_ids=input_ids,
+ max_length=10,
+ num_beams=4,
+ num_return_sequences=2,
+ return_dict_in_generate=True,
+ output_scores=True,
+ length_penalty=0.0,
+ )
+
+ transition_scores = model.compute_transition_scores(outputs.sequences, outputs.scores, outputs.beam_indices)
+ transition_scores = transition_scores.cpu().numpy()
+ outputs.sequences_scores = outputs.sequences_scores.cpu().numpy()
+
+ self.assertTrue(np.allclose(np.sum(transition_scores, axis=-1), outputs.sequences_scores, atol=1e-3))
+
+ def test_transition_scores_beam_search_decoder_only(self):
+ """
+ Test that `compute_transition_scores` is working as expected with beam search and decoder-only models
+ """
+ articles = [
+ "Justin Timberlake",
+ "Michael Phelps",
+ ]
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ tokenizer.pad_token = tokenizer.eos_token
+
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ input_ids = tokenizer(articles, return_tensors="pt", padding=True).input_ids
+ model = model.to(torch_device)
+ input_ids = input_ids.to(torch_device)
+
+ outputs = model.generate(
+ input_ids=input_ids,
+ max_length=10,
+ num_beams=4,
+ num_return_sequences=2,
+ pad_token_id=tokenizer.eos_token_id,
+ eos_token_id=None,
+ return_dict_in_generate=True,
+ output_scores=True,
+ length_penalty=0.0,
+ )
+
+ transition_scores = model.compute_transition_scores(outputs.sequences, outputs.scores, outputs.beam_indices)
+ transition_scores = transition_scores.cpu().numpy()
+ outputs.sequences_scores = outputs.sequences_scores.cpu().numpy()
+
+ self.assertTrue(np.allclose(np.sum(transition_scores, axis=-1), outputs.sequences_scores, atol=1e-3))
+
+ @slow
+ def test_transition_scores_early_stopping(self):
+ """
+ Test that `compute_transition_scores` is working as expected with beam search and early stopping
+
+ This is an aggressive test that makes sure that `beam_search's`
+ transition scores are computed correctly for varying `num_return_sequences`, `num_beams` and `batch_size > 1`
+ 2 x input_ids for "question: How are you? \n context: I had a long day, "
+ """
+ input_ids = torch.tensor(2 * [[822, 10, 571, 33, 25, 58, 2625, 10, 27, 141, 3, 9, 307, 239, 6, 1]])
+ model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-small")
+ model = model.to(torch_device)
+ input_ids = input_ids.to(torch_device)
+
+ outputs = model.generate(
+ input_ids,
+ max_length=10,
+ return_dict_in_generate=True,
+ output_scores=True,
+ forced_eos_token_id=model.config.eos_token_id,
+ num_beams=4,
+ do_sample=False,
+ num_return_sequences=3,
+ length_penalty=0.0,
+ )
+
+ transition_scores = model.compute_transition_scores(
+ sequences=outputs.sequences, scores=outputs.scores, beam_indices=outputs.beam_indices
+ )
+ transition_scores = transition_scores.cpu().numpy()
+ outputs.sequences_scores = outputs.sequences_scores.cpu().numpy()
+
+ self.assertTrue(np.allclose(np.sum(transition_scores, axis=-1), outputs.sequences_scores))
+
+ def test_encoder_decoder_generate_attention_mask(self):
+ """
+ Test that `generate` automagically creates the correct `attention_mask` for encoder-decoder models (which
+ has a different keyword)
+ """
+ articles = ["Timberlake", "Jessica Biel, welcome to parenthood among other things"]
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bart")
+ # need extreme generation values here to force this test
+ # to fail when `attention_mask` is not correctly treated in generate
+ model = AutoModelForSeq2SeqLM.from_pretrained(
+ "hf-internal-testing/tiny-random-bart",
+ )
+ model.config.eos_token_id = None
+ input_ids = tokenizer(articles[0], return_tensors="pt").input_ids
+ input_ids_batched = tokenizer(articles, padding=True, return_tensors="pt").input_ids
+ model = model.to(torch_device)
+ input_ids = input_ids.to(torch_device)
+ input_ids_batched = input_ids_batched.to(torch_device)
+
+ generate_kwargs = {
+ "return_dict_in_generate": True,
+ "output_scores": True,
+ "max_length": 50,
+ "num_beams": 5,
+ "num_return_sequences": 5,
+ }
+
+ output_sequences_batched = model.generate(input_ids=input_ids_batched, **generate_kwargs)
+ output_sequences = model.generate(input_ids=input_ids, **generate_kwargs)
+
+ batched_out = output_sequences_batched.sequences_scores
+ out = output_sequences.sequences_scores
+ batched_out = batched_out.cpu().numpy()
+ out = out.cpu().numpy()
+
+ diff = np.abs(np.sum(batched_out[:5]) - np.sum(out))
+ self.assertTrue(diff < 1e-4)
+
+ def test_generate_input_ids_as_kwarg(self):
+ """Test that `input_ids` work equaly as a positional and keyword argument in decoder-only models"""
+ article = "I need input_ids to generate"
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2", max_length=15)
+ input_ids = tokenizer(article, return_tensors="pt").input_ids
+ model = model.to(torch_device)
+ input_ids = input_ids.to(torch_device)
+
+ output_sequences_kwargs = model.generate(input_ids=input_ids)
+ output_sequences = model.generate(input_ids)
+ output_sequences_kwargs = output_sequences_kwargs.cpu().numpy()
+ output_sequences = output_sequences.cpu().numpy()
+
+ self.assertTrue(np.array_equal(output_sequences, output_sequences_kwargs))
+ self.assertEqual(output_sequences.shape, (1, 15))
+
+ def test_generate_input_ids_as_encoder_kwarg(self):
+ """Test that `input_ids` work equaly as a positional and keyword argument in encoder-decoder models"""
+ article = "Justin Timberlake and Jessica Biel, welcome to parenthood."
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bart")
+ model = AutoModelForSeq2SeqLM.from_pretrained("hf-internal-testing/tiny-random-bart")
+ model.config.eos_token_id = None
+ input_ids = tokenizer(article, return_tensors="pt").input_ids
+ model = model.to(torch_device)
+ input_ids = input_ids.to(torch_device)
+
+ output_sequences_kwargs = model.generate(input_ids=input_ids, max_length=5)
+ output_sequences = model.generate(input_ids, max_length=5)
+ output_sequences_kwargs = output_sequences_kwargs.cpu().numpy()
+ output_sequences = output_sequences.cpu().numpy()
+
+ self.assertTrue(np.array_equal(output_sequences, output_sequences_kwargs))
+ self.assertEqual(output_sequences.shape, (1, 5))
+
+ def test_generate_inputs_and_encoder_kwargs(self):
+ """
+ Test that an exception is thrown if the main tensor (`input_ids` in LLMs) is passed as both a positional and
+ keyword argument
+ """
+ article = "I need input_ids to generate"
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2", max_length=10)
+ input_ids = tokenizer(article, return_tensors="pt").input_ids
+ with self.assertRaises(ValueError):
+ model.generate(input_ids, input_ids=input_ids)
+
+ def test_generate_too_many_encoder_kwargs(self):
+ """Test that passing redundant inputs results in an exception (`input_ids` and `inputs_embeds` in LLMs)"""
+ article = "I need input_ids to generate"
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bart")
+ model = AutoModelForSeq2SeqLM.from_pretrained("hf-internal-testing/tiny-random-bart", max_length=10)
+ input_ids = tokenizer(article, return_tensors="pt").input_ids
+ with self.assertRaises(ValueError):
+ model.generate(input_ids=input_ids, inputs_embeds=input_ids)
+
+ def test_generate_input_features_as_encoder_kwarg(self):
+ """Test that non-`input_ids` main model inputs are correctly handled as positional arguments"""
+ input_features = floats_tensor((3, 80, 60))
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
+ "hf-internal-testing/tiny-random-WhisperForConditionalGeneration"
+ )
+ input_features.to(torch_device)
+ model = model.to(torch_device)
+
+ output_sequences_kwargs = model.generate(input_features=input_features, max_length=5)
+ output_sequences = model.generate(input_features, max_length=5)
+ output_sequences_kwargs = output_sequences_kwargs.cpu().numpy()
+ output_sequences = output_sequences.cpu().numpy()
+
+ self.assertTrue(np.array_equal(output_sequences, output_sequences_kwargs))
+ self.assertEqual(output_sequences.shape, (3, 5))
+
+ def test_generate_encoder_outputs_attention_mask(self):
+ """Test that `generate` can handle attention masks when the encoder outputs are passed"""
+ input_features = floats_tensor((3, 80, 60))
+ attention_mask = torch.randint(0, 2, input_features.shape).to(torch_device)
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
+ "hf-internal-testing/tiny-random-WhisperForConditionalGeneration"
+ )
+ input_features = input_features.to(torch_device)
+ attention_mask = attention_mask.to(torch_device)
+ model = model.to(torch_device)
+
+ encoder = model.get_encoder()
+ encoder_outputs = encoder(input_features)
+
+ output_sequences_no_mask = model.generate(encoder_outputs=encoder_outputs)
+ output_sequences_with_mask = model.generate(encoder_outputs=encoder_outputs, attention_mask=attention_mask)
+ output_sequences_no_mask = output_sequences_no_mask.cpu().numpy()
+ output_sequences_with_mask = output_sequences_with_mask.cpu().numpy()
+
+ self.assertFalse(np.array_equal(output_sequences_no_mask, output_sequences_with_mask))
+
+ def test_eos_token_id_int_and_list_greedy_search(self):
+ """Test that `generate` can handle multiple EOS tokens"""
+ generation_kwargs = {
+ "do_sample": False,
+ "num_beams": 1,
+ }
+ expectation = 13
+
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ text = """Hello, my dog is cute and"""
+ tokens = tokenizer(text, return_tensors="pt")
+ model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2")
+ model = model.to(torch_device)
+ tokens = tokens.to(torch_device)
+
+ eos_token_id = 873
+ generated_tokens = model.generate(**tokens, eos_token_id=eos_token_id, **generation_kwargs)
+ self.assertTrue(expectation == len(generated_tokens[0]))
+
+ eos_token_id = [873, 198]
+ generated_tokens = model.generate(**tokens, eos_token_id=eos_token_id, **generation_kwargs)
+ self.assertTrue(expectation == len(generated_tokens[0]))
+
+ def test_generate_vision2text_conditioning(self):
+ """Test that `decoder_input_ids` can be used to condition the generation in vision-to-text models"""
+ pixel_values = floats_tensor((2, 3, 30, 30))
+ conditioning_input = torch.tensor([[10], [10]]) # this should be the 2nd output token, after the BOS token
+ model = AutoModelForVision2Seq.from_pretrained(
+ "hf-internal-testing/tiny-random-VisionEncoderDecoderModel-vit-gpt2"
+ )
+ pixel_values = pixel_values.to(torch_device)
+ model = model.to(torch_device)
+ conditioning_input = conditioning_input.to(torch_device)
+
+ # we can condition on decoder_input_ids (expected decoder input) and input_ids (which we pipe internally as
+ # decoder_input_ids, if the encoder is not a model with text input)
+ output_sequences_decoder_input_ids = model.generate(
+ pixel_values, max_length=5, decoder_input_ids=conditioning_input
+ )
+ output_sequences_input_ids = model.generate(pixel_values, max_length=5, input_ids=conditioning_input)
+ output_sequences_decoder_input_ids = output_sequences_decoder_input_ids.cpu().numpy()
+ output_sequences_input_ids = output_sequences_input_ids.cpu().numpy()
+ conditioning_input = conditioning_input.cpu().numpy()
+
+ self.assertTrue(np.array_equal(output_sequences_decoder_input_ids, output_sequences_input_ids))
+ self.assertTrue(np.array_equal(output_sequences_decoder_input_ids[:, 1:2], conditioning_input))
+
+
+@require_torch
+class TokenHealingTestCase(unittest.TestCase):
+ @parameterized.expand(
+ [
+ ("url", 'The link is = 2.4 to run.")
+
+ distilbert_model = "albert/albert-base-v2"
+ device = "cpu"
+ attn_implementation = "sdpa"
+ max_length = 64
+
+ tokenizer = AutoTokenizer.from_pretrained(distilbert_model)
+ inputs = tokenizer(
+ f"Paris is the {tokenizer.mask_token} of France.",
+ return_tensors="pt",
+ padding="max_length",
+ max_length=max_length,
+ )
+
+ model = AlbertForMaskedLM.from_pretrained(
+ distilbert_model,
+ device_map=device,
+ attn_implementation=attn_implementation,
+ )
+
+ logits = model(**inputs).logits
+ eg_predicted_mask = tokenizer.decode(logits[0, 4].topk(5).indices)
+ self.assertEqual(
+ eg_predicted_mask.split(),
+ ["capital", "capitol", "comune", "arrondissement", "bastille"],
+ )
+
+ exported_program = torch.export.export(
+ model,
+ args=(inputs["input_ids"],),
+ kwargs={"attention_mask": inputs["attention_mask"]},
+ strict=True,
+ )
+
+ result = exported_program.module().forward(inputs["input_ids"], inputs["attention_mask"])
+ ep_predicted_mask = tokenizer.decode(result.logits[0, 4].topk(5).indices)
+ self.assertEqual(eg_predicted_mask, ep_predicted_mask)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/albert/test_modeling_flax_albert.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/albert/test_modeling_flax_albert.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca8eeec59131a89af8da1cf4a6a7f53995554070
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/albert/test_modeling_flax_albert.py
@@ -0,0 +1,161 @@
+# 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.
+
+import unittest
+
+import numpy as np
+
+from transformers import AlbertConfig, is_flax_available
+from transformers.testing_utils import require_flax, slow
+
+from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask
+
+
+if is_flax_available():
+ import jax.numpy as jnp
+
+ from transformers.models.albert.modeling_flax_albert import (
+ FlaxAlbertForMaskedLM,
+ FlaxAlbertForMultipleChoice,
+ FlaxAlbertForPreTraining,
+ FlaxAlbertForQuestionAnswering,
+ FlaxAlbertForSequenceClassification,
+ FlaxAlbertForTokenClassification,
+ FlaxAlbertModel,
+ )
+
+
+class FlaxAlbertModelTester:
+ def __init__(
+ self,
+ parent,
+ batch_size=13,
+ seq_length=7,
+ is_training=True,
+ use_attention_mask=True,
+ use_token_type_ids=True,
+ use_labels=True,
+ vocab_size=99,
+ hidden_size=32,
+ num_hidden_layers=2,
+ num_attention_heads=4,
+ intermediate_size=37,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.1,
+ attention_probs_dropout_prob=0.1,
+ max_position_embeddings=512,
+ type_vocab_size=16,
+ type_sequence_label_size=2,
+ initializer_range=0.02,
+ num_choices=4,
+ ):
+ self.parent = parent
+ self.batch_size = batch_size
+ self.seq_length = seq_length
+ self.is_training = is_training
+ self.use_attention_mask = use_attention_mask
+ self.use_token_type_ids = use_token_type_ids
+ self.use_labels = use_labels
+ self.vocab_size = vocab_size
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.intermediate_size = intermediate_size
+ self.hidden_act = hidden_act
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.max_position_embeddings = max_position_embeddings
+ self.type_vocab_size = type_vocab_size
+ self.type_sequence_label_size = type_sequence_label_size
+ self.initializer_range = initializer_range
+ self.num_choices = num_choices
+
+ def prepare_config_and_inputs(self):
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
+
+ attention_mask = None
+ if self.use_attention_mask:
+ attention_mask = random_attention_mask([self.batch_size, self.seq_length])
+
+ token_type_ids = None
+ if self.use_token_type_ids:
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
+
+ config = AlbertConfig(
+ vocab_size=self.vocab_size,
+ hidden_size=self.hidden_size,
+ num_hidden_layers=self.num_hidden_layers,
+ num_attention_heads=self.num_attention_heads,
+ intermediate_size=self.intermediate_size,
+ hidden_act=self.hidden_act,
+ hidden_dropout_prob=self.hidden_dropout_prob,
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
+ max_position_embeddings=self.max_position_embeddings,
+ type_vocab_size=self.type_vocab_size,
+ is_decoder=False,
+ initializer_range=self.initializer_range,
+ )
+
+ return config, input_ids, token_type_ids, attention_mask
+
+ def prepare_config_and_inputs_for_common(self):
+ config_and_inputs = self.prepare_config_and_inputs()
+ config, input_ids, token_type_ids, attention_mask = config_and_inputs
+ inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask}
+ return config, inputs_dict
+
+
+@require_flax
+class FlaxAlbertModelTest(FlaxModelTesterMixin, unittest.TestCase):
+ all_model_classes = (
+ (
+ FlaxAlbertModel,
+ FlaxAlbertForPreTraining,
+ FlaxAlbertForMaskedLM,
+ FlaxAlbertForMultipleChoice,
+ FlaxAlbertForQuestionAnswering,
+ FlaxAlbertForSequenceClassification,
+ FlaxAlbertForTokenClassification,
+ FlaxAlbertForQuestionAnswering,
+ )
+ if is_flax_available()
+ else ()
+ )
+
+ def setUp(self):
+ self.model_tester = FlaxAlbertModelTester(self)
+
+ @slow
+ def test_model_from_pretrained(self):
+ for model_class_name in self.all_model_classes:
+ model = model_class_name.from_pretrained("albert/albert-base-v2")
+ outputs = model(np.ones((1, 1)))
+ self.assertIsNotNone(outputs)
+
+
+@require_flax
+class FlaxAlbertModelIntegrationTest(unittest.TestCase):
+ @slow
+ def test_inference_no_head_absolute_embedding(self):
+ model = FlaxAlbertModel.from_pretrained("albert/albert-base-v2")
+ input_ids = np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]])
+ attention_mask = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
+ output = model(input_ids, attention_mask=attention_mask)[0]
+ expected_shape = (1, 11, 768)
+ self.assertEqual(output.shape, expected_shape)
+ expected_slice = np.array(
+ [[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]]
+ )
+
+ self.assertTrue(jnp.allclose(output[:, 1:4, 1:4], expected_slice, atol=1e-4))
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/albert/test_modeling_tf_albert.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/albert/test_modeling_tf_albert.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3dab618eecb4abcef1d07e4c4b8b26af21ef743
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/albert/test_modeling_tf_albert.py
@@ -0,0 +1,329 @@
+# coding=utf-8
+# 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 __future__ import annotations
+
+import unittest
+
+from transformers import AlbertConfig, is_tf_available
+from transformers.models.auto import get_values
+from transformers.testing_utils import require_tf, slow
+
+from ...test_configuration_common import ConfigTester
+from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
+from ...test_pipeline_mixin import PipelineTesterMixin
+
+
+if is_tf_available():
+ import tensorflow as tf
+
+ from transformers import TF_MODEL_FOR_PRETRAINING_MAPPING
+ from transformers.models.albert.modeling_tf_albert import (
+ TFAlbertForMaskedLM,
+ TFAlbertForMultipleChoice,
+ TFAlbertForPreTraining,
+ TFAlbertForQuestionAnswering,
+ TFAlbertForSequenceClassification,
+ TFAlbertForTokenClassification,
+ TFAlbertModel,
+ )
+
+
+class TFAlbertModelTester:
+ def __init__(
+ self,
+ parent,
+ batch_size=13,
+ seq_length=7,
+ is_training=True,
+ use_input_mask=True,
+ use_token_type_ids=True,
+ use_labels=True,
+ vocab_size=99,
+ embedding_size=16,
+ hidden_size=32,
+ num_hidden_layers=2,
+ num_attention_heads=4,
+ intermediate_size=37,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.1,
+ attention_probs_dropout_prob=0.1,
+ max_position_embeddings=512,
+ type_vocab_size=16,
+ type_sequence_label_size=2,
+ initializer_range=0.02,
+ num_labels=3,
+ num_choices=4,
+ scope=None,
+ ):
+ self.parent = parent
+ self.batch_size = 13
+ self.seq_length = 7
+ self.is_training = True
+ self.use_input_mask = True
+ self.use_token_type_ids = True
+ self.use_labels = True
+ self.vocab_size = 99
+ self.embedding_size = 16
+ self.hidden_size = 32
+ self.num_hidden_layers = 2
+ self.num_attention_heads = 4
+ self.intermediate_size = 37
+ self.hidden_act = "gelu"
+ self.hidden_dropout_prob = 0.1
+ self.attention_probs_dropout_prob = 0.1
+ self.max_position_embeddings = 512
+ self.type_vocab_size = 16
+ self.type_sequence_label_size = 2
+ self.initializer_range = 0.02
+ self.num_labels = 3
+ self.num_choices = 4
+ self.scope = None
+
+ def prepare_config_and_inputs(self):
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
+
+ input_mask = None
+ if self.use_input_mask:
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
+
+ token_type_ids = None
+ if self.use_token_type_ids:
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
+
+ sequence_labels = None
+ token_labels = None
+ choice_labels = None
+ if self.use_labels:
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
+
+ config = AlbertConfig(
+ vocab_size=self.vocab_size,
+ hidden_size=self.hidden_size,
+ embedding_size=self.embedding_size,
+ num_hidden_layers=self.num_hidden_layers,
+ num_attention_heads=self.num_attention_heads,
+ intermediate_size=self.intermediate_size,
+ hidden_act=self.hidden_act,
+ hidden_dropout_prob=self.hidden_dropout_prob,
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
+ max_position_embeddings=self.max_position_embeddings,
+ type_vocab_size=self.type_vocab_size,
+ initializer_range=self.initializer_range,
+ )
+
+ return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
+
+ def create_and_check_albert_model(
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
+ ):
+ model = TFAlbertModel(config=config)
+ # inputs = {'input_ids': input_ids,
+ # 'attention_mask': input_mask,
+ # 'token_type_ids': token_type_ids}
+ # sequence_output, pooled_output = model(**inputs)
+ inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
+ result = model(inputs)
+
+ inputs = [input_ids, input_mask]
+ result = model(inputs)
+
+ result = model(input_ids)
+
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
+ self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
+
+ def create_and_check_albert_for_pretraining(
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
+ ):
+ config.num_labels = self.num_labels
+ model = TFAlbertForPreTraining(config=config)
+ inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
+ result = model(inputs)
+ self.parent.assertEqual(result.prediction_logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
+ self.parent.assertEqual(result.sop_logits.shape, (self.batch_size, self.num_labels))
+
+ def create_and_check_albert_for_masked_lm(
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
+ ):
+ model = TFAlbertForMaskedLM(config=config)
+ inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
+ result = model(inputs)
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
+
+ def create_and_check_albert_for_sequence_classification(
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
+ ):
+ config.num_labels = self.num_labels
+ model = TFAlbertForSequenceClassification(config=config)
+ inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
+ result = model(inputs)
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
+
+ def create_and_check_albert_for_question_answering(
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
+ ):
+ model = TFAlbertForQuestionAnswering(config=config)
+ inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
+ result = model(inputs)
+ self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
+ self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
+
+ def create_and_check_albert_for_multiple_choice(
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
+ ):
+ config.num_choices = self.num_choices
+ model = TFAlbertForMultipleChoice(config=config)
+ multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids, 1), (1, self.num_choices, 1))
+ multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1))
+ multiple_choice_token_type_ids = tf.tile(tf.expand_dims(token_type_ids, 1), (1, self.num_choices, 1))
+ inputs = {
+ "input_ids": multiple_choice_inputs_ids,
+ "attention_mask": multiple_choice_input_mask,
+ "token_type_ids": multiple_choice_token_type_ids,
+ }
+ result = model(inputs)
+ self.parent.assertListEqual(list(result["logits"].shape), [self.batch_size, self.num_choices])
+
+ def create_and_check_albert_for_token_classification(
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
+ ):
+ config.num_labels = self.num_labels
+ model = TFAlbertForTokenClassification(config=config)
+ inputs = {
+ "input_ids": input_ids,
+ "attention_mask": input_mask,
+ "token_type_ids": token_type_ids,
+ }
+ result = model(inputs)
+ self.parent.assertListEqual(list(result["logits"].shape), [self.batch_size, self.seq_length, self.num_labels])
+
+ def prepare_config_and_inputs_for_common(self):
+ config_and_inputs = self.prepare_config_and_inputs()
+ (
+ config,
+ input_ids,
+ token_type_ids,
+ input_mask,
+ sequence_labels,
+ token_labels,
+ choice_labels,
+ ) = config_and_inputs
+ inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
+ return config, inputs_dict
+
+
+@require_tf
+class TFAlbertModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
+ all_model_classes = (
+ (
+ TFAlbertModel,
+ TFAlbertForPreTraining,
+ TFAlbertForMaskedLM,
+ TFAlbertForSequenceClassification,
+ TFAlbertForQuestionAnswering,
+ TFAlbertForTokenClassification,
+ TFAlbertForMultipleChoice,
+ )
+ if is_tf_available()
+ else ()
+ )
+ pipeline_model_mapping = (
+ {
+ "feature-extraction": TFAlbertModel,
+ "fill-mask": TFAlbertForMaskedLM,
+ "question-answering": TFAlbertForQuestionAnswering,
+ "text-classification": TFAlbertForSequenceClassification,
+ "token-classification": TFAlbertForTokenClassification,
+ "zero-shot": TFAlbertForSequenceClassification,
+ }
+ if is_tf_available()
+ else {}
+ )
+ test_head_masking = False
+ test_onnx = False
+
+ # special case for ForPreTraining model
+ def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
+ inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
+
+ if return_labels:
+ if model_class in get_values(TF_MODEL_FOR_PRETRAINING_MAPPING):
+ inputs_dict["sentence_order_label"] = tf.zeros(self.model_tester.batch_size, dtype=tf.int32)
+
+ return inputs_dict
+
+ def setUp(self):
+ self.model_tester = TFAlbertModelTester(self)
+ self.config_tester = ConfigTester(self, config_class=AlbertConfig, hidden_size=37)
+
+ def test_config(self):
+ self.config_tester.run_common_tests()
+
+ def test_albert_model(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_albert_model(*config_and_inputs)
+
+ def test_for_pretraining(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_albert_for_pretraining(*config_and_inputs)
+
+ def test_for_masked_lm(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_albert_for_masked_lm(*config_and_inputs)
+
+ def test_for_multiple_choice(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_albert_for_multiple_choice(*config_and_inputs)
+
+ def test_for_sequence_classification(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_albert_for_sequence_classification(*config_and_inputs)
+
+ def test_for_question_answering(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_albert_for_question_answering(*config_and_inputs)
+
+ @slow
+ def test_model_from_pretrained(self):
+ model_name = "albert/albert-base-v1"
+ model = TFAlbertModel.from_pretrained(model_name)
+ self.assertIsNotNone(model)
+
+
+@require_tf
+class TFAlbertModelIntegrationTest(unittest.TestCase):
+ @slow
+ def test_inference_masked_lm(self):
+ model = TFAlbertForPreTraining.from_pretrained("albert/albert-base-v2")
+ input_ids = tf.constant([[0, 1, 2, 3, 4, 5]])
+ output = model(input_ids)[0]
+
+ expected_shape = [1, 6, 30000]
+ self.assertEqual(output.shape, expected_shape)
+
+ expected_slice = tf.constant(
+ [
+ [
+ [4.595668, 0.74462754, -1.818147],
+ [4.5954347, 0.7454184, -1.8188258],
+ [4.5954905, 0.7448235, -1.8182316],
+ ]
+ ]
+ )
+ tf.debugging.assert_near(output[:, :3, :3], expected_slice, atol=1e-4)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/albert/test_tokenization_albert.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/albert/test_tokenization_albert.py
new file mode 100644
index 0000000000000000000000000000000000000000..beb910b9d1555b0fbca02f4df36606219fe7f379
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/albert/test_tokenization_albert.py
@@ -0,0 +1,133 @@
+# coding=utf-8
+# Copyright 2019 Hugging Face inc.
+#
+# 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 unittest
+
+from transformers import AlbertTokenizer, AlbertTokenizerFast
+from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
+
+from ...test_tokenization_common import TokenizerTesterMixin
+
+
+SAMPLE_VOCAB = get_tests_dir("fixtures/spiece.model")
+
+
+@require_sentencepiece
+@require_tokenizers
+class AlbertTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
+ from_pretrained_id = "albert/albert-base-v1"
+ tokenizer_class = AlbertTokenizer
+ rust_tokenizer_class = AlbertTokenizerFast
+ test_rust_tokenizer = True
+ test_sentencepiece = True
+ test_sentencepiece_ignore_case = True
+
+ def setUp(self):
+ super().setUp()
+
+ # We have a SentencePiece fixture for testing
+ tokenizer = AlbertTokenizer(SAMPLE_VOCAB)
+ tokenizer.save_pretrained(self.tmpdirname)
+
+ def get_input_output_texts(self, tokenizer):
+ input_text = "this is a test"
+ output_text = "this is a test"
+ return input_text, output_text
+
+ def test_convert_token_and_id(self):
+ """Test ``_convert_token_to_id`` and ``_convert_id_to_token``."""
+ token = ""
+ token_id = 0
+
+ self.assertEqual(self.get_tokenizer()._convert_token_to_id(token), token_id)
+ self.assertEqual(self.get_tokenizer()._convert_id_to_token(token_id), token)
+
+ def test_get_vocab(self):
+ vocab_keys = list(self.get_tokenizer().get_vocab().keys())
+
+ self.assertEqual(vocab_keys[0], "")
+ self.assertEqual(vocab_keys[1], "")
+ self.assertEqual(vocab_keys[-1], "▁eloquent")
+ self.assertEqual(len(vocab_keys), 30_000)
+
+ def test_vocab_size(self):
+ self.assertEqual(self.get_tokenizer().vocab_size, 30_000)
+
+ def test_rust_and_python_full_tokenizers(self):
+ if not self.test_rust_tokenizer:
+ self.skipTest(reason="test_rust_tokenizer is set to False")
+
+ tokenizer = self.get_tokenizer()
+ rust_tokenizer = self.get_rust_tokenizer()
+
+ sequence = "I was born in 92000, and this is falsé."
+
+ tokens = tokenizer.tokenize(sequence)
+ rust_tokens = rust_tokenizer.tokenize(sequence)
+ self.assertListEqual(tokens, rust_tokens)
+
+ ids = tokenizer.encode(sequence, add_special_tokens=False)
+ rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False)
+ self.assertListEqual(ids, rust_ids)
+
+ rust_tokenizer = self.get_rust_tokenizer()
+ ids = tokenizer.encode(sequence)
+ rust_ids = rust_tokenizer.encode(sequence)
+ self.assertListEqual(ids, rust_ids)
+
+ def test_full_tokenizer(self):
+ tokenizer = AlbertTokenizer(SAMPLE_VOCAB, keep_accents=True)
+
+ tokens = tokenizer.tokenize("This is a test")
+ self.assertListEqual(tokens, ["▁this", "▁is", "▁a", "▁test"])
+
+ self.assertListEqual(tokenizer.convert_tokens_to_ids(tokens), [48, 25, 21, 1289])
+
+ tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.")
+ self.assertListEqual(
+ tokens, ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", "."]
+ )
+ ids = tokenizer.convert_tokens_to_ids(tokens)
+ self.assertListEqual(ids, [31, 23, 386, 19, 561, 3050, 15, 17, 48, 25, 8256, 18, 1, 9])
+
+ back_tokens = tokenizer.convert_ids_to_tokens(ids)
+ self.assertListEqual(
+ back_tokens,
+ ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "", "."],
+ )
+
+ def test_sequence_builders(self):
+ tokenizer = AlbertTokenizer(SAMPLE_VOCAB)
+
+ text = tokenizer.encode("sequence builders")
+ text_2 = tokenizer.encode("multi-sequence build")
+
+ encoded_sentence = tokenizer.build_inputs_with_special_tokens(text)
+ encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2)
+
+ assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
+ assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_2 + [
+ tokenizer.sep_token_id
+ ]
+
+ @slow
+ def test_tokenizer_integration(self):
+ expected_encoding = {'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, 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, 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 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]], 'input_ids': [[2, 21970, 13, 5, 6092, 167, 28, 7103, 2153, 673, 8, 7028, 12051, 18, 17, 7103, 2153, 673, 8, 3515, 18684, 8, 4461, 6, 1927, 297, 8, 12060, 2607, 18, 13, 5, 4461, 15, 10538, 38, 8, 135, 15, 822, 58, 15, 993, 10363, 15, 1460, 8005, 4461, 15, 993, 255, 2328, 9, 9, 9, 6, 26, 1112, 816, 3260, 13, 5, 103, 2377, 6, 17, 1112, 816, 2782, 13, 5, 103, 10641, 6, 29, 84, 2512, 2430, 782, 18684, 2761, 19, 808, 2430, 2556, 17, 855, 1480, 9477, 4091, 128, 11712, 15, 7103, 2153, 673, 17, 24883, 9990, 9, 3], [2, 11502, 25, 1006, 20, 782, 8, 11809, 855, 1732, 19393, 18667, 37, 367, 21018, 69, 1854, 34, 11860, 19124, 27, 156, 225, 17, 193, 4141, 19, 65, 9124, 9, 3, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 14, 2231, 886, 2385, 17659, 84, 14, 16792, 1952, 9, 3, 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, 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]], '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, 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, 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, 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, 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, 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, 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]]} # fmt: skip
+
+ self.tokenizer_integration_test_util(
+ expected_encoding=expected_encoding,
+ model_name="albert/albert-base-v2",
+ revision="6b6560eaf5ff2e250b00c50f380c5389a9c2d82e",
+ )
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/align/__init__.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/align/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/align/test_modeling_align.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/align/test_modeling_align.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc41929dca6087fa872bfca130cec6d72b3796f8
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/align/test_modeling_align.py
@@ -0,0 +1,654 @@
+# coding=utf-8
+# Copyright 2023 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.
+"""Testing suite for the PyTorch ALIGN model."""
+
+import inspect
+import os
+import tempfile
+import unittest
+
+import requests
+
+from transformers import AlignConfig, AlignProcessor, AlignTextConfig, AlignVisionConfig
+from transformers.testing_utils import (
+ require_torch,
+ require_vision,
+ slow,
+ torch_device,
+)
+from transformers.utils import is_torch_available, is_vision_available
+
+from ...test_configuration_common import ConfigTester
+from ...test_modeling_common import (
+ ModelTesterMixin,
+ _config_zero_init,
+ floats_tensor,
+ ids_tensor,
+ random_attention_mask,
+)
+from ...test_pipeline_mixin import PipelineTesterMixin
+
+
+if is_torch_available():
+ import torch
+
+ from transformers import (
+ AlignModel,
+ AlignTextModel,
+ AlignVisionModel,
+ )
+
+
+if is_vision_available():
+ from PIL import Image
+
+
+class AlignVisionModelTester:
+ def __init__(
+ self,
+ parent,
+ batch_size=12,
+ image_size=32,
+ num_channels=3,
+ kernel_sizes=[3, 3, 5],
+ in_channels=[32, 16, 24],
+ out_channels=[16, 24, 30],
+ hidden_dim=64,
+ strides=[1, 1, 2],
+ num_block_repeats=[1, 1, 2],
+ expand_ratios=[1, 6, 6],
+ is_training=True,
+ hidden_act="gelu",
+ ):
+ self.parent = parent
+ self.batch_size = batch_size
+ self.image_size = image_size
+ self.num_channels = num_channels
+ self.kernel_sizes = kernel_sizes
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.hidden_dim = hidden_dim
+ self.strides = strides
+ self.num_block_repeats = num_block_repeats
+ self.expand_ratios = expand_ratios
+ self.is_training = is_training
+ self.hidden_act = hidden_act
+
+ def prepare_config_and_inputs(self):
+ pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
+ config = self.get_config()
+
+ return config, pixel_values
+
+ def get_config(self):
+ return AlignVisionConfig(
+ num_channels=self.num_channels,
+ kernel_sizes=self.kernel_sizes,
+ in_channels=self.in_channels,
+ out_channels=self.out_channels,
+ hidden_dim=self.hidden_dim,
+ strides=self.strides,
+ num_block_repeats=self.num_block_repeats,
+ expand_ratios=self.expand_ratios,
+ hidden_act=self.hidden_act,
+ )
+
+ def create_and_check_model(self, config, pixel_values):
+ model = AlignVisionModel(config=config)
+ model.to(torch_device)
+ model.eval()
+ with torch.no_grad():
+ result = model(pixel_values)
+
+ patch_size = self.image_size // 4
+ self.parent.assertEqual(
+ result.last_hidden_state.shape, (self.batch_size, config.hidden_dim, patch_size, patch_size)
+ )
+ self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, config.hidden_dim))
+
+ def prepare_config_and_inputs_for_common(self):
+ config_and_inputs = self.prepare_config_and_inputs()
+ config, pixel_values = config_and_inputs
+ inputs_dict = {"pixel_values": pixel_values}
+ return config, inputs_dict
+
+
+@require_torch
+class AlignVisionModelTest(ModelTesterMixin, unittest.TestCase):
+ """
+ Here we also overwrite some of the tests of test_modeling_common.py, as ALIGN does not use input_ids, inputs_embeds,
+ attention_mask and seq_length.
+ """
+
+ all_model_classes = (AlignVisionModel,) if is_torch_available() else ()
+ fx_compatible = False
+ test_pruning = False
+ test_resize_embeddings = False
+ test_head_masking = False
+ has_attentions = False
+
+ def setUp(self):
+ self.model_tester = AlignVisionModelTester(self)
+ self.config_tester = ConfigTester(
+ self,
+ config_class=AlignVisionConfig,
+ has_text_modality=False,
+ hidden_size=37,
+ common_properties=["num_channels", "image_size"],
+ )
+
+ def test_config(self):
+ self.config_tester.run_common_tests()
+
+ @unittest.skip(reason="AlignVisionModel does not use inputs_embeds")
+ def test_inputs_embeds(self):
+ pass
+
+ @unittest.skip(reason="AlignVisionModel does not use inputs_embeds")
+ def test_inputs_embeds_matches_input_ids(self):
+ pass
+
+ @unittest.skip(reason="AlignVisionModel does not support input and output embeddings")
+ def test_model_get_set_embeddings(self):
+ pass
+
+ def test_forward_signature(self):
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+ signature = inspect.signature(model.forward)
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
+ arg_names = [*signature.parameters.keys()]
+
+ expected_arg_names = ["pixel_values"]
+ self.assertListEqual(arg_names[:1], expected_arg_names)
+
+ def test_model(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_model(*config_and_inputs)
+
+ def test_hidden_states_output(self):
+ def check_hidden_states_output(inputs_dict, config, model_class):
+ model = model_class(config)
+ model.to(torch_device)
+ model.eval()
+
+ with torch.no_grad():
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
+
+ hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
+ num_blocks = sum(config.num_block_repeats) * 4
+ self.assertEqual(len(hidden_states), num_blocks)
+
+ self.assertListEqual(
+ list(hidden_states[0].shape[-2:]),
+ [self.model_tester.image_size // 2, self.model_tester.image_size // 2],
+ )
+
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ inputs_dict["output_hidden_states"] = True
+ check_hidden_states_output(inputs_dict, config, model_class)
+
+ # check that output_hidden_states also work using config
+ del inputs_dict["output_hidden_states"]
+ config.output_hidden_states = True
+
+ check_hidden_states_output(inputs_dict, config, model_class)
+
+ @unittest.skip
+ def test_training(self):
+ pass
+
+ @unittest.skip
+ def test_training_gradient_checkpointing(self):
+ pass
+
+ @unittest.skip(
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
+ )
+ def test_training_gradient_checkpointing_use_reentrant(self):
+ pass
+
+ @unittest.skip(
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
+ )
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
+ pass
+
+ @slow
+ def test_model_from_pretrained(self):
+ model_name = "kakaobrain/align-base"
+ model = AlignVisionModel.from_pretrained(model_name)
+ self.assertIsNotNone(model)
+
+
+class AlignTextModelTester:
+ def __init__(
+ self,
+ parent,
+ batch_size=12,
+ seq_length=7,
+ is_training=True,
+ use_input_mask=True,
+ use_token_type_ids=True,
+ vocab_size=99,
+ hidden_size=32,
+ num_hidden_layers=2,
+ num_attention_heads=4,
+ intermediate_size=37,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.1,
+ attention_probs_dropout_prob=0.1,
+ max_position_embeddings=512,
+ type_vocab_size=16,
+ type_sequence_label_size=2,
+ initializer_range=0.02,
+ scope=None,
+ ):
+ self.parent = parent
+ self.batch_size = batch_size
+ self.seq_length = seq_length
+ self.is_training = is_training
+ self.use_input_mask = use_input_mask
+ self.use_token_type_ids = use_token_type_ids
+ self.vocab_size = vocab_size
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.intermediate_size = intermediate_size
+ self.hidden_act = hidden_act
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.max_position_embeddings = max_position_embeddings
+ self.type_vocab_size = type_vocab_size
+ self.type_sequence_label_size = type_sequence_label_size
+ self.initializer_range = initializer_range
+ self.scope = scope
+
+ def prepare_config_and_inputs(self):
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
+
+ input_mask = None
+ if self.use_input_mask:
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
+
+ token_type_ids = None
+ if self.use_token_type_ids:
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
+
+ config = self.get_config()
+
+ return config, input_ids, token_type_ids, input_mask
+
+ def get_config(self):
+ return AlignTextConfig(
+ vocab_size=self.vocab_size,
+ hidden_size=self.hidden_size,
+ num_hidden_layers=self.num_hidden_layers,
+ num_attention_heads=self.num_attention_heads,
+ intermediate_size=self.intermediate_size,
+ hidden_act=self.hidden_act,
+ hidden_dropout_prob=self.hidden_dropout_prob,
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
+ max_position_embeddings=self.max_position_embeddings,
+ type_vocab_size=self.type_vocab_size,
+ is_decoder=False,
+ initializer_range=self.initializer_range,
+ )
+
+ def create_and_check_model(self, config, input_ids, token_type_ids, input_mask):
+ model = AlignTextModel(config=config)
+ model.to(torch_device)
+ model.eval()
+ with torch.no_grad():
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
+ result = model(input_ids, token_type_ids=token_type_ids)
+ result = model(input_ids)
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
+ self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
+
+ def prepare_config_and_inputs_for_common(self):
+ config_and_inputs = self.prepare_config_and_inputs()
+ (
+ config,
+ input_ids,
+ token_type_ids,
+ input_mask,
+ ) = config_and_inputs
+ inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
+ return config, inputs_dict
+
+
+@require_torch
+class AlignTextModelTest(ModelTesterMixin, unittest.TestCase):
+ all_model_classes = (AlignTextModel,) if is_torch_available() else ()
+ fx_compatible = False
+ test_pruning = False
+ test_head_masking = False
+
+ def setUp(self):
+ self.model_tester = AlignTextModelTester(self)
+ self.config_tester = ConfigTester(self, config_class=AlignTextConfig, hidden_size=37)
+
+ def test_config(self):
+ self.config_tester.run_common_tests()
+
+ def test_model(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_model(*config_and_inputs)
+
+ @unittest.skip
+ def test_training(self):
+ pass
+
+ @unittest.skip
+ def test_training_gradient_checkpointing(self):
+ pass
+
+ @unittest.skip(
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
+ )
+ def test_training_gradient_checkpointing_use_reentrant(self):
+ pass
+
+ @unittest.skip(
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
+ )
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
+ pass
+
+ @unittest.skip(reason="ALIGN does not use inputs_embeds")
+ def test_inputs_embeds(self):
+ pass
+
+ @unittest.skip(reason="Align does not use inputs_embeds")
+ def test_inputs_embeds_matches_input_ids(self):
+ pass
+
+ @unittest.skip(reason="AlignTextModel has no base class and is not available in MODEL_MAPPING")
+ def test_save_load_fast_init_from_base(self):
+ pass
+
+ @unittest.skip(reason="AlignTextModel has no base class and is not available in MODEL_MAPPING")
+ def test_save_load_fast_init_to_base(self):
+ pass
+
+ @slow
+ def test_model_from_pretrained(self):
+ model_name = "kakaobrain/align-base"
+ model = AlignTextModel.from_pretrained(model_name)
+ self.assertIsNotNone(model)
+
+
+class AlignModelTester:
+ def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True):
+ if text_kwargs is None:
+ text_kwargs = {}
+ if vision_kwargs is None:
+ vision_kwargs = {}
+
+ self.parent = parent
+ self.text_model_tester = AlignTextModelTester(parent, **text_kwargs)
+ self.vision_model_tester = AlignVisionModelTester(parent, **vision_kwargs)
+ self.batch_size = self.text_model_tester.batch_size # need bs for batching_equivalence test
+ self.is_training = is_training
+
+ def prepare_config_and_inputs(self):
+ test_config, input_ids, token_type_ids, input_mask = self.text_model_tester.prepare_config_and_inputs()
+ vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs()
+
+ config = self.get_config()
+
+ return config, input_ids, token_type_ids, input_mask, pixel_values
+
+ def get_config(self):
+ return AlignConfig.from_text_vision_configs(
+ self.text_model_tester.get_config(), self.vision_model_tester.get_config(), projection_dim=64
+ )
+
+ def create_and_check_model(self, config, input_ids, token_type_ids, attention_mask, pixel_values):
+ model = AlignModel(config).to(torch_device).eval()
+ with torch.no_grad():
+ result = model(input_ids, pixel_values, attention_mask, token_type_ids)
+ self.parent.assertEqual(
+ result.logits_per_image.shape, (self.vision_model_tester.batch_size, self.text_model_tester.batch_size)
+ )
+ self.parent.assertEqual(
+ result.logits_per_text.shape, (self.text_model_tester.batch_size, self.vision_model_tester.batch_size)
+ )
+
+ def prepare_config_and_inputs_for_common(self):
+ config_and_inputs = self.prepare_config_and_inputs()
+ config, input_ids, token_type_ids, input_mask, pixel_values = config_and_inputs
+ inputs_dict = {
+ "input_ids": input_ids,
+ "token_type_ids": token_type_ids,
+ "attention_mask": input_mask,
+ "pixel_values": pixel_values,
+ "return_loss": True,
+ }
+ return config, inputs_dict
+
+
+@require_torch
+class AlignModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
+ all_model_classes = (AlignModel,) if is_torch_available() else ()
+ pipeline_model_mapping = {"feature-extraction": AlignModel} if is_torch_available() else {}
+ fx_compatible = False
+ test_head_masking = False
+ test_pruning = False
+ test_resize_embeddings = False
+ test_attention_outputs = False
+
+ def setUp(self):
+ self.model_tester = AlignModelTester(self)
+ self.config_tester = ConfigTester(
+ self,
+ config_class=AlignConfig,
+ has_text_modality=False,
+ common_properties=["projection_dim", "temperature_init_value"],
+ )
+
+ def test_model(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_model(*config_and_inputs)
+
+ def test_config(self):
+ self.config_tester.run_common_tests()
+
+ @unittest.skip(reason="Start to fail after using torch `cu118`.")
+ def test_multi_gpu_data_parallel_forward(self):
+ super().test_multi_gpu_data_parallel_forward()
+
+ @unittest.skip(reason="Hidden_states is tested in individual model tests")
+ def test_hidden_states_output(self):
+ pass
+
+ @unittest.skip(reason="Inputs_embeds is tested in individual model tests")
+ def test_inputs_embeds(self):
+ pass
+
+ @unittest.skip(reason="Align does not use inputs_embeds")
+ def test_inputs_embeds_matches_input_ids(self):
+ pass
+
+ @unittest.skip(reason="Retain_grad is tested in individual model tests")
+ def test_retain_grad_hidden_states_attentions(self):
+ pass
+
+ @unittest.skip(reason="AlignModel does not have input/output embeddings")
+ def test_model_get_set_embeddings(self):
+ pass
+
+ # override as the `temperature` parameter initilization is different for ALIGN
+ def test_initialization(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+
+ configs_no_init = _config_zero_init(config)
+ for model_class in self.all_model_classes:
+ model = model_class(config=configs_no_init)
+ for name, param in model.named_parameters():
+ if param.requires_grad:
+ # check if `temperature` is initilized as per the original implementation
+ if name == "temperature":
+ self.assertAlmostEqual(
+ param.data.item(),
+ 1.0,
+ delta=1e-3,
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
+ )
+ elif name == "text_projection.weight":
+ self.assertTrue(
+ -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0,
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
+ )
+ else:
+ self.assertIn(
+ ((param.data.mean() * 1e9).round() / 1e9).item(),
+ [0.0, 1.0],
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
+ )
+
+ def _create_and_check_torchscript(self, config, inputs_dict):
+ if not self.test_torchscript:
+ self.skipTest(reason="test_torchscript is set to False")
+
+ configs_no_init = _config_zero_init(config) # To be sure we have no Nan
+ configs_no_init.torchscript = True
+ configs_no_init.return_dict = False
+ for model_class in self.all_model_classes:
+ model = model_class(config=configs_no_init)
+ model.to(torch_device)
+ model.eval()
+
+ try:
+ input_ids = inputs_dict["input_ids"]
+ pixel_values = inputs_dict["pixel_values"] # ALIGN needs pixel_values
+ traced_model = torch.jit.trace(model, (input_ids, pixel_values))
+ except RuntimeError:
+ self.fail("Couldn't trace module.")
+
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
+ pt_file_name = os.path.join(tmp_dir_name, "traced_model.pt")
+
+ try:
+ torch.jit.save(traced_model, pt_file_name)
+ except Exception:
+ self.fail("Couldn't save module.")
+
+ try:
+ loaded_model = torch.jit.load(pt_file_name)
+ except Exception:
+ self.fail("Couldn't load module.")
+
+ model.to(torch_device)
+ model.eval()
+
+ loaded_model.to(torch_device)
+ loaded_model.eval()
+
+ model_state_dict = model.state_dict()
+ loaded_model_state_dict = loaded_model.state_dict()
+
+ non_persistent_buffers = {}
+ for key in loaded_model_state_dict.keys():
+ if key not in model_state_dict.keys():
+ non_persistent_buffers[key] = loaded_model_state_dict[key]
+
+ loaded_model_state_dict = {
+ key: value for key, value in loaded_model_state_dict.items() if key not in non_persistent_buffers
+ }
+
+ self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys()))
+
+ model_buffers = list(model.buffers())
+ for non_persistent_buffer in non_persistent_buffers.values():
+ found_buffer = False
+ for i, model_buffer in enumerate(model_buffers):
+ if torch.equal(non_persistent_buffer, model_buffer):
+ found_buffer = True
+ break
+
+ self.assertTrue(found_buffer)
+ model_buffers.pop(i)
+
+ models_equal = True
+ for layer_name, p1 in model_state_dict.items():
+ p2 = loaded_model_state_dict[layer_name]
+ if p1.data.ne(p2.data).sum() > 0:
+ models_equal = False
+
+ self.assertTrue(models_equal)
+
+ def test_load_vision_text_config(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+
+ # Save AlignConfig and check if we can load AlignVisionConfig from it
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
+ config.save_pretrained(tmp_dir_name)
+ vision_config = AlignVisionConfig.from_pretrained(tmp_dir_name)
+ self.assertDictEqual(config.vision_config.to_dict(), vision_config.to_dict())
+
+ # Save AlignConfig and check if we can load AlignTextConfig from it
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
+ config.save_pretrained(tmp_dir_name)
+ text_config = AlignTextConfig.from_pretrained(tmp_dir_name)
+ self.assertDictEqual(config.text_config.to_dict(), text_config.to_dict())
+
+ @slow
+ def test_model_from_pretrained(self):
+ model_name = "kakaobrain/align-base"
+ model = AlignModel.from_pretrained(model_name)
+ self.assertIsNotNone(model)
+
+
+# We will verify our results on an image of cute cats
+def prepare_img():
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ im = Image.open(requests.get(url, stream=True).raw)
+ return im
+
+
+@require_vision
+@require_torch
+class AlignModelIntegrationTest(unittest.TestCase):
+ @slow
+ def test_inference(self):
+ model_name = "kakaobrain/align-base"
+ model = AlignModel.from_pretrained(model_name).to(torch_device)
+ processor = AlignProcessor.from_pretrained(model_name)
+
+ image = prepare_img()
+ texts = ["a photo of a cat", "a photo of a dog"]
+ inputs = processor(images=image, text=texts, return_tensors="pt").to(torch_device)
+
+ # forward pass
+ with torch.no_grad():
+ outputs = model(**inputs)
+
+ # verify the logits
+ self.assertEqual(
+ outputs.logits_per_image.shape,
+ torch.Size((inputs.pixel_values.shape[0], inputs.input_ids.shape[0])),
+ )
+ self.assertEqual(
+ outputs.logits_per_text.shape,
+ torch.Size((inputs.input_ids.shape[0], inputs.pixel_values.shape[0])),
+ )
+ expected_logits = torch.tensor([[9.7093, 3.4679]], device=torch_device)
+ torch.testing.assert_close(outputs.logits_per_image, expected_logits, rtol=1e-3, atol=1e-3)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/align/test_processor_align.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/align/test_processor_align.py
new file mode 100644
index 0000000000000000000000000000000000000000..73e0d1df91f36381a2fc3444847b0e9cffcafd47
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/align/test_processor_align.py
@@ -0,0 +1,196 @@
+# Copyright 2023 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 shutil
+import tempfile
+import unittest
+
+import pytest
+
+from transformers import BertTokenizer, BertTokenizerFast
+from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES
+from transformers.testing_utils import require_vision
+from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available
+
+from ...test_processing_common import ProcessorTesterMixin
+
+
+if is_vision_available():
+ from transformers import AlignProcessor, EfficientNetImageProcessor
+
+
+@require_vision
+class AlignProcessorTest(ProcessorTesterMixin, unittest.TestCase):
+ processor_class = AlignProcessor
+
+ def setUp(self):
+ self.tmpdirname = tempfile.mkdtemp()
+
+ vocab_tokens = [
+ "[UNK]",
+ "[CLS]",
+ "[SEP]",
+ "[PAD]",
+ "[MASK]",
+ "want",
+ "##want",
+ "##ed",
+ "wa",
+ "un",
+ "runn",
+ "##ing",
+ ",",
+ "low",
+ "lowest",
+ ]
+ self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"])
+ with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer:
+ vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
+
+ image_processor_map = {
+ "do_resize": True,
+ "size": 20,
+ "do_normalize": True,
+ "image_mean": [0.48145466, 0.4578275, 0.40821073],
+ "image_std": [0.26862954, 0.26130258, 0.27577711],
+ }
+ self.image_processor_file = os.path.join(self.tmpdirname, IMAGE_PROCESSOR_NAME)
+ with open(self.image_processor_file, "w", encoding="utf-8") as fp:
+ json.dump(image_processor_map, fp)
+
+ def get_tokenizer(self, **kwargs):
+ return BertTokenizer.from_pretrained(self.tmpdirname, **kwargs)
+
+ def get_rust_tokenizer(self, **kwargs):
+ return BertTokenizerFast.from_pretrained(self.tmpdirname, **kwargs)
+
+ def get_image_processor(self, **kwargs):
+ return EfficientNetImageProcessor.from_pretrained(self.tmpdirname, **kwargs)
+
+ def tearDown(self):
+ shutil.rmtree(self.tmpdirname)
+
+ def test_save_load_pretrained_default(self):
+ tokenizer_slow = self.get_tokenizer()
+ tokenizer_fast = self.get_rust_tokenizer()
+ image_processor = self.get_image_processor()
+
+ processor_slow = AlignProcessor(tokenizer=tokenizer_slow, image_processor=image_processor)
+ processor_slow.save_pretrained(self.tmpdirname)
+ processor_slow = AlignProcessor.from_pretrained(self.tmpdirname, use_fast=False)
+
+ processor_fast = AlignProcessor(tokenizer=tokenizer_fast, image_processor=image_processor)
+ processor_fast.save_pretrained(self.tmpdirname)
+ processor_fast = AlignProcessor.from_pretrained(self.tmpdirname)
+
+ self.assertEqual(processor_slow.tokenizer.get_vocab(), tokenizer_slow.get_vocab())
+ self.assertEqual(processor_fast.tokenizer.get_vocab(), tokenizer_fast.get_vocab())
+ self.assertEqual(tokenizer_slow.get_vocab(), tokenizer_fast.get_vocab())
+ self.assertIsInstance(processor_slow.tokenizer, BertTokenizer)
+ self.assertIsInstance(processor_fast.tokenizer, BertTokenizerFast)
+
+ self.assertEqual(processor_slow.image_processor.to_json_string(), image_processor.to_json_string())
+ self.assertEqual(processor_fast.image_processor.to_json_string(), image_processor.to_json_string())
+ self.assertIsInstance(processor_slow.image_processor, EfficientNetImageProcessor)
+ self.assertIsInstance(processor_fast.image_processor, EfficientNetImageProcessor)
+
+ def test_save_load_pretrained_additional_features(self):
+ processor = AlignProcessor(tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor())
+ processor.save_pretrained(self.tmpdirname)
+
+ tokenizer_add_kwargs = self.get_tokenizer(bos_token="(BOS)", eos_token="(EOS)")
+ image_processor_add_kwargs = self.get_image_processor(do_normalize=False, padding_value=1.0)
+
+ processor = AlignProcessor.from_pretrained(
+ self.tmpdirname, bos_token="(BOS)", eos_token="(EOS)", do_normalize=False, padding_value=1.0
+ )
+
+ self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab())
+ self.assertIsInstance(processor.tokenizer, BertTokenizerFast)
+
+ self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string())
+ self.assertIsInstance(processor.image_processor, EfficientNetImageProcessor)
+
+ def test_image_processor(self):
+ image_processor = self.get_image_processor()
+ tokenizer = self.get_tokenizer()
+
+ processor = AlignProcessor(tokenizer=tokenizer, image_processor=image_processor)
+
+ image_input = self.prepare_image_inputs()
+
+ input_image_proc = image_processor(image_input, return_tensors="np")
+ input_processor = processor(images=image_input, return_tensors="np")
+
+ for key in input_image_proc.keys():
+ self.assertAlmostEqual(input_image_proc[key].sum(), input_processor[key].sum(), delta=1e-2)
+
+ def test_tokenizer(self):
+ image_processor = self.get_image_processor()
+ tokenizer = self.get_tokenizer()
+
+ processor = AlignProcessor(tokenizer=tokenizer, image_processor=image_processor)
+
+ input_str = "lower newer"
+
+ encoded_processor = processor(text=input_str)
+
+ encoded_tok = tokenizer(input_str, padding="max_length", max_length=64)
+ for key in encoded_tok.keys():
+ self.assertListEqual(encoded_tok[key], encoded_processor[key])
+
+ def test_processor(self):
+ image_processor = self.get_image_processor()
+ tokenizer = self.get_tokenizer()
+
+ processor = AlignProcessor(tokenizer=tokenizer, image_processor=image_processor)
+
+ input_str = "lower newer"
+ image_input = self.prepare_image_inputs()
+
+ inputs = processor(text=input_str, images=image_input)
+
+ self.assertListEqual(list(inputs.keys()), ["input_ids", "token_type_ids", "attention_mask", "pixel_values"])
+
+ # test if it raises when no input is passed
+ with pytest.raises(ValueError):
+ processor()
+
+ def test_tokenizer_decode(self):
+ image_processor = self.get_image_processor()
+ tokenizer = self.get_tokenizer()
+
+ processor = AlignProcessor(tokenizer=tokenizer, image_processor=image_processor)
+
+ predicted_ids = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
+
+ decoded_processor = processor.batch_decode(predicted_ids)
+ decoded_tok = tokenizer.batch_decode(predicted_ids)
+
+ self.assertListEqual(decoded_tok, decoded_processor)
+
+ def test_model_input_names(self):
+ image_processor = self.get_image_processor()
+ tokenizer = self.get_tokenizer()
+
+ processor = AlignProcessor(tokenizer=tokenizer, image_processor=image_processor)
+
+ input_str = "lower newer"
+ image_input = self.prepare_image_inputs()
+
+ inputs = processor(text=input_str, images=image_input)
+
+ self.assertListEqual(list(inputs.keys()), processor.model_input_names)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/altclip/__init__.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/altclip/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/altclip/test_modeling_altclip.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/altclip/test_modeling_altclip.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fadadf4a76dcc252a0ef9db3c3e9b66b77b61f9
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/altclip/test_modeling_altclip.py
@@ -0,0 +1,656 @@
+# 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.
+"""Testing suite for the PyTorch AltCLIP model."""
+
+import inspect
+import os
+import tempfile
+import unittest
+
+import numpy as np
+import requests
+
+from transformers import AltCLIPConfig, AltCLIPProcessor, AltCLIPTextConfig, AltCLIPVisionConfig
+from transformers.testing_utils import require_torch, require_vision, slow, torch_device
+from transformers.utils import is_torch_available, is_vision_available
+
+from ...test_configuration_common import ConfigTester
+from ...test_modeling_common import (
+ ModelTesterMixin,
+ _config_zero_init,
+ floats_tensor,
+ ids_tensor,
+ random_attention_mask,
+)
+from ...test_pipeline_mixin import PipelineTesterMixin
+
+
+if is_torch_available():
+ import torch
+ import torch.nn as nn
+
+ from transformers import AltCLIPModel, AltCLIPTextModel, AltCLIPVisionModel
+
+if is_vision_available():
+ from PIL import Image
+
+
+class AltCLIPVisionModelTester:
+ def __init__(
+ self,
+ parent,
+ batch_size=12,
+ image_size=30,
+ patch_size=2,
+ num_channels=3,
+ is_training=True,
+ hidden_size=32,
+ projection_dim=32,
+ num_hidden_layers=2,
+ num_attention_heads=4,
+ intermediate_size=37,
+ dropout=0.1,
+ attention_dropout=0.1,
+ initializer_range=0.02,
+ scope=None,
+ ):
+ self.parent = parent
+ self.batch_size = batch_size
+ self.image_size = image_size
+ self.patch_size = patch_size
+ self.num_channels = num_channels
+ self.is_training = is_training
+ self.hidden_size = hidden_size
+ self.projection_dim = projection_dim
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.intermediate_size = intermediate_size
+ self.dropout = dropout
+ self.attention_dropout = attention_dropout
+ self.initializer_range = initializer_range
+ self.scope = scope
+
+ # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
+ num_patches = (image_size // patch_size) ** 2
+ self.seq_length = num_patches + 1
+
+ def prepare_config_and_inputs(self):
+ pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
+ config = self.get_config()
+
+ return config, pixel_values
+
+ def get_config(self):
+ return AltCLIPVisionConfig(
+ image_size=self.image_size,
+ patch_size=self.patch_size,
+ num_channels=self.num_channels,
+ hidden_size=self.hidden_size,
+ projection_dim=self.projection_dim,
+ num_hidden_layers=self.num_hidden_layers,
+ num_attention_heads=self.num_attention_heads,
+ intermediate_size=self.intermediate_size,
+ dropout=self.dropout,
+ attention_dropout=self.attention_dropout,
+ initializer_range=self.initializer_range,
+ )
+
+ def create_and_check_model(self, config, pixel_values):
+ model = AltCLIPVisionModel(config=config)
+ model.to(torch_device)
+ model.eval()
+ with torch.no_grad():
+ result = model(pixel_values)
+ # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
+ image_size = (self.image_size, self.image_size)
+ patch_size = (self.patch_size, self.patch_size)
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size))
+ self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
+
+ def prepare_config_and_inputs_for_common(self):
+ config_and_inputs = self.prepare_config_and_inputs()
+ config, pixel_values = config_and_inputs
+ inputs_dict = {"pixel_values": pixel_values}
+ return config, inputs_dict
+
+
+@require_torch
+class AltCLIPVisionModelTest(ModelTesterMixin, unittest.TestCase):
+ """
+ Here we also overwrite some of the tests of test_modeling_common.py, as CLIP does not use input_ids, inputs_embeds,
+ attention_mask and seq_length.
+ """
+
+ all_model_classes = (AltCLIPVisionModel,) if is_torch_available() else ()
+ fx_compatible = False
+ test_pruning = False
+ test_resize_embeddings = False
+ test_head_masking = False
+
+ def setUp(self):
+ self.model_tester = AltCLIPVisionModelTester(self)
+ self.config_tester = ConfigTester(
+ self, config_class=AltCLIPVisionConfig, has_text_modality=False, hidden_size=37
+ )
+
+ def test_config(self):
+ self.config_tester.run_common_tests()
+
+ @unittest.skip(reason="CLIP does not use inputs_embeds")
+ def test_inputs_embeds(self):
+ pass
+
+ def test_model_get_set_embeddings(self):
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+ self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
+ x = model.get_output_embeddings()
+ self.assertTrue(x is None or isinstance(x, nn.Linear))
+
+ def test_forward_signature(self):
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+ signature = inspect.signature(model.forward)
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
+ arg_names = [*signature.parameters.keys()]
+
+ expected_arg_names = ["pixel_values"]
+ self.assertListEqual(arg_names[:1], expected_arg_names)
+
+ def test_model(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_model(*config_and_inputs)
+
+ @unittest.skip
+ def test_training(self):
+ pass
+
+ @unittest.skip
+ def test_training_gradient_checkpointing(self):
+ pass
+
+ @unittest.skip(
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
+ )
+ def test_training_gradient_checkpointing_use_reentrant(self):
+ pass
+
+ @unittest.skip(
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
+ )
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
+ pass
+
+ @unittest.skip(reason="AltCLIPVisionModel has no base class and is not available in MODEL_MAPPING")
+ def test_save_load_fast_init_from_base(self):
+ pass
+
+ @unittest.skip(reason="AltCLIPVisionModel has no base class and is not available in MODEL_MAPPING")
+ def test_save_load_fast_init_to_base(self):
+ pass
+
+ @unittest.skip(reason="AltCLIPVisionModel use the same cv backbone with CLIP model.")
+ def test_model_from_pretrained(self):
+ pass
+
+
+class AltCLIPTextModelTester:
+ def __init__(
+ self,
+ parent,
+ batch_size=12,
+ seq_length=7,
+ is_training=True,
+ use_input_mask=True,
+ use_labels=True,
+ vocab_size=99,
+ hidden_size=32,
+ projection_dim=32,
+ project_dim=32,
+ num_hidden_layers=2,
+ num_attention_heads=4,
+ intermediate_size=37,
+ dropout=0.1,
+ attention_dropout=0.1,
+ max_position_embeddings=512,
+ initializer_range=0.02,
+ scope=None,
+ ):
+ self.parent = parent
+ self.batch_size = batch_size
+ self.seq_length = seq_length
+ self.is_training = is_training
+ self.use_input_mask = use_input_mask
+ self.use_labels = use_labels
+ self.vocab_size = vocab_size
+ self.hidden_size = hidden_size
+ self.projection_dim = projection_dim
+ self.project_dim = project_dim
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.intermediate_size = intermediate_size
+ self.dropout = dropout
+ self.attention_dropout = attention_dropout
+ self.max_position_embeddings = max_position_embeddings
+ self.initializer_range = initializer_range
+ self.scope = scope
+
+ def prepare_config_and_inputs(self):
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
+
+ input_mask = None
+ if self.use_input_mask:
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
+
+ if input_mask is not None:
+ batch_size, seq_length = input_mask.shape
+ rnd_start_indices = np.random.randint(1, seq_length - 1, size=(batch_size,))
+ for batch_idx, start_index in enumerate(rnd_start_indices):
+ input_mask[batch_idx, :start_index] = 1
+ input_mask[batch_idx, start_index:] = 0
+
+ config = self.get_config()
+
+ return config, input_ids, input_mask
+
+ def get_config(self):
+ return AltCLIPTextConfig(
+ vocab_size=self.vocab_size,
+ hidden_size=self.hidden_size,
+ projection_dim=self.projection_dim,
+ project_dim=self.project_dim,
+ num_hidden_layers=self.num_hidden_layers,
+ num_attention_heads=self.num_attention_heads,
+ intermediate_size=self.intermediate_size,
+ dropout=self.dropout,
+ attention_dropout=self.attention_dropout,
+ max_position_embeddings=self.max_position_embeddings,
+ initializer_range=self.initializer_range,
+ pad_token_id=1,
+ )
+
+ def create_and_check_model(self, config, input_ids, input_mask):
+ model = AltCLIPTextModel(config=config)
+ model.to(torch_device)
+ model.eval()
+ with torch.no_grad():
+ result = model(input_ids, attention_mask=input_mask)
+ result = model(input_ids)
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
+ self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.projection_dim))
+
+ def prepare_config_and_inputs_for_common(self):
+ config_and_inputs = self.prepare_config_and_inputs()
+ config, input_ids, input_mask = config_and_inputs
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
+ return config, inputs_dict
+
+
+@require_torch
+class AltCLIPTextModelTest(ModelTesterMixin, unittest.TestCase):
+ all_model_classes = (AltCLIPTextModel,) if is_torch_available() else ()
+ fx_compatible = True
+ test_pruning = False
+ test_head_masking = False
+
+ # TODO (@SunMarc): Fix me
+ @unittest.skip(reason="It's broken.")
+ def test_resize_tokens_embeddings(self):
+ super().test_resize_tokens_embeddings()
+
+ def setUp(self):
+ self.model_tester = AltCLIPTextModelTester(self)
+ self.config_tester = ConfigTester(self, config_class=AltCLIPTextConfig, hidden_size=37)
+
+ def test_config(self):
+ self.config_tester.run_common_tests()
+
+ def test_model(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_model(*config_and_inputs)
+
+ @unittest.skip
+ def test_training(self):
+ pass
+
+ @unittest.skip
+ def test_training_gradient_checkpointing(self):
+ pass
+
+ @unittest.skip(
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
+ )
+ def test_training_gradient_checkpointing_use_reentrant(self):
+ pass
+
+ @unittest.skip(
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
+ )
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
+ pass
+
+ def test_model_outputs_equivalence(self):
+ pass
+
+ @unittest.skip(reason="Result of the model is a dict")
+ def test_hidden_states_output(self):
+ pass
+
+ @unittest.skip(reason="AltCLIP does not use inputs_embeds")
+ def test_inputs_embeds(self):
+ pass
+
+ @unittest.skip(reason="AltCLIPTextModel has no base class and is not available in MODEL_MAPPING")
+ def test_save_load_fast_init_from_base(self):
+ pass
+
+ @unittest.skip(reason="AltCLIPTextModel has no base class and is not available in MODEL_MAPPING")
+ def test_save_load_fast_init_to_base(self):
+ pass
+
+ @slow
+ def test_model_from_pretrained(self):
+ model_name = "BAAI/AltCLIP"
+ model = AltCLIPTextModel.from_pretrained(model_name)
+ self.assertIsNotNone(model)
+
+
+class AltCLIPModelTester:
+ def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True):
+ if text_kwargs is None:
+ text_kwargs = {}
+ if vision_kwargs is None:
+ vision_kwargs = {}
+
+ self.parent = parent
+ self.text_model_tester = AltCLIPTextModelTester(parent, **text_kwargs)
+ self.vision_model_tester = AltCLIPVisionModelTester(parent, **vision_kwargs)
+ self.batch_size = self.text_model_tester.batch_size # need bs for batching_equivalence test
+ self.is_training = is_training
+
+ def prepare_config_and_inputs(self):
+ text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs()
+ vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs()
+
+ config = self.get_config()
+ return config, input_ids, attention_mask, pixel_values
+
+ def get_config(self):
+ return AltCLIPConfig.from_text_vision_configs(
+ self.text_model_tester.get_config(), self.vision_model_tester.get_config(), projection_dim=64
+ )
+
+ def create_and_check_model(self, config, input_ids, attention_mask, pixel_values):
+ model = AltCLIPModel(config=config)
+ model.to(torch_device)
+ model.eval()
+
+ with torch.no_grad():
+ model(input_ids, pixel_values, attention_mask)
+
+ def prepare_config_and_inputs_for_common(self):
+ config_and_inputs = self.prepare_config_and_inputs()
+ config, input_ids, attention_mask, pixel_values = config_and_inputs
+ inputs_dict = {
+ "input_ids": input_ids,
+ "attention_mask": attention_mask,
+ "pixel_values": pixel_values,
+ "return_loss": True,
+ }
+ return config, inputs_dict
+
+
+# We will verify our results on an image of cute cats
+def prepare_img():
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ im = Image.open(requests.get(url, stream=True).raw)
+ return im
+
+
+@require_torch
+class AltCLIPModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
+ all_model_classes = (AltCLIPModel,) if is_torch_available() else ()
+ pipeline_model_mapping = {"feature-extraction": AltCLIPModel} if is_torch_available() else {}
+ fx_compatible = True
+ test_head_masking = False
+ test_pruning = False
+ test_resize_embeddings = False
+ test_attention_outputs = False
+
+ # TODO: Fix the failed tests when this model gets more usage
+ def is_pipeline_test_to_skip(
+ self,
+ pipeline_test_case_name,
+ config_class,
+ model_architecture,
+ tokenizer_name,
+ image_processor_name,
+ feature_extractor_name,
+ processor_name,
+ ):
+ if pipeline_test_case_name == "FeatureExtractionPipelineTests":
+ return True
+
+ return False
+
+ def setUp(self):
+ self.model_tester = AltCLIPModelTester(self)
+ self.config_tester = ConfigTester(
+ self,
+ config_class=AltCLIPConfig,
+ has_text_modality=False,
+ common_properties=["projection_dim", "logit_scale_init_value"],
+ )
+
+ def test_model(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_model(*config_and_inputs)
+
+ def test_config(self):
+ self.config_tester.run_common_tests()
+
+ @unittest.skip(reason="Hidden_states is tested in individual model tests")
+ def test_hidden_states_output(self):
+ pass
+
+ @unittest.skip(reason="Inputs_embeds is tested in individual model tests")
+ def test_inputs_embeds(self):
+ pass
+
+ @unittest.skip(reason="Retain_grad is tested in individual model tests")
+ def test_retain_grad_hidden_states_attentions(self):
+ pass
+
+ @unittest.skip(reason="CLIPModel does not have input/output embeddings")
+ def test_model_get_set_embeddings(self):
+ pass
+
+ # override as the `logit_scale` parameter initilization is different for AltCLIP
+ def test_initialization(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+ configs_no_init = _config_zero_init(config)
+ for model_class in self.all_model_classes:
+ model = model_class(config=configs_no_init)
+ for name, param in model.named_parameters():
+ if param.requires_grad:
+ # check if `logit_scale` is initilized as per the original implementation
+ if name == "logit_scale":
+ self.assertAlmostEqual(
+ param.data.item(),
+ np.log(1 / 0.07),
+ delta=1e-3,
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
+ )
+ else:
+ self.assertIn(
+ ((param.data.mean() * 1e9).round() / 1e9).item(),
+ [0.0, 1.0],
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
+ )
+
+ def _create_and_check_torchscript(self, config, inputs_dict):
+ if not self.test_torchscript:
+ self.skipTest(reason="test_torchscript is set to False")
+
+ configs_no_init = _config_zero_init(config) # To be sure we have no Nan
+ configs_no_init.torchscript = True
+ configs_no_init.return_dict = False
+ for model_class in self.all_model_classes:
+ model = model_class(config=configs_no_init)
+ model.to(torch_device)
+ model.eval()
+
+ try:
+ input_ids = inputs_dict["input_ids"]
+ pixel_values = inputs_dict["pixel_values"] # CLIP needs pixel_values
+ traced_model = torch.jit.trace(model, (input_ids, pixel_values))
+ except RuntimeError:
+ self.fail("Couldn't trace module.")
+
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
+ pt_file_name = os.path.join(tmp_dir_name, "traced_model.pt")
+
+ try:
+ torch.jit.save(traced_model, pt_file_name)
+ except Exception:
+ self.fail("Couldn't save module.")
+
+ try:
+ loaded_model = torch.jit.load(pt_file_name)
+ except Exception:
+ self.fail("Couldn't load module.")
+
+ model.to(torch_device)
+ model.eval()
+
+ loaded_model.to(torch_device)
+ loaded_model.eval()
+
+ model_state_dict = model.state_dict()
+ loaded_model_state_dict = loaded_model.state_dict()
+
+ non_persistent_buffers = {}
+ for key in loaded_model_state_dict.keys():
+ if key not in model_state_dict.keys():
+ non_persistent_buffers[key] = loaded_model_state_dict[key]
+
+ loaded_model_state_dict = {
+ key: value for key, value in loaded_model_state_dict.items() if key not in non_persistent_buffers
+ }
+
+ self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys()))
+
+ model_buffers = list(model.buffers())
+ for non_persistent_buffer in non_persistent_buffers.values():
+ found_buffer = False
+ for i, model_buffer in enumerate(model_buffers):
+ if torch.equal(non_persistent_buffer, model_buffer):
+ found_buffer = True
+ break
+
+ self.assertTrue(found_buffer)
+ model_buffers.pop(i)
+
+ models_equal = True
+ for layer_name, p1 in model_state_dict.items():
+ p2 = loaded_model_state_dict[layer_name]
+ if p1.data.ne(p2.data).sum() > 0:
+ models_equal = False
+
+ self.assertTrue(models_equal)
+
+ @slow
+ def test_model_from_pretrained(self):
+ model_name = "BAAI/AltCLIP"
+ model = AltCLIPModel.from_pretrained(model_name)
+ self.assertIsNotNone(model)
+
+
+@require_vision
+@require_torch
+class AltCLIPModelIntegrationTest(unittest.TestCase):
+ @slow
+ def test_inference(self):
+ model_name = "BAAI/AltCLIP"
+ model = AltCLIPModel.from_pretrained(model_name).to(torch_device)
+ processor = AltCLIPProcessor.from_pretrained(model_name)
+
+ image = prepare_img()
+ inputs = processor(text=["一张猫的照片", "一张狗的照片"], images=image, padding=True, return_tensors="pt").to(torch_device) # fmt: skip
+
+ # forward pass
+ with torch.no_grad():
+ outputs = model(**inputs)
+
+ # verify the logits
+ self.assertEqual(
+ outputs.logits_per_image.shape,
+ torch.Size((inputs.pixel_values.shape[0], inputs.input_ids.shape[0])),
+ )
+ self.assertEqual(
+ outputs.logits_per_text.shape,
+ torch.Size((inputs.input_ids.shape[0], inputs.pixel_values.shape[0])),
+ )
+
+ probs = outputs.logits_per_image.softmax(dim=1)
+ expected_probs = torch.tensor([[9.9942e-01, 5.7805e-04]], device=torch_device)
+
+ torch.testing.assert_close(probs, expected_probs, rtol=5e-3, atol=5e-3)
+
+ @slow
+ def test_inference_interpolate_pos_encoding(self):
+ # ViT models have an `interpolate_pos_encoding` argument in their forward method,
+ # allowing to interpolate the pre-trained position embeddings in order to use
+ # the model on higher resolutions. The DINO model by Facebook AI leverages this
+ # to visualize self-attention on higher resolution images.
+ model_name = "BAAI/AltCLIP"
+ model = AltCLIPModel.from_pretrained(model_name).to(torch_device)
+
+ image_processor = AltCLIPProcessor.from_pretrained(
+ model_name, size={"shortest_edge": 180}, crop_size={"height": 180, "width": 180}
+ )
+
+ image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
+ inputs = image_processor(text="what's in the image", images=image, return_tensors="pt").to(torch_device)
+
+ # interpolate_pos_encodiung false should return value error
+ with self.assertRaises(ValueError, msg="doesn't match model"):
+ with torch.no_grad():
+ model(**inputs, interpolate_pos_encoding=False)
+
+ # forward pass
+ with torch.no_grad():
+ outputs = model(**inputs, interpolate_pos_encoding=True)
+
+ # verify the logits
+ expected_shape = torch.Size((1, 145, 1024))
+ print("nilesh ")
+ print(outputs.vision_model_output.last_hidden_state.shape)
+ print(outputs.vision_model_output.last_hidden_state[0, :3, :3])
+
+ self.assertEqual(outputs.vision_model_output.last_hidden_state.shape, expected_shape)
+
+ expected_slice = torch.tensor(
+ [[-0.3589, -0.5939, 0.3534], [0.4346, 0.1647, 0.7071], [1.1404, -0.4716, 0.1664]]
+ ).to(torch_device)
+
+ torch.testing.assert_close(
+ outputs.vision_model_output.last_hidden_state[0, :3, :3], expected_slice, rtol=1e-4, atol=1e-4
+ )
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/altclip/test_processor_altclip.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/altclip/test_processor_altclip.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b290efb1150310f19347fff01107c395fe14672
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/altclip/test_processor_altclip.py
@@ -0,0 +1,47 @@
+# 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 tempfile
+import unittest
+
+from transformers import AltCLIPProcessor, CLIPImageProcessor, XLMRobertaTokenizer, XLMRobertaTokenizerFast
+from transformers.testing_utils import require_vision
+
+from ...test_processing_common import ProcessorTesterMixin
+
+
+@require_vision
+class AltClipProcessorTest(ProcessorTesterMixin, unittest.TestCase):
+ processor_class = AltCLIPProcessor
+
+ def setUp(self):
+ self.model_id = "BAAI/AltCLIP"
+ self.tmpdirname = tempfile.mkdtemp()
+ image_processor = CLIPImageProcessor()
+ tokenizer = XLMRobertaTokenizer.from_pretrained(self.model_id)
+
+ processor = self.processor_class(image_processor, tokenizer)
+
+ processor.save_pretrained(self.tmpdirname)
+
+ def get_tokenizer(self, **kwargs):
+ return XLMRobertaTokenizer.from_pretrained(self.model_id, **kwargs)
+
+ def get_rust_tokenizer(self, **kwargs):
+ return XLMRobertaTokenizerFast.from_pretrained(self.model_id, **kwargs)
+
+ def get_image_processor(self, **kwargs):
+ return CLIPImageProcessor.from_pretrained(self.model_id, **kwargs)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/aria/__init__.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/aria/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/aria/test_image_processing_aria.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/aria/test_image_processing_aria.py
new file mode 100644
index 0000000000000000000000000000000000000000..255903e4077e4f75986c01d2845c0bbbfb16a054
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/aria/test_image_processing_aria.py
@@ -0,0 +1,267 @@
+# coding=utf-8
+# Copyright 2024 HuggingFace Inc.
+#
+# 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 unittest
+
+import numpy as np
+
+from transformers.image_utils import PILImageResampling
+from transformers.testing_utils import require_torch, require_vision
+from transformers.utils import is_torch_available, is_vision_available
+
+from ...test_image_processing_common import ImageProcessingTestMixin
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from transformers import AriaImageProcessor
+
+
+if is_torch_available():
+ import torch
+
+
+class AriaImageProcessingTester:
+ def __init__(
+ self,
+ parent,
+ batch_size=7,
+ num_channels=3,
+ num_images=1,
+ min_resolution=30,
+ max_resolution=40,
+ size=None,
+ max_image_size=980,
+ min_image_size=336,
+ split_resolutions=None,
+ split_image=True,
+ do_normalize=True,
+ image_mean=[0.5, 0.5, 0.5],
+ image_std=[0.5, 0.5, 0.5],
+ do_convert_rgb=True,
+ resample=PILImageResampling.BICUBIC,
+ ):
+ self.size = size if size is not None else {"longest_edge": max_resolution}
+ self.parent = parent
+ self.batch_size = batch_size
+ self.num_channels = num_channels
+ self.num_images = num_images
+ self.min_resolution = min_resolution
+ self.max_resolution = max_resolution
+ self.resample = resample
+ self.max_image_size = max_image_size
+ self.min_image_size = min_image_size
+ self.split_resolutions = split_resolutions if split_resolutions is not None else [[980, 980]]
+ self.split_image = split_image
+ self.do_normalize = do_normalize
+ self.image_mean = image_mean
+ self.image_std = image_std
+ self.do_convert_rgb = do_convert_rgb
+
+ def prepare_image_processor_dict(self):
+ return {
+ "image_mean": self.image_mean,
+ "image_std": self.image_std,
+ "max_image_size": self.max_image_size,
+ "min_image_size": self.min_image_size,
+ "split_resolutions": self.split_resolutions,
+ "split_image": self.split_image,
+ "do_convert_rgb": self.do_convert_rgb,
+ "do_normalize": self.do_normalize,
+ "resample": self.resample,
+ }
+
+ def get_expected_values(self, image_inputs, batched=False):
+ """
+ This function computes the expected height and width when providing images to AriaImageProcessor,
+ assuming do_resize is set to True. The expected size in that case the max image size.
+ """
+ return self.max_image_size, self.max_image_size
+
+ def expected_output_image_shape(self, images):
+ height, width = self.get_expected_values(images, batched=True)
+ return self.num_channels, height, width
+
+ def prepare_image_inputs(
+ self,
+ batch_size=None,
+ min_resolution=None,
+ max_resolution=None,
+ num_channels=None,
+ num_images=None,
+ size_divisor=None,
+ equal_resolution=False,
+ numpify=False,
+ torchify=False,
+ ):
+ """This function prepares a list of PIL images, or a list of numpy arrays if one specifies numpify=True,
+ or a list of PyTorch tensors if one specifies torchify=True.
+
+ One can specify whether the images are of the same resolution or not.
+ """
+ assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"
+
+ batch_size = batch_size if batch_size is not None else self.batch_size
+ min_resolution = min_resolution if min_resolution is not None else self.min_resolution
+ max_resolution = max_resolution if max_resolution is not None else self.max_resolution
+ num_channels = num_channels if num_channels is not None else self.num_channels
+ num_images = num_images if num_images is not None else self.num_images
+
+ images_list = []
+ for i in range(batch_size):
+ images = []
+ for j in range(num_images):
+ if equal_resolution:
+ width = height = max_resolution
+ else:
+ # To avoid getting image width/height 0
+ if size_divisor is not None:
+ # If `size_divisor` is defined, the image needs to have width/size >= `size_divisor`
+ min_resolution = max(size_divisor, min_resolution)
+ width, height = np.random.choice(np.arange(min_resolution, max_resolution), 2)
+ images.append(np.random.randint(255, size=(num_channels, width, height), dtype=np.uint8))
+ images_list.append(images)
+
+ if not numpify and not torchify:
+ # PIL expects the channel dimension as last dimension
+ images_list = [[Image.fromarray(np.moveaxis(image, 0, -1)) for image in images] for images in images_list]
+
+ if torchify:
+ images_list = [[torch.from_numpy(image) for image in images] for images in images_list]
+
+ if numpify:
+ # Numpy images are typically in channels last format
+ images_list = [[image.transpose(1, 2, 0) for image in images] for images in images_list]
+
+ return images_list
+
+
+@require_torch
+@require_vision
+class AriaImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
+ image_processing_class = AriaImageProcessor if is_vision_available() else None
+
+ def setUp(self):
+ super().setUp()
+ self.image_processor_tester = AriaImageProcessingTester(self)
+
+ @property
+ def image_processor_dict(self):
+ return self.image_processor_tester.prepare_image_processor_dict()
+
+ def test_image_processor_properties(self):
+ image_processing = self.image_processing_class(**self.image_processor_dict)
+ self.assertTrue(hasattr(image_processing, "do_convert_rgb"))
+ self.assertTrue(hasattr(image_processing, "max_image_size"))
+ self.assertTrue(hasattr(image_processing, "min_image_size"))
+ self.assertTrue(hasattr(image_processing, "do_normalize"))
+ self.assertTrue(hasattr(image_processing, "image_mean"))
+ self.assertTrue(hasattr(image_processing, "image_std"))
+ self.assertTrue(hasattr(image_processing, "split_image"))
+
+ def test_call_numpy(self):
+ for image_processing_class in self.image_processor_list:
+ # Initialize image_processing
+ image_processing = self.image_processing_class(**self.image_processor_dict)
+ # create random numpy tensors
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True)
+ for sample_images in image_inputs:
+ for image in sample_images:
+ self.assertIsInstance(image, np.ndarray)
+
+ # Test not batched input
+ encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]])
+ self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape))
+
+ # Test batched
+ encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs)
+ self.assertEqual(
+ tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape)
+ )
+
+ def test_call_numpy_4_channels(self):
+ # Aria always processes images as RGB, so it always returns images with 3 channels
+ for image_processing_class in self.image_processor_list:
+ # Initialize image_processing
+ image_processor_dict = self.image_processor_dict
+ image_processing = self.image_processing_class(**image_processor_dict)
+ # create random numpy tensors
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True)
+
+ for sample_images in image_inputs:
+ for image in sample_images:
+ self.assertIsInstance(image, np.ndarray)
+
+ # Test not batched input
+ encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]])
+ self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape))
+
+ # Test batched
+ encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs)
+ self.assertEqual(
+ tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape)
+ )
+
+ def test_call_pil(self):
+ for image_processing_class in self.image_processor_list:
+ # Initialize image_processing
+ image_processing = self.image_processing_class(**self.image_processor_dict)
+ # create random PIL images
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False)
+ for images in image_inputs:
+ for image in images:
+ self.assertIsInstance(image, Image.Image)
+
+ # Test not batched input
+ encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]])
+ self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape))
+
+ # Test batched
+ encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs)
+ self.assertEqual(
+ tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape)
+ )
+
+ def test_call_pytorch(self):
+ for image_processing_class in self.image_processor_list:
+ # Initialize image_processing
+ image_processing = self.image_processing_class(**self.image_processor_dict)
+ # create random PyTorch tensors
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True)
+
+ for images in image_inputs:
+ for image in images:
+ self.assertIsInstance(image, torch.Tensor)
+
+ # Test not batched input
+ encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]])
+ self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape))
+
+ # Test batched
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs)
+ encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
+ self.assertEqual(
+ tuple(encoded_images.shape),
+ (self.image_processor_tester.batch_size, *expected_output_image_shape),
+ )
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/aria/test_modeling_aria.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/aria/test_modeling_aria.py
new file mode 100644
index 0000000000000000000000000000000000000000..e29a507d6a810e0e5e6a86ed2b8e24f374ae4fd5
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/aria/test_modeling_aria.py
@@ -0,0 +1,504 @@
+# 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.
+"""Testing suite for the PyTorch Aria model."""
+
+import gc
+import unittest
+
+import requests
+
+from transformers import (
+ AriaConfig,
+ AriaForConditionalGeneration,
+ AriaTextConfig,
+ AutoProcessor,
+ AutoTokenizer,
+ is_torch_available,
+ is_vision_available,
+)
+from transformers.models.idefics3 import Idefics3VisionConfig
+from transformers.testing_utils import (
+ require_bitsandbytes,
+ require_torch,
+ require_vision,
+ slow,
+ torch_device,
+)
+
+from ...generation.test_utils import GenerationTesterMixin
+from ...test_configuration_common import ConfigTester
+from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
+
+
+if is_torch_available():
+ import torch
+
+
+if is_vision_available():
+ from PIL import Image
+
+
+class AriaVisionText2TextModelTester:
+ def __init__(
+ self,
+ parent,
+ ignore_index=-100,
+ image_token_index=9,
+ projector_hidden_act="gelu",
+ seq_length=7,
+ vision_feature_select_strategy="default",
+ vision_feature_layer=-1,
+ text_config=AriaTextConfig(
+ seq_length=7,
+ is_training=True,
+ use_input_mask=True,
+ use_token_type_ids=False,
+ use_labels=True,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.1,
+ attention_probs_dropout_prob=0.1,
+ type_vocab_size=16,
+ type_sequence_label_size=2,
+ initializer_range=0.02,
+ num_labels=3,
+ num_choices=4,
+ pad_token_id=1,
+ hidden_size=32,
+ intermediate_size=64,
+ max_position_embeddings=60,
+ model_type="aria_moe_lm",
+ moe_intermediate_size=4,
+ moe_num_experts=4,
+ moe_topk=2,
+ num_attention_heads=8,
+ num_experts_per_tok=3,
+ num_hidden_layers=2,
+ num_key_value_heads=8,
+ rope_theta=5000000,
+ vocab_size=99,
+ eos_token_id=2,
+ head_dim=4,
+ ),
+ is_training=True,
+ vision_config=Idefics3VisionConfig(
+ image_size=358,
+ patch_size=10,
+ num_channels=3,
+ is_training=True,
+ hidden_size=32,
+ projection_dim=20,
+ num_hidden_layers=2,
+ num_attention_heads=16,
+ intermediate_size=10,
+ dropout=0.1,
+ attention_dropout=0.1,
+ initializer_range=0.02,
+ ),
+ ):
+ self.parent = parent
+ self.ignore_index = ignore_index
+ self.image_token_index = image_token_index
+ self.projector_hidden_act = projector_hidden_act
+ self.vision_feature_select_strategy = vision_feature_select_strategy
+ self.vision_feature_layer = vision_feature_layer
+ self.text_config = text_config
+ self.vision_config = vision_config
+ self.pad_token_id = text_config.pad_token_id
+ self.eos_token_id = text_config.eos_token_id
+ self.num_hidden_layers = text_config.num_hidden_layers
+ self.vocab_size = text_config.vocab_size
+ self.hidden_size = text_config.hidden_size
+ self.num_attention_heads = text_config.num_attention_heads
+ self.is_training = is_training
+
+ self.batch_size = 10
+ self.num_channels = 3
+ self.image_size = 358
+ self.num_image_tokens = 128
+ self.seq_length = seq_length + self.num_image_tokens
+
+ def get_config(self):
+ return AriaConfig(
+ text_config=self.text_config,
+ vision_config=self.vision_config,
+ ignore_index=self.ignore_index,
+ image_token_index=self.image_token_index,
+ projector_hidden_act=self.projector_hidden_act,
+ vision_feature_select_strategy=self.vision_feature_select_strategy,
+ vision_feature_layer=self.vision_feature_layer,
+ eos_token_id=self.eos_token_id,
+ )
+
+ def prepare_config_and_inputs(self):
+ pixel_values = floats_tensor(
+ [
+ self.batch_size,
+ self.vision_config.num_channels,
+ self.vision_config.image_size,
+ self.vision_config.image_size,
+ ]
+ )
+ config = self.get_config()
+
+ return config, pixel_values
+
+ def prepare_config_and_inputs_for_common(self):
+ config_and_inputs = self.prepare_config_and_inputs()
+ config, pixel_values = config_and_inputs
+ input_ids = ids_tensor([self.batch_size, self.seq_length], config.text_config.vocab_size - 1) + 1
+ attention_mask = input_ids.ne(1).to(torch_device)
+ input_ids[input_ids == config.image_token_index] = self.pad_token_id
+ input_ids[:, : self.num_image_tokens] = config.image_token_index
+ inputs_dict = {
+ "pixel_values": pixel_values,
+ "input_ids": input_ids,
+ "attention_mask": attention_mask,
+ }
+ return config, inputs_dict
+
+ def create_and_check_aria_model_fp16_forward(self, config, input_ids, pixel_values, attention_mask):
+ model = AriaForConditionalGeneration(config=config)
+ model.to(torch_device)
+ model.eval()
+ with torch.autocast(device_type="cuda", dtype=torch.float16):
+ logits = model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ pixel_values=pixel_values.to(torch.bfloat16),
+ return_dict=True,
+ )["logits"]
+ self.parent.assertFalse(torch.isnan(logits).any().item())
+
+
+@require_torch
+class AriaForConditionalGenerationModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
+ """
+ Model tester for `AriaForConditionalGeneration`.
+ """
+
+ all_model_classes = (AriaForConditionalGeneration,) if is_torch_available() else ()
+ test_pruning = False
+ test_head_masking = False
+ _is_composite = True
+
+ def setUp(self):
+ self.model_tester = AriaVisionText2TextModelTester(self)
+ self.config_tester = ConfigTester(self, config_class=AriaConfig, has_text_modality=False)
+
+ # overwrite inputs_embeds tests because we need to delete "pixel values" for LVLMs
+ def test_inputs_embeds(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+ model.to(torch_device)
+ model.eval()
+
+ inputs = self._prepare_for_class(inputs_dict, model_class)
+
+ input_ids = inputs["input_ids"]
+ del inputs["input_ids"]
+ del inputs["pixel_values"]
+
+ wte = model.get_input_embeddings()
+ inputs["inputs_embeds"] = wte(input_ids)
+
+ with torch.no_grad():
+ model(**inputs)
+
+ # overwrite inputs_embeds tests because we need to delete "pixel values" for LVLMs
+ # while some other models require pixel_values to be present
+ def test_inputs_embeds_matches_input_ids(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+ model.to(torch_device)
+ model.eval()
+
+ inputs = self._prepare_for_class(inputs_dict, model_class)
+ input_ids = inputs["input_ids"]
+ del inputs["input_ids"]
+ del inputs["pixel_values"]
+
+ inputs_embeds = model.get_input_embeddings()(input_ids)
+
+ with torch.no_grad():
+ out_ids = model(input_ids=input_ids, **inputs)[0]
+ out_embeds = model(inputs_embeds=inputs_embeds, **inputs)[0]
+ torch.testing.assert_close(out_embeds, out_ids)
+
+ @unittest.skip(
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
+ )
+ def test_training_gradient_checkpointing(self):
+ pass
+
+ @unittest.skip(
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
+ )
+ def test_training_gradient_checkpointing_use_reentrant(self):
+ pass
+
+ @unittest.skip(
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
+ )
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
+ pass
+
+ @unittest.skip(reason="Compile not yet supported because in LLava models")
+ def test_sdpa_can_compile_dynamic(self):
+ pass
+
+ @unittest.skip(reason="Compile not yet supported because in LLava models")
+ def test_sdpa_can_dispatch_on_flash(self):
+ pass
+
+ @unittest.skip(reason="Feedforward chunking is not yet supported")
+ def test_feed_forward_chunking(self):
+ pass
+
+ @unittest.skip(reason="Unstable test")
+ def test_initialization(self):
+ pass
+
+ @unittest.skip(reason="Unstable test")
+ def test_dola_decoding_sample(self):
+ pass
+
+ @unittest.skip(reason="Unsupported")
+ def test_generate_from_inputs_embeds_0_greedy(self):
+ pass
+
+ @unittest.skip(reason="Unsupported")
+ def test_generate_from_inputs_embeds_1_beam_search(self):
+ pass
+
+ @unittest.skip(reason="Dynamic control flow due to MoE")
+ def test_generate_with_static_cache(self):
+ pass
+
+ @unittest.skip(reason="Dynamic control flow due to MoE")
+ def test_generate_from_inputs_embeds_with_static_cache(self):
+ pass
+
+ @unittest.skip(reason="Dynamic control flow due to MoE")
+ def test_generate_compile_model_forward(self):
+ pass
+
+
+@require_torch
+class AriaForConditionalGenerationIntegrationTest(unittest.TestCase):
+ def setUp(self):
+ self.processor = AutoProcessor.from_pretrained("rhymes-ai/Aria")
+
+ def tearDown(self):
+ gc.collect()
+ torch.cuda.empty_cache()
+
+ @slow
+ @require_bitsandbytes
+ def test_small_model_integration_test(self):
+ # Let' s make sure we test the preprocessing to replace what is used
+ model = AriaForConditionalGeneration.from_pretrained("rhymes-ai/Aria", load_in_4bit=True)
+
+ prompt = "\nUSER: What are the things I should be cautious about when I visit this place?\nASSISTANT:"
+ image_file = "https://aria-vl.github.io/static/images/view.jpg"
+ raw_image = Image.open(requests.get(image_file, stream=True).raw)
+ inputs = self.processor(images=raw_image, text=prompt, return_tensors="pt")
+
+ EXPECTED_INPUT_IDS = torch.tensor([[1, 32000, 28705, 13, 11123, 28747, 1824, 460, 272, 1722,315, 1023, 347, 13831, 925, 684, 739, 315, 3251, 456,1633, 28804, 13, 4816, 8048, 12738, 28747]]) # fmt: skip
+ self.assertTrue(torch.equal(inputs["input_ids"], EXPECTED_INPUT_IDS))
+
+ output = model.generate(**inputs, max_new_tokens=20)
+ EXPECTED_DECODED_TEXT = "\nUSER: What are the things I should be cautious about when I visit this place?\nASSISTANT: When visiting this place, there are a few things one should be cautious about. Firstly," # fmt: skip
+
+ self.assertEqual(
+ self.processor.decode(output[0], skip_special_tokens=True),
+ EXPECTED_DECODED_TEXT,
+ )
+
+ @slow
+ @require_bitsandbytes
+ def test_small_model_integration_test_llama_single(self):
+ # Let' s make sure we test the preprocessing to replace what is used
+ model_id = "rhymes-ai/Aria"
+
+ model = AriaForConditionalGeneration.from_pretrained(model_id, load_in_4bit=True)
+ processor = AutoProcessor.from_pretrained(model_id)
+
+ prompt = "USER: \nWhat are the things I should be cautious about when I visit this place? ASSISTANT:"
+ image_file = "https://aria-vl.github.io/static/images/view.jpg"
+ raw_image = Image.open(requests.get(image_file, stream=True).raw)
+ inputs = processor(images=raw_image, text=prompt, return_tensors="pt").to(torch_device, torch.float16)
+
+ output = model.generate(**inputs, max_new_tokens=900, do_sample=False)
+ EXPECTED_DECODED_TEXT = "USER: \nWhat are the things I should be cautious about when I visit this place? ASSISTANT: When visiting this place, which is a pier or dock extending over a body of water, there are a few things to be cautious about. First, be aware of the weather conditions, as sudden changes in weather can make the pier unsafe to walk on. Second, be mindful of the water depth and any potential hazards, such as submerged rocks or debris, that could cause accidents or injuries. Additionally, be cautious of the tides and currents, as they can change rapidly and pose a risk to swimmers or those who venture too close to the edge of the pier. Finally, be respectful of the environment and other visitors, and follow any posted rules or guidelines for the area." # fmt: skip
+
+ self.assertEqual(
+ processor.decode(output[0], skip_special_tokens=True),
+ EXPECTED_DECODED_TEXT,
+ )
+
+ @slow
+ @require_bitsandbytes
+ def test_small_model_integration_test_llama_batched(self):
+ # Let' s make sure we test the preprocessing to replace what is used
+ model_id = "rhymes-ai/Aria"
+
+ model = AriaForConditionalGeneration.from_pretrained(model_id, load_in_4bit=True)
+ processor = AutoProcessor.from_pretrained(model_id)
+
+ prompts = [
+ "USER: \nWhat are the things I should be cautious about when I visit this place? What should I bring with me? ASSISTANT:",
+ "USER: \nWhat is this? ASSISTANT:",
+ ]
+ image1 = Image.open(requests.get("https://aria-vl.github.io/static/images/view.jpg", stream=True).raw)
+ image2 = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)
+
+ inputs = processor(images=[image1, image2], text=prompts, return_tensors="pt", padding=True)
+
+ output = model.generate(**inputs, max_new_tokens=20)
+
+ EXPECTED_DECODED_TEXT = ['USER: \nWhat are the things I should be cautious about when I visit this place? What should I bring with me? ASSISTANT: When visiting this place, which is a pier or dock extending over a body of water, you', 'USER: \nWhat is this? ASSISTANT: The image features two cats lying down on a pink couch. One cat is located on'] # fmt: skip
+
+ self.assertEqual(
+ processor.batch_decode(output, skip_special_tokens=True),
+ EXPECTED_DECODED_TEXT,
+ )
+
+ @slow
+ @require_bitsandbytes
+ def test_small_model_integration_test_batch(self):
+ # Let' s make sure we test the preprocessing to replace what is used
+ model = AriaForConditionalGeneration.from_pretrained("rhymes-ai/Aria", load_in_4bit=True)
+ # The first batch is longer in terms of text, but only has 1 image. The second batch will be padded in text, but the first will be padded because images take more space!.
+ prompts = [
+ "USER: \nWhat are the things I should be cautious about when I visit this place? What should I bring with me?\nASSISTANT:",
+ "USER: \nWhat is this?\nASSISTANT:",
+ ]
+ image1 = Image.open(requests.get("https://aria-vl.github.io/static/images/view.jpg", stream=True).raw)
+ image2 = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)
+
+ inputs = self.processor(images=[image1, image2], text=prompts, return_tensors="pt", padding=True)
+
+ output = model.generate(**inputs, max_new_tokens=20)
+
+ EXPECTED_DECODED_TEXT = [
+ 'USER: \nWhat are the things I should be cautious about when I visit this place? What should I bring with me?\nASSISTANT: When visiting this place, there are a few things to be cautious about and items to bring.',
+ 'USER: \nWhat is this?\nASSISTANT: Cats'
+ ] # fmt: skip
+ self.assertEqual(
+ self.processor.batch_decode(output, skip_special_tokens=True),
+ EXPECTED_DECODED_TEXT,
+ )
+
+ @slow
+ @require_bitsandbytes
+ def test_small_model_integration_test_llama_batched_regression(self):
+ # Let' s make sure we test the preprocessing to replace what is used
+ model_id = "rhymes-ai/Aria"
+
+ # Multi-image & multi-prompt (e.g. 3 images and 2 prompts now fails with SDPA, this tests if "eager" works as before)
+ model = AriaForConditionalGeneration.from_pretrained(model_id, load_in_4bit=True, attn_implementation="eager")
+ processor = AutoProcessor.from_pretrained(model_id, pad_token="")
+
+ prompts = [
+ "USER: \nWhat are the things I should be cautious about when I visit this place? What should I bring with me?\nASSISTANT:",
+ "USER: \nWhat is this?\nASSISTANT: Two cats lying on a bed!\nUSER: \nAnd this?\nASSISTANT:",
+ ]
+ image1 = Image.open(requests.get("https://aria-vl.github.io/static/images/view.jpg", stream=True).raw)
+ image2 = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)
+
+ inputs = processor(images=[image1, image2, image1], text=prompts, return_tensors="pt", padding=True)
+
+ output = model.generate(**inputs, max_new_tokens=20)
+
+ EXPECTED_DECODED_TEXT = ['USER: \nWhat are the things I should be cautious about when I visit this place? What should I bring with me?\nASSISTANT: When visiting this place, which appears to be a dock or pier extending over a body of water', 'USER: \nWhat is this?\nASSISTANT: Two cats lying on a bed!\nUSER: \nAnd this?\nASSISTANT: A cat sleeping on a bed.'] # fmt: skip
+
+ self.assertEqual(
+ processor.batch_decode(output, skip_special_tokens=True),
+ EXPECTED_DECODED_TEXT,
+ )
+
+ @slow
+ @require_torch
+ @require_vision
+ @require_bitsandbytes
+ def test_batched_generation(self):
+ model = AriaForConditionalGeneration.from_pretrained("rhymes-ai/Aria", load_in_4bit=True)
+
+ processor = AutoProcessor.from_pretrained("rhymes-ai/Aria")
+
+ prompt1 = "\n\nUSER: What's the the difference of two images?\nASSISTANT:"
+ prompt2 = "\nUSER: Describe the image.\nASSISTANT:"
+ prompt3 = "\nUSER: Describe the image.\nASSISTANT:"
+ url1 = "https://images.unsplash.com/photo-1552053831-71594a27632d?q=80&w=3062&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
+ url2 = "https://images.unsplash.com/photo-1617258683320-61900b281ced?q=80&w=3087&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
+ image1 = Image.open(requests.get(url1, stream=True).raw)
+ image2 = Image.open(requests.get(url2, stream=True).raw)
+
+ inputs = processor(
+ images=[image1, image2, image1, image2],
+ text=[prompt1, prompt2, prompt3],
+ return_tensors="pt",
+ padding=True,
+ ).to(torch_device)
+
+ model = model.eval()
+
+ EXPECTED_OUTPUT = [
+ "\n \nUSER: What's the the difference of two images?\nASSISTANT: The difference between the two images is that one shows a dog standing on a grassy field, while",
+ "\nUSER: Describe the image.\nASSISTANT: The image features a brown and white dog sitting on a sidewalk. The dog is holding a small",
+ "\nUSER: Describe the image.\nASSISTANT: The image features a lone llama standing on a grassy hill. The llama is the",
+ ]
+
+ generate_ids = model.generate(**inputs, max_new_tokens=20)
+ outputs = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
+ self.assertEqual(outputs, EXPECTED_OUTPUT)
+
+ def test_tokenizer_integration(self):
+ model_id = "rhymes-ai/Aria"
+ slow_tokenizer = AutoTokenizer.from_pretrained(
+ model_id, bos_token="<|startoftext|>", eos_token="<|endoftext|>", use_fast=False
+ )
+ slow_tokenizer.add_tokens("", True)
+
+ fast_tokenizer = AutoTokenizer.from_pretrained(
+ model_id,
+ bos_token="<|startoftext|>",
+ eos_token="<|endoftext|>",
+ from_slow=True,
+ legacy=False,
+ )
+ fast_tokenizer.add_tokens("", True)
+
+ prompt = "<|startoftext|><|im_start|>system\nAnswer the questions.<|im_end|><|im_start|>user\n\nWhat is shown in this image?<|im_end|>"
+ EXPECTED_OUTPUT = ['<|startoftext|>', '<', '|', 'im', '_', 'start', '|', '>', 'system', '\n', 'Answer', '▁the', '▁questions', '.<', '|', 'im', '_', 'end', '|', '><', '|', 'im', '_', 'start', '|', '>', 'user', '\n', '', '\n', 'What', '▁is', '▁shown', '▁in', '▁this', '▁image', '?', '<', '|', 'im', '_', 'end', '|', '>'] # fmt: skip
+ self.assertEqual(slow_tokenizer.tokenize(prompt), EXPECTED_OUTPUT)
+ self.assertEqual(fast_tokenizer.tokenize(prompt), EXPECTED_OUTPUT)
+
+ @slow
+ @require_bitsandbytes
+ def test_generation_no_images(self):
+ model_id = "rhymes-ai/Aria"
+ model = AriaForConditionalGeneration.from_pretrained(model_id, load_in_4bit=True)
+ processor = AutoProcessor.from_pretrained(model_id)
+
+ # Prepare inputs with no images
+ inputs = processor(text="Hello, I am", return_tensors="pt").to(torch_device)
+
+ # Make sure that `generate` works
+ _ = model.generate(**inputs, max_new_tokens=20)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/aria/test_processor_aria.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/aria/test_processor_aria.py
new file mode 100644
index 0000000000000000000000000000000000000000..623153b6798adf06456b03ca27b6c1f9ffd78e10
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/aria/test_processor_aria.py
@@ -0,0 +1,440 @@
+# coding=utf-8
+# Copyright 2024 HuggingFace Inc.
+#
+# 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 shutil
+import tempfile
+import unittest
+from io import BytesIO
+from typing import Optional
+
+import numpy as np
+import requests
+
+from transformers import AriaProcessor
+from transformers.models.auto.processing_auto import AutoProcessor
+from transformers.testing_utils import require_torch, require_vision
+from transformers.utils import is_vision_available
+
+from ...test_processing_common import ProcessorTesterMixin
+
+
+if is_vision_available():
+ from PIL import Image
+
+
+@require_torch
+@require_vision
+class AriaProcessorTest(ProcessorTesterMixin, unittest.TestCase):
+ processor_class = AriaProcessor
+
+ @classmethod
+ def setUpClass(cls):
+ cls.tmpdirname = tempfile.mkdtemp()
+ processor = AriaProcessor.from_pretrained("m-ric/Aria_hf_2", image_seq_len=2)
+ processor.save_pretrained(cls.tmpdirname)
+ cls.image1 = Image.open(
+ BytesIO(
+ requests.get(
+ "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
+ ).content
+ )
+ )
+ cls.image2 = Image.open(
+ BytesIO(requests.get("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg").content)
+ )
+ cls.image3 = Image.open(
+ BytesIO(
+ requests.get(
+ "https://thumbs.dreamstime.com/b/golden-gate-bridge-san-francisco-purple-flowers-california-echium-candicans-36805947.jpg"
+ ).content
+ )
+ )
+ cls.bos_token = "<|im_start|>"
+ cls.eos_token = "<|im_end|>"
+
+ cls.image_token = processor.tokenizer.image_token
+ cls.fake_image_token = "o"
+ cls.global_img_token = "<|img|>"
+
+ cls.bos_token_id = processor.tokenizer.convert_tokens_to_ids(cls.bos_token)
+ cls.eos_token_id = processor.tokenizer.convert_tokens_to_ids(cls.eos_token)
+
+ cls.image_token_id = processor.tokenizer.convert_tokens_to_ids(cls.image_token)
+ cls.fake_image_token_id = processor.tokenizer.convert_tokens_to_ids(cls.fake_image_token)
+ cls.global_img_tokens_id = processor.tokenizer(cls.global_img_token, add_special_tokens=False)["input_ids"]
+ cls.padding_token_id = processor.tokenizer.pad_token_id
+ cls.image_seq_len = 256
+
+ def get_tokenizer(self, **kwargs):
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).tokenizer
+
+ def get_image_processor(self, **kwargs):
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor
+
+ def get_processor(self, **kwargs):
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs)
+
+ @classmethod
+ def tearDownClass(cls):
+ shutil.rmtree(cls.tmpdirname)
+
+ def test_kwargs_overrides_default_image_processor_kwargs(self):
+ if "image_processor" not in self.processor_class.attributes:
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
+ processor_components = self.prepare_components()
+ processor_components["image_processor"] = self.get_component(
+ "image_processor", do_rescale=True, rescale_factor=1
+ )
+ processor_components["tokenizer"] = self.get_component("tokenizer", max_length=117, padding="max_length")
+
+ processor = self.processor_class(**processor_components)
+ self.skip_processor_without_typed_kwargs(processor)
+
+ input_str = self.prepare_text_inputs()
+ image_input = self.prepare_image_inputs()
+
+ inputs = processor(text=input_str, images=image_input, return_tensors="pt")
+ self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0)
+
+ def test_process_interleaved_images_prompts_image_splitting(self):
+ processor = self.get_processor()
+ processor.image_processor.split_image = True
+
+ # Test that a single image is processed correctly
+ inputs = processor(images=self.image1, text="Ok<|img|>", images_kwargs={"split_image": True})
+ self.assertEqual(np.array(inputs["pixel_values"]).shape, (2, 3, 980, 980))
+ self.assertEqual(np.array(inputs["pixel_mask"]).shape, (2, 980, 980))
+
+ def test_process_interleaved_images_prompts_no_image_splitting(self):
+ processor = self.get_processor()
+ processor.image_processor.split_image = False
+
+ # Test that a single image is processed correctly
+ inputs = processor(images=self.image1, text="Ok<|img|>")
+ image1_expected_size = (980, 980)
+ self.assertEqual(np.array(inputs["pixel_values"]).shape, (1, 3, *image1_expected_size))
+ self.assertEqual(np.array(inputs["pixel_mask"]).shape, (1, *image1_expected_size))
+ # fmt: on
+
+ # Test a single sample with image and text
+ image_str = "<|img|>"
+ text_str = "In this image, we see"
+ text = image_str + text_str
+ inputs = processor(text=text, images=self.image1)
+
+ # fmt: off
+ tokenized_sentence = processor.tokenizer(text_str, add_special_tokens=False)
+
+ expected_input_ids = [[self.image_token_id] * self.image_seq_len + tokenized_sentence["input_ids"]]
+ # self.assertEqual(len(inputs["input_ids"]), len(expected_input_ids))
+
+ self.assertEqual(inputs["input_ids"], expected_input_ids)
+ self.assertEqual(inputs["attention_mask"], [[1] * len(expected_input_ids[0])])
+ self.assertEqual(np.array(inputs["pixel_values"]).shape, (1, 3, *image1_expected_size))
+ self.assertEqual(np.array(inputs["pixel_mask"]).shape, (1, *image1_expected_size))
+ # fmt: on
+
+ # Test that batch is correctly processed
+ image_str = "<|img|>"
+ text_str_1 = "In this image, we see"
+ text_str_2 = "In this image, we see"
+
+ text = [
+ image_str + text_str_1,
+ image_str + image_str + text_str_2,
+ ]
+ images = [[self.image1], [self.image2, self.image3]]
+
+ inputs = processor(text=text, images=images, padding=True)
+
+ # fmt: off
+ tokenized_sentence_1 = processor.tokenizer(text_str_1, add_special_tokens=False)
+ tokenized_sentence_2 = processor.tokenizer(text_str_2, add_special_tokens=False)
+
+ image_tokens = [self.image_token_id] * self.image_seq_len
+ expected_input_ids_1 = image_tokens + tokenized_sentence_1["input_ids"]
+ expected_input_ids_2 = 2 * image_tokens + tokenized_sentence_2["input_ids"]
+
+ # Pad the first input to match the second input
+ pad_len = len(expected_input_ids_2) - len(expected_input_ids_1)
+
+ expected_attention_mask = [[0] * pad_len + [1] * len(expected_input_ids_1), [1] * (len(expected_input_ids_2))]
+
+ self.assertEqual(
+ inputs["attention_mask"],
+ expected_attention_mask
+ )
+ self.assertEqual(np.array(inputs['pixel_values']).shape, (3, 3, 980, 980))
+ self.assertEqual(np.array(inputs['pixel_mask']).shape, (3, 980, 980))
+ # fmt: on
+
+ def test_non_nested_images_with_batched_text(self):
+ processor = self.get_processor()
+ processor.image_processor.do_image_splitting = False
+
+ image_str = "<|img|>"
+ text_str_1 = "In this image, we see"
+ text_str_2 = "In this image, we see"
+
+ text = [
+ image_str + text_str_1,
+ image_str + image_str + text_str_2,
+ ]
+ images = [self.image1, self.image2, self.image3]
+
+ inputs = processor(text=text, images=images, padding=True)
+
+ self.assertEqual(np.array(inputs["pixel_values"]).shape, (3, 3, 980, 980))
+ self.assertEqual(np.array(inputs["pixel_mask"]).shape, (3, 980, 980))
+
+ def test_apply_chat_template(self):
+ # Message contains content which a mix of lists with images and image urls and string
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "What do these images show?"},
+ {"type": "image"},
+ {"type": "image"},
+ "What do these images show?",
+ ],
+ },
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "The first image shows the statue of Liberty in New York. The second image picture depicts Idefix, the dog of Obelix in Asterix and Obelix.",
+ }
+ ],
+ },
+ {"role": "user", "content": [{"type": "text", "text": "And who is that?"}]},
+ ]
+ processor = self.get_processor()
+ # Make short sequence length to test that the fake tokens are added correctly
+ rendered = processor.apply_chat_template(messages, add_generation_prompt=True)
+ print(rendered)
+
+ expected_rendered = """<|im_start|>user
+What do these images show?<|img|><|img|><|im_end|>
+<|im_start|>assistant
+The first image shows the statue of Liberty in New York. The second image picture depicts Idefix, the dog of Obelix in Asterix and Obelix.<|im_end|>
+<|im_start|>user
+And who is that?<|im_end|>
+<|im_start|>assistant
+"""
+ self.assertEqual(rendered, expected_rendered)
+
+ # Override as AriaImageProcessor doesn't accept `do_rescale`
+ def test_chat_template_accepts_processing_kwargs(self):
+ processor = self.get_processor()
+ if processor.chat_template is None:
+ self.skipTest("Processor has no chat template")
+
+ messages = [
+ [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "What is shown in this image?"},
+ ],
+ },
+ ]
+ ]
+
+ formatted_prompt_tokenized = processor.apply_chat_template(
+ messages,
+ add_generation_prompt=True,
+ tokenize=True,
+ padding="max_length",
+ max_length=50,
+ )
+ self.assertEqual(len(formatted_prompt_tokenized[0]), 50)
+
+ formatted_prompt_tokenized = processor.apply_chat_template(
+ messages,
+ add_generation_prompt=True,
+ tokenize=True,
+ truncation=True,
+ max_length=5,
+ )
+ self.assertEqual(len(formatted_prompt_tokenized[0]), 5)
+
+ # Now test the ability to return dict
+ messages[0][0]["content"].append(
+ {"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"}
+ )
+ out_dict = processor.apply_chat_template(
+ messages,
+ add_generation_prompt=True,
+ tokenize=True,
+ return_dict=True,
+ max_image_size=980,
+ return_tensors="np",
+ )
+ self.assertListEqual(list(out_dict[self.images_input_name].shape), [1, 3, 980, 980])
+
+ # Override as AriaProcessor needs image tokens in prompts
+ def prepare_text_inputs(self, batch_size: Optional[int] = None):
+ if batch_size is None:
+ return "lower newer <|img|>"
+
+ if batch_size < 1:
+ raise ValueError("batch_size must be greater than 0")
+
+ if batch_size == 1:
+ return ["lower newer <|img|>"]
+ return ["lower newer <|img|>", "<|img|> upper older longer string"] + ["<|img|> lower newer"] * (
+ batch_size - 2
+ )
+
+ # Override tests as inputs_ids padded dimension is the second one but not the last one
+ @require_vision
+ @require_torch
+ def test_kwargs_overrides_default_tokenizer_kwargs(self):
+ if "image_processor" not in self.processor_class.attributes:
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
+ image_processor = self.get_component("image_processor")
+ tokenizer = self.get_component("tokenizer", max_length=30)
+
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
+ self.skip_processor_without_typed_kwargs(processor)
+ input_str = self.prepare_text_inputs()
+ image_input = self.prepare_image_inputs()
+
+ inputs = processor(text=input_str, images=image_input, return_tensors="pt", max_length=30)
+ self.assertEqual(len(inputs["input_ids"][0]), 30)
+
+ @require_torch
+ @require_vision
+ def test_structured_kwargs_nested(self):
+ if "image_processor" not in self.processor_class.attributes:
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
+ image_processor = self.get_component("image_processor")
+ tokenizer = self.get_component("tokenizer")
+
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
+ self.skip_processor_without_typed_kwargs(processor)
+
+ input_str = self.prepare_text_inputs()
+ image_input = self.prepare_image_inputs()
+
+ # Define the kwargs for each modality
+ inputs = processor(
+ text=input_str,
+ images=image_input,
+ common_kwargs={"return_tensors": "pt"},
+ images_kwargs={"max_image_size": 980},
+ text_kwargs={"padding": "max_length", "max_length": 120, "truncation": "longest_first"},
+ )
+ self.skip_processor_without_typed_kwargs(processor)
+
+ self.assertEqual(inputs["pixel_values"].shape[3], 980)
+
+ self.assertEqual(len(inputs["input_ids"][0]), 120)
+
+ @require_torch
+ @require_vision
+ def test_structured_kwargs_nested_from_dict(self):
+ if "image_processor" not in self.processor_class.attributes:
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
+
+ image_processor = self.get_component("image_processor")
+ tokenizer = self.get_component("tokenizer")
+
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
+ self.skip_processor_without_typed_kwargs(processor)
+ input_str = self.prepare_text_inputs()
+ image_input = self.prepare_image_inputs()
+
+ # Define the kwargs for each modality
+ all_kwargs = {
+ "common_kwargs": {"return_tensors": "pt"},
+ "images_kwargs": {"max_image_size": 980},
+ "text_kwargs": {"padding": "max_length", "max_length": 120, "truncation": "longest_first"},
+ }
+
+ inputs = processor(text=input_str, images=image_input, **all_kwargs)
+ self.assertEqual(inputs["pixel_values"].shape[3], 980)
+ self.assertEqual(len(inputs["input_ids"][0]), 120)
+
+ @require_vision
+ @require_torch
+ def test_tokenizer_defaults_preserved_by_kwargs(self):
+ if "image_processor" not in self.processor_class.attributes:
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
+ image_processor = self.get_component("image_processor")
+ tokenizer = self.get_component("tokenizer", max_length=30)
+
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
+ self.skip_processor_without_typed_kwargs(processor)
+ input_str = self.prepare_text_inputs()
+ image_input = self.prepare_image_inputs()
+
+ inputs = processor(text=input_str, images=image_input, return_tensors="pt")
+ self.assertEqual(len(inputs["input_ids"][0]), 30)
+
+ @require_torch
+ @require_vision
+ def test_unstructured_kwargs_batched(self):
+ if "image_processor" not in self.processor_class.attributes:
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
+ image_processor = self.get_component("image_processor")
+ tokenizer = self.get_component("tokenizer")
+
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
+ self.skip_processor_without_typed_kwargs(processor)
+
+ input_str = self.prepare_text_inputs(batch_size=2)
+ image_input = self.prepare_image_inputs(batch_size=2)
+ inputs = processor(
+ text=input_str,
+ images=image_input,
+ return_tensors="pt",
+ padding="longest",
+ max_length=76,
+ truncation=True,
+ max_image_size=980,
+ )
+
+ self.assertEqual(inputs["pixel_values"].shape[1], 3)
+ self.assertEqual(inputs["pixel_values"].shape[3], 980)
+ self.assertEqual(len(inputs["input_ids"][0]), 76)
+
+ @require_torch
+ @require_vision
+ def test_unstructured_kwargs(self):
+ if "image_processor" not in self.processor_class.attributes:
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
+ image_processor = self.get_component("image_processor")
+ tokenizer = self.get_component("tokenizer")
+
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
+ self.skip_processor_without_typed_kwargs(processor)
+
+ input_str = self.prepare_text_inputs()
+ image_input = self.prepare_image_inputs()
+ inputs = processor(
+ text=input_str,
+ images=image_input,
+ return_tensors="pt",
+ max_image_size=980,
+ padding="max_length",
+ max_length=120,
+ truncation="longest_first",
+ )
+
+ self.assertEqual(inputs["pixel_values"].shape[3], 980)
+ self.assertEqual(len(inputs["input_ids"][0]), 120)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/audio_spectrogram_transformer/__init__.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/audio_spectrogram_transformer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/audio_spectrogram_transformer/test_feature_extraction_audio_spectrogram_transformer.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/audio_spectrogram_transformer/test_feature_extraction_audio_spectrogram_transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..7455d5ff8561e54033dc583eb6c9fc3d0f83d855
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/audio_spectrogram_transformer/test_feature_extraction_audio_spectrogram_transformer.py
@@ -0,0 +1,222 @@
+# coding=utf-8
+# Copyright 2022 HuggingFace Inc.
+#
+# 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 itertools
+import os
+import random
+import tempfile
+import unittest
+
+import numpy as np
+
+from transformers import ASTFeatureExtractor
+from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
+from transformers.utils.import_utils import is_torch_available
+
+from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin
+
+
+global_rng = random.Random()
+
+if is_torch_available():
+ import torch
+
+
+# Copied from tests.models.whisper.test_feature_extraction_whisper.floats_list
+def floats_list(shape, scale=1.0, rng=None, name=None):
+ """Creates a random float32 tensor"""
+ if rng is None:
+ rng = global_rng
+
+ values = []
+ for batch_idx in range(shape[0]):
+ values.append([])
+ for _ in range(shape[1]):
+ values[-1].append(rng.random() * scale)
+
+ return values
+
+
+class ASTFeatureExtractionTester:
+ def __init__(
+ self,
+ parent,
+ batch_size=7,
+ min_seq_length=400,
+ max_seq_length=2000,
+ feature_size=1,
+ padding_value=0.0,
+ sampling_rate=16000,
+ return_attention_mask=True,
+ do_normalize=True,
+ ):
+ self.parent = parent
+ self.batch_size = batch_size
+ self.min_seq_length = min_seq_length
+ self.max_seq_length = max_seq_length
+ self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
+ self.feature_size = feature_size
+ self.padding_value = padding_value
+ self.sampling_rate = sampling_rate
+ self.return_attention_mask = return_attention_mask
+ self.do_normalize = do_normalize
+
+ def prepare_feat_extract_dict(self):
+ return {
+ "feature_size": self.feature_size,
+ "padding_value": self.padding_value,
+ "sampling_rate": self.sampling_rate,
+ "return_attention_mask": self.return_attention_mask,
+ "do_normalize": self.do_normalize,
+ }
+
+ def prepare_inputs_for_common(self, equal_length=False, numpify=False):
+ def _flatten(list_of_lists):
+ return list(itertools.chain(*list_of_lists))
+
+ if equal_length:
+ speech_inputs = floats_list((self.batch_size, self.max_seq_length))
+ else:
+ # make sure that inputs increase in size
+ speech_inputs = [
+ _flatten(floats_list((x, self.feature_size)))
+ for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff)
+ ]
+
+ if numpify:
+ speech_inputs = [np.asarray(x) for x in speech_inputs]
+
+ return speech_inputs
+
+
+@require_torch
+@require_torchaudio
+class ASTFeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase):
+ feature_extraction_class = ASTFeatureExtractor
+
+ def setUp(self):
+ self.feat_extract_tester = ASTFeatureExtractionTester(self)
+
+ def test_call(self):
+ # Tests that all call wrap to encode_plus and batch_encode_plus
+ feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
+ # create three inputs of length 800, 1000, and 1200
+ speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)]
+ np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs]
+
+ # Test not batched input
+ encoded_sequences_1 = feat_extract(speech_inputs[0], return_tensors="np").input_values
+ encoded_sequences_2 = feat_extract(np_speech_inputs[0], return_tensors="np").input_values
+ self.assertTrue(np.allclose(encoded_sequences_1, encoded_sequences_2, atol=1e-3))
+
+ # Test batched
+ encoded_sequences_1 = feat_extract(speech_inputs, padding=True, return_tensors="np").input_values
+ encoded_sequences_2 = feat_extract(np_speech_inputs, padding=True, return_tensors="np").input_values
+ for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2):
+ self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3))
+
+ # Test 2-D numpy arrays are batched.
+ speech_inputs = [floats_list((1, x))[0] for x in (800, 800, 800)]
+ np_speech_inputs = np.asarray(speech_inputs)
+ encoded_sequences_1 = feat_extract(speech_inputs, return_tensors="np").input_values
+ encoded_sequences_2 = feat_extract(np_speech_inputs, return_tensors="np").input_values
+ for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2):
+ self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3))
+
+ @require_torch
+ def test_double_precision_pad(self):
+ import torch
+
+ feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
+ np_speech_inputs = np.random.rand(100).astype(np.float64)
+ py_speech_inputs = np_speech_inputs.tolist()
+
+ for inputs in [py_speech_inputs, np_speech_inputs]:
+ np_processed = feature_extractor.pad([{"input_values": inputs}], return_tensors="np")
+ self.assertTrue(np_processed.input_values.dtype == np.float32)
+ pt_processed = feature_extractor.pad([{"input_values": inputs}], return_tensors="pt")
+ self.assertTrue(pt_processed.input_values.dtype == torch.float32)
+
+ def _load_datasamples(self, num_samples):
+ from datasets import load_dataset
+
+ ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
+ # automatic decoding with librispeech
+ speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"]
+
+ return [x["array"] for x in speech_samples]
+
+ @require_torch
+ def test_integration(self):
+ # fmt: off
+ EXPECTED_INPUT_VALUES = torch.tensor(
+ [-0.9894, -1.2776, -0.9066, -1.2776, -0.9349, -1.2609, -1.0386, -1.2776,
+ -1.1561, -1.2776, -1.2052, -1.2723, -1.2190, -1.2132, -1.2776, -1.1133,
+ -1.1953, -1.1343, -1.1584, -1.2203, -1.1770, -1.2474, -1.2381, -1.1936,
+ -0.9270, -0.8317, -0.8049, -0.7706, -0.7565, -0.7869]
+ )
+ # fmt: on
+
+ input_speech = self._load_datasamples(1)
+ feature_extractor = ASTFeatureExtractor()
+ input_values = feature_extractor(input_speech, return_tensors="pt").input_values
+ self.assertEqual(input_values.shape, (1, 1024, 128))
+ torch.testing.assert_close(input_values[0, 0, :30], EXPECTED_INPUT_VALUES, rtol=1e-4, atol=1e-4)
+
+ def test_feat_extract_from_and_save_pretrained(self):
+ feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict)
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ saved_file = feat_extract_first.save_pretrained(tmpdirname)[0]
+ check_json_file_has_correct_format(saved_file)
+ feat_extract_second = self.feature_extraction_class.from_pretrained(tmpdirname)
+
+ dict_first = feat_extract_first.to_dict()
+ dict_second = feat_extract_second.to_dict()
+ self.assertDictEqual(dict_first, dict_second)
+
+ def test_feat_extract_to_json_file(self):
+ feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict)
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ json_file_path = os.path.join(tmpdirname, "feat_extract.json")
+ feat_extract_first.to_json_file(json_file_path)
+ feat_extract_second = self.feature_extraction_class.from_json_file(json_file_path)
+
+ dict_first = feat_extract_first.to_dict()
+ dict_second = feat_extract_second.to_dict()
+ self.assertEqual(dict_first, dict_second)
+
+
+# exact same tests than before, except that we simulate that torchaudio is not available
+@require_torch
+@unittest.mock.patch(
+ "transformers.models.audio_spectrogram_transformer.feature_extraction_audio_spectrogram_transformer.is_speech_available",
+ lambda: False,
+)
+class ASTFeatureExtractionWithoutTorchaudioTest(ASTFeatureExtractionTest):
+ def test_using_audio_utils(self):
+ # Tests that it uses audio_utils instead of torchaudio
+ feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
+
+ self.assertTrue(hasattr(feat_extract, "window"))
+ self.assertTrue(hasattr(feat_extract, "mel_filters"))
+
+ from transformers.models.audio_spectrogram_transformer.feature_extraction_audio_spectrogram_transformer import (
+ is_speech_available,
+ )
+
+ self.assertFalse(is_speech_available())
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/audio_spectrogram_transformer/test_modeling_audio_spectrogram_transformer.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/audio_spectrogram_transformer/test_modeling_audio_spectrogram_transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..169ba3e8aeb476edb8b3a8a3c3335e78bf742915
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/audio_spectrogram_transformer/test_modeling_audio_spectrogram_transformer.py
@@ -0,0 +1,269 @@
+# 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.
+"""Testing suite for the PyTorch Audio Spectrogram Transformer (AST) model."""
+
+import inspect
+import unittest
+
+from huggingface_hub import hf_hub_download
+
+from transformers import ASTConfig
+from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device
+from transformers.utils import cached_property, is_torch_available, is_torchaudio_available
+
+from ...test_configuration_common import ConfigTester
+from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
+from ...test_pipeline_mixin import PipelineTesterMixin
+
+
+if is_torch_available():
+ import torch
+ from torch import nn
+
+ from transformers import ASTForAudioClassification, ASTModel
+
+
+if is_torchaudio_available():
+ import torchaudio
+
+ from transformers import ASTFeatureExtractor
+
+
+class ASTModelTester:
+ def __init__(
+ self,
+ parent,
+ batch_size=13,
+ patch_size=2,
+ max_length=24,
+ num_mel_bins=16,
+ is_training=True,
+ use_labels=True,
+ hidden_size=32,
+ num_hidden_layers=2,
+ num_attention_heads=4,
+ intermediate_size=37,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.1,
+ attention_probs_dropout_prob=0.1,
+ type_sequence_label_size=10,
+ initializer_range=0.02,
+ scope=None,
+ frequency_stride=2,
+ time_stride=2,
+ attn_implementation="eager",
+ ):
+ self.parent = parent
+ self.batch_size = batch_size
+ self.patch_size = patch_size
+ self.max_length = max_length
+ self.num_mel_bins = num_mel_bins
+ self.is_training = is_training
+ self.use_labels = use_labels
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.intermediate_size = intermediate_size
+ self.hidden_act = hidden_act
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.type_sequence_label_size = type_sequence_label_size
+ self.initializer_range = initializer_range
+ self.scope = scope
+ self.frequency_stride = frequency_stride
+ self.time_stride = time_stride
+ self.attn_implementation = attn_implementation
+
+ # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
+ frequency_out_dimension = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
+ time_out_dimension = (self.max_length - self.patch_size) // self.time_stride + 1
+ num_patches = frequency_out_dimension * time_out_dimension
+ self.seq_length = num_patches + 2
+
+ def prepare_config_and_inputs(self):
+ input_values = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins])
+
+ labels = None
+ if self.use_labels:
+ labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
+
+ config = self.get_config()
+
+ return config, input_values, labels
+
+ def get_config(self):
+ return ASTConfig(
+ patch_size=self.patch_size,
+ max_length=self.max_length,
+ num_mel_bins=self.num_mel_bins,
+ hidden_size=self.hidden_size,
+ num_hidden_layers=self.num_hidden_layers,
+ num_attention_heads=self.num_attention_heads,
+ intermediate_size=self.intermediate_size,
+ hidden_act=self.hidden_act,
+ hidden_dropout_prob=self.hidden_dropout_prob,
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
+ is_decoder=False,
+ initializer_range=self.initializer_range,
+ frequency_stride=self.frequency_stride,
+ time_stride=self.time_stride,
+ attn_implementation=self.attn_implementation,
+ )
+
+ def create_and_check_model(self, config, input_values, labels):
+ model = ASTModel(config=config)
+ model.to(torch_device)
+ model.eval()
+ result = model(input_values)
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
+
+ def prepare_config_and_inputs_for_common(self):
+ config_and_inputs = self.prepare_config_and_inputs()
+ (
+ config,
+ input_values,
+ labels,
+ ) = config_and_inputs
+ inputs_dict = {"input_values": input_values}
+ return config, inputs_dict
+
+
+@require_torch
+class ASTModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
+ """
+ Here we also overwrite some of the tests of test_modeling_common.py, as AST does not use input_ids, inputs_embeds,
+ attention_mask and seq_length.
+ """
+
+ all_model_classes = (
+ (
+ ASTModel,
+ ASTForAudioClassification,
+ )
+ if is_torch_available()
+ else ()
+ )
+ pipeline_model_mapping = (
+ {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel}
+ if is_torch_available()
+ else {}
+ )
+ fx_compatible = False
+ test_pruning = False
+ test_resize_embeddings = False
+ test_head_masking = False
+
+ # TODO: Fix the failed tests when this model gets more usage
+ def is_pipeline_test_to_skip(
+ self,
+ pipeline_test_case_name,
+ config_class,
+ model_architecture,
+ tokenizer_name,
+ image_processor_name,
+ feature_extractor_name,
+ processor_name,
+ ):
+ if pipeline_test_case_name == "AudioClassificationPipelineTests":
+ return True
+
+ return False
+
+ def setUp(self):
+ self.model_tester = ASTModelTester(self)
+ self.config_tester = ConfigTester(self, config_class=ASTConfig, has_text_modality=False, hidden_size=37)
+
+ def test_config(self):
+ self.config_tester.run_common_tests()
+
+ @unittest.skip(reason="AST does not use inputs_embeds")
+ def test_inputs_embeds(self):
+ pass
+
+ def test_model_get_set_embeddings(self):
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+ self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
+ x = model.get_output_embeddings()
+ self.assertTrue(x is None or isinstance(x, nn.Linear))
+
+ def test_forward_signature(self):
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+ signature = inspect.signature(model.forward)
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
+ arg_names = [*signature.parameters.keys()]
+
+ expected_arg_names = ["input_values"]
+ self.assertListEqual(arg_names[:1], expected_arg_names)
+
+ def test_model(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_model(*config_and_inputs)
+
+ @slow
+ def test_model_from_pretrained(self):
+ model_name = "MIT/ast-finetuned-audioset-10-10-0.4593"
+ model = ASTModel.from_pretrained(model_name)
+ self.assertIsNotNone(model)
+
+
+# We will verify our results on some audio from AudioSet
+def prepare_audio():
+ filepath = hf_hub_download(
+ repo_id="nielsr/audio-spectogram-transformer-checkpoint", filename="sample_audio.flac", repo_type="dataset"
+ )
+
+ audio, sampling_rate = torchaudio.load(filepath)
+
+ return audio, sampling_rate
+
+
+@require_torch
+@require_torchaudio
+class ASTModelIntegrationTest(unittest.TestCase):
+ @cached_property
+ def default_feature_extractor(self):
+ return (
+ ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593")
+ if is_torchaudio_available()
+ else None
+ )
+
+ @slow
+ def test_inference_audio_classification(self):
+ feature_extractor = self.default_feature_extractor
+ model = ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593").to(torch_device)
+
+ feature_extractor = self.default_feature_extractor
+ audio, sampling_rate = prepare_audio()
+ audio = audio.squeeze().numpy()
+ inputs = feature_extractor(audio, sampling_rate=sampling_rate, return_tensors="pt").to(torch_device)
+
+ # forward pass
+ with torch.no_grad():
+ outputs = model(**inputs)
+
+ # verify the logits
+ expected_shape = torch.Size((1, 527))
+ self.assertEqual(outputs.logits.shape, expected_shape)
+
+ expected_slice = torch.tensor([-0.8760, -7.0042, -8.6602]).to(torch_device)
+
+ torch.testing.assert_close(outputs.logits[0, :3], expected_slice, rtol=1e-4, atol=1e-4)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/__init__.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_configuration_auto.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_configuration_auto.py
new file mode 100644
index 0000000000000000000000000000000000000000..69f9029f909b3e8d650d226b0c42a5ceb253b9d1
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_configuration_auto.py
@@ -0,0 +1,159 @@
+# coding=utf-8
+# Copyright 2019-present, 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 json
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+import transformers
+import transformers.models.auto
+from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
+from transformers.models.bert.configuration_bert import BertConfig
+from transformers.models.roberta.configuration_roberta import RobertaConfig
+from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir
+
+
+sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils"))
+
+from test_module.custom_configuration import CustomConfig # noqa E402
+
+
+SAMPLE_ROBERTA_CONFIG = get_tests_dir("fixtures/dummy-config.json")
+
+
+class AutoConfigTest(unittest.TestCase):
+ def setUp(self):
+ transformers.dynamic_module_utils.TIME_OUT_REMOTE_CODE = 0
+
+ def test_module_spec(self):
+ self.assertIsNotNone(transformers.models.auto.__spec__)
+ self.assertIsNotNone(importlib.util.find_spec("transformers.models.auto"))
+
+ def test_config_from_model_shortcut(self):
+ config = AutoConfig.from_pretrained("google-bert/bert-base-uncased")
+ self.assertIsInstance(config, BertConfig)
+
+ def test_config_model_type_from_local_file(self):
+ config = AutoConfig.from_pretrained(SAMPLE_ROBERTA_CONFIG)
+ self.assertIsInstance(config, RobertaConfig)
+
+ def test_config_model_type_from_model_identifier(self):
+ config = AutoConfig.from_pretrained(DUMMY_UNKNOWN_IDENTIFIER)
+ self.assertIsInstance(config, RobertaConfig)
+
+ def test_config_for_model_str(self):
+ config = AutoConfig.for_model("roberta")
+ self.assertIsInstance(config, RobertaConfig)
+
+ def test_pattern_matching_fallback(self):
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ # This model name contains bert and roberta, but roberta ends up being picked.
+ folder = os.path.join(tmp_dir, "fake-roberta")
+ os.makedirs(folder, exist_ok=True)
+ with open(os.path.join(folder, "config.json"), "w") as f:
+ f.write(json.dumps({}))
+ config = AutoConfig.from_pretrained(folder)
+ self.assertEqual(type(config), RobertaConfig)
+
+ def test_new_config_registration(self):
+ try:
+ AutoConfig.register("custom", CustomConfig)
+ # Wrong model type will raise an error
+ with self.assertRaises(ValueError):
+ AutoConfig.register("model", CustomConfig)
+ # Trying to register something existing in the Transformers library will raise an error
+ with self.assertRaises(ValueError):
+ AutoConfig.register("bert", BertConfig)
+
+ # Now that the config is registered, it can be used as any other config with the auto-API
+ config = CustomConfig()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ config.save_pretrained(tmp_dir)
+ new_config = AutoConfig.from_pretrained(tmp_dir)
+ self.assertIsInstance(new_config, CustomConfig)
+
+ finally:
+ if "custom" in CONFIG_MAPPING._extra_content:
+ del CONFIG_MAPPING._extra_content["custom"]
+
+ def test_repo_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError, "bert-base is not a local folder and is not a valid model identifier"
+ ):
+ _ = AutoConfig.from_pretrained("bert-base")
+
+ def test_revision_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError, r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"
+ ):
+ _ = AutoConfig.from_pretrained(DUMMY_UNKNOWN_IDENTIFIER, revision="aaaaaa")
+
+ def test_from_pretrained_dynamic_config(self):
+ # If remote code is not set, we will time out when asking whether to load the model.
+ with self.assertRaises(ValueError):
+ config = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model")
+ # If remote code is disabled, we can't load this config.
+ with self.assertRaises(ValueError):
+ config = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model", trust_remote_code=False)
+
+ config = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model", trust_remote_code=True)
+ self.assertEqual(config.__class__.__name__, "NewModelConfig")
+
+ # Test the dynamic module is loaded only once.
+ reloaded_config = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model", trust_remote_code=True)
+ self.assertIs(config.__class__, reloaded_config.__class__)
+
+ # Test config can be reloaded.
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ config.save_pretrained(tmp_dir)
+ reloaded_config = AutoConfig.from_pretrained(tmp_dir, trust_remote_code=True)
+ self.assertEqual(reloaded_config.__class__.__name__, "NewModelConfig")
+
+ # The configuration file is cached in the snapshot directory. So the module file is not changed after dumping
+ # to a temp dir. Because the revision of the configuration file is not changed.
+ # Test the dynamic module is loaded only once if the configuration file is not changed.
+ self.assertIs(config.__class__, reloaded_config.__class__)
+
+ # Test the dynamic module is reloaded if we force it.
+ reloaded_config = AutoConfig.from_pretrained(
+ "hf-internal-testing/test_dynamic_model", trust_remote_code=True, force_download=True
+ )
+ self.assertIsNot(config.__class__, reloaded_config.__class__)
+
+ def test_from_pretrained_dynamic_config_conflict(self):
+ class NewModelConfigLocal(BertConfig):
+ model_type = "new-model"
+
+ try:
+ AutoConfig.register("new-model", NewModelConfigLocal)
+ # If remote code is not set, the default is to use local
+ config = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model")
+ self.assertEqual(config.__class__.__name__, "NewModelConfigLocal")
+
+ # If remote code is disabled, we load the local one.
+ config = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model", trust_remote_code=False)
+ self.assertEqual(config.__class__.__name__, "NewModelConfigLocal")
+
+ # If remote is enabled, we load from the Hub
+ config = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model", trust_remote_code=True)
+ self.assertEqual(config.__class__.__name__, "NewModelConfig")
+
+ finally:
+ if "new-model" in CONFIG_MAPPING._extra_content:
+ del CONFIG_MAPPING._extra_content["new-model"]
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_feature_extraction_auto.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_feature_extraction_auto.py
new file mode 100644
index 0000000000000000000000000000000000000000..d36183a63c6a9d67ed31ded255ca1fccde87ce7f
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_feature_extraction_auto.py
@@ -0,0 +1,195 @@
+# 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.
+
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+import transformers
+from transformers import (
+ CONFIG_MAPPING,
+ FEATURE_EXTRACTOR_MAPPING,
+ AutoConfig,
+ AutoFeatureExtractor,
+ Wav2Vec2Config,
+ Wav2Vec2FeatureExtractor,
+)
+from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir
+
+
+sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils"))
+
+from test_module.custom_configuration import CustomConfig # noqa E402
+from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402
+
+
+SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR = get_tests_dir("fixtures")
+SAMPLE_FEATURE_EXTRACTION_CONFIG = get_tests_dir("fixtures/dummy_feature_extractor_config.json")
+SAMPLE_CONFIG = get_tests_dir("fixtures/dummy-config.json")
+
+
+class AutoFeatureExtractorTest(unittest.TestCase):
+ def setUp(self):
+ transformers.dynamic_module_utils.TIME_OUT_REMOTE_CODE = 0
+
+ def test_feature_extractor_from_model_shortcut(self):
+ config = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h")
+ self.assertIsInstance(config, Wav2Vec2FeatureExtractor)
+
+ def test_feature_extractor_from_local_directory_from_key(self):
+ config = AutoFeatureExtractor.from_pretrained(SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR)
+ self.assertIsInstance(config, Wav2Vec2FeatureExtractor)
+
+ def test_feature_extractor_from_local_directory_from_config(self):
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ model_config = Wav2Vec2Config()
+
+ # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
+ config_dict = AutoFeatureExtractor.from_pretrained(SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR).to_dict()
+
+ config_dict.pop("feature_extractor_type")
+ config = Wav2Vec2FeatureExtractor(**config_dict)
+
+ # save in new folder
+ model_config.save_pretrained(tmpdirname)
+ config.save_pretrained(tmpdirname)
+
+ config = AutoFeatureExtractor.from_pretrained(tmpdirname)
+
+ # make sure private variable is not incorrectly saved
+ dict_as_saved = json.loads(config.to_json_string())
+ self.assertTrue("_processor_class" not in dict_as_saved)
+
+ self.assertIsInstance(config, Wav2Vec2FeatureExtractor)
+
+ def test_feature_extractor_from_local_file(self):
+ config = AutoFeatureExtractor.from_pretrained(SAMPLE_FEATURE_EXTRACTION_CONFIG)
+ self.assertIsInstance(config, Wav2Vec2FeatureExtractor)
+
+ def test_repo_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError, "bert-base is not a local folder and is not a valid model identifier"
+ ):
+ _ = AutoFeatureExtractor.from_pretrained("bert-base")
+
+ def test_revision_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError, r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"
+ ):
+ _ = AutoFeatureExtractor.from_pretrained(DUMMY_UNKNOWN_IDENTIFIER, revision="aaaaaa")
+
+ def test_feature_extractor_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError,
+ "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.",
+ ):
+ _ = AutoFeatureExtractor.from_pretrained("hf-internal-testing/config-no-model")
+
+ def test_from_pretrained_dynamic_feature_extractor(self):
+ # If remote code is not set, we will time out when asking whether to load the model.
+ with self.assertRaises(ValueError):
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
+ "hf-internal-testing/test_dynamic_feature_extractor"
+ )
+ # If remote code is disabled, we can't load this config.
+ with self.assertRaises(ValueError):
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
+ "hf-internal-testing/test_dynamic_feature_extractor", trust_remote_code=False
+ )
+
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
+ "hf-internal-testing/test_dynamic_feature_extractor", trust_remote_code=True
+ )
+ self.assertEqual(feature_extractor.__class__.__name__, "NewFeatureExtractor")
+
+ # Test the dynamic module is loaded only once.
+ reloaded_feature_extractor = AutoFeatureExtractor.from_pretrained(
+ "hf-internal-testing/test_dynamic_feature_extractor", trust_remote_code=True
+ )
+ self.assertIs(feature_extractor.__class__, reloaded_feature_extractor.__class__)
+
+ # Test feature extractor can be reloaded.
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ feature_extractor.save_pretrained(tmp_dir)
+ reloaded_feature_extractor = AutoFeatureExtractor.from_pretrained(tmp_dir, trust_remote_code=True)
+ self.assertEqual(reloaded_feature_extractor.__class__.__name__, "NewFeatureExtractor")
+
+ # The feature extractor file is cached in the snapshot directory. So the module file is not changed after dumping
+ # to a temp dir. Because the revision of the module file is not changed.
+ # Test the dynamic module is loaded only once if the module file is not changed.
+ self.assertIs(feature_extractor.__class__, reloaded_feature_extractor.__class__)
+
+ # Test the dynamic module is reloaded if we force it.
+ reloaded_feature_extractor = AutoFeatureExtractor.from_pretrained(
+ "hf-internal-testing/test_dynamic_feature_extractor", trust_remote_code=True, force_download=True
+ )
+ self.assertIsNot(feature_extractor.__class__, reloaded_feature_extractor.__class__)
+
+ def test_new_feature_extractor_registration(self):
+ try:
+ AutoConfig.register("custom", CustomConfig)
+ AutoFeatureExtractor.register(CustomConfig, CustomFeatureExtractor)
+ # Trying to register something existing in the Transformers library will raise an error
+ with self.assertRaises(ValueError):
+ AutoFeatureExtractor.register(Wav2Vec2Config, Wav2Vec2FeatureExtractor)
+
+ # Now that the config is registered, it can be used as any other config with the auto-API
+ feature_extractor = CustomFeatureExtractor.from_pretrained(SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR)
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ feature_extractor.save_pretrained(tmp_dir)
+ new_feature_extractor = AutoFeatureExtractor.from_pretrained(tmp_dir)
+ self.assertIsInstance(new_feature_extractor, CustomFeatureExtractor)
+
+ finally:
+ if "custom" in CONFIG_MAPPING._extra_content:
+ del CONFIG_MAPPING._extra_content["custom"]
+ if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
+ del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
+
+ def test_from_pretrained_dynamic_feature_extractor_conflict(self):
+ class NewFeatureExtractor(Wav2Vec2FeatureExtractor):
+ is_local = True
+
+ try:
+ AutoConfig.register("custom", CustomConfig)
+ AutoFeatureExtractor.register(CustomConfig, NewFeatureExtractor)
+ # If remote code is not set, the default is to use local
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
+ "hf-internal-testing/test_dynamic_feature_extractor"
+ )
+ self.assertEqual(feature_extractor.__class__.__name__, "NewFeatureExtractor")
+ self.assertTrue(feature_extractor.is_local)
+
+ # If remote code is disabled, we load the local one.
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
+ "hf-internal-testing/test_dynamic_feature_extractor", trust_remote_code=False
+ )
+ self.assertEqual(feature_extractor.__class__.__name__, "NewFeatureExtractor")
+ self.assertTrue(feature_extractor.is_local)
+
+ # If remote is enabled, we load from the Hub
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
+ "hf-internal-testing/test_dynamic_feature_extractor", trust_remote_code=True
+ )
+ self.assertEqual(feature_extractor.__class__.__name__, "NewFeatureExtractor")
+ self.assertTrue(not hasattr(feature_extractor, "is_local"))
+
+ finally:
+ if "custom" in CONFIG_MAPPING._extra_content:
+ del CONFIG_MAPPING._extra_content["custom"]
+ if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
+ del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_image_processing_auto.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_image_processing_auto.py
new file mode 100644
index 0000000000000000000000000000000000000000..1becf25ae7c33ce4f4d39ed057fa71c662b6f8b8
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_image_processing_auto.py
@@ -0,0 +1,255 @@
+# 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.
+
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+import transformers
+from transformers import (
+ CONFIG_MAPPING,
+ IMAGE_PROCESSOR_MAPPING,
+ AutoConfig,
+ AutoImageProcessor,
+ CLIPConfig,
+ CLIPImageProcessor,
+ ViTImageProcessor,
+ ViTImageProcessorFast,
+)
+from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_torchvision, require_vision
+
+
+sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils"))
+
+from test_module.custom_configuration import CustomConfig # noqa E402
+from test_module.custom_image_processing import CustomImageProcessor # noqa E402
+
+
+class AutoImageProcessorTest(unittest.TestCase):
+ def setUp(self):
+ transformers.dynamic_module_utils.TIME_OUT_REMOTE_CODE = 0
+
+ def test_image_processor_from_model_shortcut(self):
+ config = AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32")
+ self.assertIsInstance(config, CLIPImageProcessor)
+
+ def test_image_processor_from_local_directory_from_key(self):
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ processor_tmpfile = Path(tmpdirname) / "preprocessor_config.json"
+ config_tmpfile = Path(tmpdirname) / "config.json"
+ json.dump(
+ {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"},
+ open(processor_tmpfile, "w"),
+ )
+ json.dump({"model_type": "clip"}, open(config_tmpfile, "w"))
+
+ config = AutoImageProcessor.from_pretrained(tmpdirname)
+ self.assertIsInstance(config, CLIPImageProcessor)
+
+ def test_image_processor_from_local_directory_from_feature_extractor_key(self):
+ # Ensure we can load the image processor from the feature extractor config
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ processor_tmpfile = Path(tmpdirname) / "preprocessor_config.json"
+ config_tmpfile = Path(tmpdirname) / "config.json"
+ json.dump(
+ {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"},
+ open(processor_tmpfile, "w"),
+ )
+ json.dump({"model_type": "clip"}, open(config_tmpfile, "w"))
+
+ config = AutoImageProcessor.from_pretrained(tmpdirname)
+ self.assertIsInstance(config, CLIPImageProcessor)
+
+ def test_image_processor_from_local_directory_from_config(self):
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ model_config = CLIPConfig()
+
+ # Create a dummy config file with image_proceesor_type
+ processor_tmpfile = Path(tmpdirname) / "preprocessor_config.json"
+ config_tmpfile = Path(tmpdirname) / "config.json"
+ json.dump(
+ {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"},
+ open(processor_tmpfile, "w"),
+ )
+ json.dump({"model_type": "clip"}, open(config_tmpfile, "w"))
+
+ # remove image_processor_type to make sure config.json alone is enough to load image processor locally
+ config_dict = AutoImageProcessor.from_pretrained(tmpdirname).to_dict()
+
+ config_dict.pop("image_processor_type")
+ config = CLIPImageProcessor(**config_dict)
+
+ # save in new folder
+ model_config.save_pretrained(tmpdirname)
+ config.save_pretrained(tmpdirname)
+
+ config = AutoImageProcessor.from_pretrained(tmpdirname)
+
+ # make sure private variable is not incorrectly saved
+ dict_as_saved = json.loads(config.to_json_string())
+ self.assertTrue("_processor_class" not in dict_as_saved)
+
+ self.assertIsInstance(config, CLIPImageProcessor)
+
+ def test_image_processor_from_local_file(self):
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ processor_tmpfile = Path(tmpdirname) / "preprocessor_config.json"
+ json.dump(
+ {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"},
+ open(processor_tmpfile, "w"),
+ )
+
+ config = AutoImageProcessor.from_pretrained(processor_tmpfile)
+ self.assertIsInstance(config, CLIPImageProcessor)
+
+ def test_repo_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError, "clip-base is not a local folder and is not a valid model identifier"
+ ):
+ _ = AutoImageProcessor.from_pretrained("clip-base")
+
+ def test_revision_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError, r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"
+ ):
+ _ = AutoImageProcessor.from_pretrained(DUMMY_UNKNOWN_IDENTIFIER, revision="aaaaaa")
+
+ def test_image_processor_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError,
+ "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.",
+ ):
+ _ = AutoImageProcessor.from_pretrained("hf-internal-testing/config-no-model")
+
+ @require_vision
+ @require_torchvision
+ def test_use_fast_selection(self):
+ checkpoint = "hf-internal-testing/tiny-random-vit"
+
+ # TODO: @yoni, change in v4.48 (when use_fast set to True by default)
+ # Slow image processor is selected by default
+ image_processor = AutoImageProcessor.from_pretrained(checkpoint)
+ self.assertIsInstance(image_processor, ViTImageProcessor)
+
+ # Fast image processor is selected when use_fast=True
+ image_processor = AutoImageProcessor.from_pretrained(checkpoint, use_fast=True)
+ self.assertIsInstance(image_processor, ViTImageProcessorFast)
+
+ # Slow image processor is selected when use_fast=False
+ image_processor = AutoImageProcessor.from_pretrained(checkpoint, use_fast=False)
+ self.assertIsInstance(image_processor, ViTImageProcessor)
+
+ def test_from_pretrained_dynamic_image_processor(self):
+ # If remote code is not set, we will time out when asking whether to load the model.
+ with self.assertRaises(ValueError):
+ image_processor = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor")
+ # If remote code is disabled, we can't load this config.
+ with self.assertRaises(ValueError):
+ image_processor = AutoImageProcessor.from_pretrained(
+ "hf-internal-testing/test_dynamic_image_processor", trust_remote_code=False
+ )
+
+ image_processor = AutoImageProcessor.from_pretrained(
+ "hf-internal-testing/test_dynamic_image_processor", trust_remote_code=True
+ )
+ self.assertEqual(image_processor.__class__.__name__, "NewImageProcessor")
+
+ # Test the dynamic module is loaded only once.
+ reloaded_image_processor = AutoImageProcessor.from_pretrained(
+ "hf-internal-testing/test_dynamic_image_processor", trust_remote_code=True
+ )
+ self.assertIs(image_processor.__class__, reloaded_image_processor.__class__)
+
+ # Test image processor can be reloaded.
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ image_processor.save_pretrained(tmp_dir)
+ reloaded_image_processor = AutoImageProcessor.from_pretrained(tmp_dir, trust_remote_code=True)
+ self.assertEqual(reloaded_image_processor.__class__.__name__, "NewImageProcessor")
+
+ # The image processor file is cached in the snapshot directory. So the module file is not changed after dumping
+ # to a temp dir. Because the revision of the module file is not changed.
+ # Test the dynamic module is loaded only once if the module file is not changed.
+ self.assertIs(image_processor.__class__, reloaded_image_processor.__class__)
+
+ # Test the dynamic module is reloaded if we force it.
+ reloaded_image_processor = AutoImageProcessor.from_pretrained(
+ "hf-internal-testing/test_dynamic_image_processor", trust_remote_code=True, force_download=True
+ )
+ self.assertIsNot(image_processor.__class__, reloaded_image_processor.__class__)
+
+ def test_new_image_processor_registration(self):
+ try:
+ AutoConfig.register("custom", CustomConfig)
+ AutoImageProcessor.register(CustomConfig, CustomImageProcessor)
+ # Trying to register something existing in the Transformers library will raise an error
+ with self.assertRaises(ValueError):
+ AutoImageProcessor.register(CLIPConfig, CLIPImageProcessor)
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ processor_tmpfile = Path(tmpdirname) / "preprocessor_config.json"
+ config_tmpfile = Path(tmpdirname) / "config.json"
+ json.dump(
+ {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"},
+ open(processor_tmpfile, "w"),
+ )
+ json.dump({"model_type": "clip"}, open(config_tmpfile, "w"))
+
+ image_processor = CustomImageProcessor.from_pretrained(tmpdirname)
+
+ # Now that the config is registered, it can be used as any other config with the auto-API
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ image_processor.save_pretrained(tmp_dir)
+ new_image_processor = AutoImageProcessor.from_pretrained(tmp_dir)
+ self.assertIsInstance(new_image_processor, CustomImageProcessor)
+
+ finally:
+ if "custom" in CONFIG_MAPPING._extra_content:
+ del CONFIG_MAPPING._extra_content["custom"]
+ if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
+ del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
+
+ def test_from_pretrained_dynamic_image_processor_conflict(self):
+ class NewImageProcessor(CLIPImageProcessor):
+ is_local = True
+
+ try:
+ AutoConfig.register("custom", CustomConfig)
+ AutoImageProcessor.register(CustomConfig, NewImageProcessor)
+ # If remote code is not set, the default is to use local
+ image_processor = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor")
+ self.assertEqual(image_processor.__class__.__name__, "NewImageProcessor")
+ self.assertTrue(image_processor.is_local)
+
+ # If remote code is disabled, we load the local one.
+ image_processor = AutoImageProcessor.from_pretrained(
+ "hf-internal-testing/test_dynamic_image_processor", trust_remote_code=False
+ )
+ self.assertEqual(image_processor.__class__.__name__, "NewImageProcessor")
+ self.assertTrue(image_processor.is_local)
+
+ # If remote is enabled, we load from the Hub
+ image_processor = AutoImageProcessor.from_pretrained(
+ "hf-internal-testing/test_dynamic_image_processor", trust_remote_code=True
+ )
+ self.assertEqual(image_processor.__class__.__name__, "NewImageProcessor")
+ self.assertTrue(not hasattr(image_processor, "is_local"))
+
+ finally:
+ if "custom" in CONFIG_MAPPING._extra_content:
+ del CONFIG_MAPPING._extra_content["custom"]
+ if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
+ del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_modeling_auto.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_modeling_auto.py
new file mode 100644
index 0000000000000000000000000000000000000000..5766b4adae871da69938f997be135fa6be6b3484
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_modeling_auto.py
@@ -0,0 +1,591 @@
+# coding=utf-8
+# 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 copy
+import sys
+import tempfile
+import unittest
+from collections import OrderedDict
+from pathlib import Path
+
+import pytest
+from huggingface_hub import Repository
+
+import transformers
+from transformers import BertConfig, GPT2Model, is_safetensors_available, is_torch_available
+from transformers.models.auto.configuration_auto import CONFIG_MAPPING
+from transformers.testing_utils import (
+ DUMMY_UNKNOWN_IDENTIFIER,
+ SMALL_MODEL_IDENTIFIER,
+ RequestCounter,
+ require_torch,
+ slow,
+)
+
+from ..bert.test_modeling_bert import BertModelTester
+
+
+sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils"))
+
+from test_module.custom_configuration import CustomConfig # noqa E402
+
+
+if is_torch_available():
+ import torch
+ from test_module.custom_modeling import CustomModel
+
+ from transformers import (
+ AutoBackbone,
+ AutoConfig,
+ AutoModel,
+ AutoModelForCausalLM,
+ AutoModelForMaskedLM,
+ AutoModelForPreTraining,
+ AutoModelForQuestionAnswering,
+ AutoModelForSeq2SeqLM,
+ AutoModelForSequenceClassification,
+ AutoModelForTableQuestionAnswering,
+ AutoModelForTokenClassification,
+ AutoModelWithLMHead,
+ BertForMaskedLM,
+ BertForPreTraining,
+ BertForQuestionAnswering,
+ BertForSequenceClassification,
+ BertForTokenClassification,
+ BertModel,
+ FunnelBaseModel,
+ FunnelModel,
+ GenerationMixin,
+ GPT2Config,
+ GPT2LMHeadModel,
+ ResNetBackbone,
+ RobertaForMaskedLM,
+ T5Config,
+ T5ForConditionalGeneration,
+ TapasConfig,
+ TapasForQuestionAnswering,
+ TimmBackbone,
+ )
+ from transformers.models.auto.modeling_auto import (
+ MODEL_FOR_CAUSAL_LM_MAPPING,
+ MODEL_FOR_MASKED_LM_MAPPING,
+ MODEL_FOR_PRETRAINING_MAPPING,
+ MODEL_FOR_QUESTION_ANSWERING_MAPPING,
+ MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
+ MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
+ MODEL_MAPPING,
+ )
+
+
+@require_torch
+class AutoModelTest(unittest.TestCase):
+ def setUp(self):
+ transformers.dynamic_module_utils.TIME_OUT_REMOTE_CODE = 0
+
+ @slow
+ def test_model_from_pretrained(self):
+ model_name = "google-bert/bert-base-uncased"
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, BertConfig)
+
+ model = AutoModel.from_pretrained(model_name)
+ model, loading_info = AutoModel.from_pretrained(model_name, output_loading_info=True)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, BertModel)
+
+ self.assertEqual(len(loading_info["missing_keys"]), 0)
+ # When using PyTorch checkpoint, the expected value is `8`. With `safetensors` checkpoint (if it is
+ # installed), the expected value becomes `7`.
+ EXPECTED_NUM_OF_UNEXPECTED_KEYS = 7 if is_safetensors_available() else 8
+ self.assertEqual(len(loading_info["unexpected_keys"]), EXPECTED_NUM_OF_UNEXPECTED_KEYS)
+ self.assertEqual(len(loading_info["mismatched_keys"]), 0)
+ self.assertEqual(len(loading_info["error_msgs"]), 0)
+
+ @slow
+ def test_model_for_pretraining_from_pretrained(self):
+ model_name = "google-bert/bert-base-uncased"
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, BertConfig)
+
+ model = AutoModelForPreTraining.from_pretrained(model_name)
+ model, loading_info = AutoModelForPreTraining.from_pretrained(model_name, output_loading_info=True)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, BertForPreTraining)
+ # Only one value should not be initialized and in the missing keys.
+ for key, value in loading_info.items():
+ self.assertEqual(len(value), 0)
+
+ @slow
+ def test_lmhead_model_from_pretrained(self):
+ model_name = "google-bert/bert-base-uncased"
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, BertConfig)
+
+ model = AutoModelWithLMHead.from_pretrained(model_name)
+ model, loading_info = AutoModelWithLMHead.from_pretrained(model_name, output_loading_info=True)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, BertForMaskedLM)
+
+ @slow
+ def test_model_for_causal_lm(self):
+ model_name = "openai-community/gpt2"
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, GPT2Config)
+
+ model = AutoModelForCausalLM.from_pretrained(model_name)
+ model, loading_info = AutoModelForCausalLM.from_pretrained(model_name, output_loading_info=True)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, GPT2LMHeadModel)
+
+ @slow
+ def test_model_for_masked_lm(self):
+ model_name = "google-bert/bert-base-uncased"
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, BertConfig)
+
+ model = AutoModelForMaskedLM.from_pretrained(model_name)
+ model, loading_info = AutoModelForMaskedLM.from_pretrained(model_name, output_loading_info=True)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, BertForMaskedLM)
+
+ @slow
+ def test_model_for_encoder_decoder_lm(self):
+ model_name = "google-t5/t5-base"
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, T5Config)
+
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
+ model, loading_info = AutoModelForSeq2SeqLM.from_pretrained(model_name, output_loading_info=True)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, T5ForConditionalGeneration)
+
+ @slow
+ def test_sequence_classification_model_from_pretrained(self):
+ model_name = "google-bert/bert-base-uncased"
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, BertConfig)
+
+ model = AutoModelForSequenceClassification.from_pretrained(model_name)
+ model, loading_info = AutoModelForSequenceClassification.from_pretrained(model_name, output_loading_info=True)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, BertForSequenceClassification)
+
+ @slow
+ def test_question_answering_model_from_pretrained(self):
+ model_name = "google-bert/bert-base-uncased"
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, BertConfig)
+
+ model = AutoModelForQuestionAnswering.from_pretrained(model_name)
+ model, loading_info = AutoModelForQuestionAnswering.from_pretrained(model_name, output_loading_info=True)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, BertForQuestionAnswering)
+
+ @slow
+ def test_table_question_answering_model_from_pretrained(self):
+ model_name = "google/tapas-base"
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, TapasConfig)
+
+ model = AutoModelForTableQuestionAnswering.from_pretrained(model_name)
+ model, loading_info = AutoModelForTableQuestionAnswering.from_pretrained(model_name, output_loading_info=True)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, TapasForQuestionAnswering)
+
+ @slow
+ def test_token_classification_model_from_pretrained(self):
+ model_name = "google-bert/bert-base-uncased"
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, BertConfig)
+
+ model = AutoModelForTokenClassification.from_pretrained(model_name)
+ model, loading_info = AutoModelForTokenClassification.from_pretrained(model_name, output_loading_info=True)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, BertForTokenClassification)
+
+ @slow
+ def test_auto_backbone_timm_model_from_pretrained(self):
+ # Configs can't be loaded for timm models
+ model = AutoBackbone.from_pretrained("resnet18", use_timm_backbone=True)
+
+ with pytest.raises(ValueError):
+ # We can't pass output_loading_info=True as we're loading from timm
+ AutoBackbone.from_pretrained("resnet18", use_timm_backbone=True, output_loading_info=True)
+
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, TimmBackbone)
+
+ # Check kwargs are correctly passed to the backbone
+ model = AutoBackbone.from_pretrained("resnet18", use_timm_backbone=True, out_indices=(-2, -1))
+ self.assertEqual(model.out_indices, [-2, -1])
+
+ # Check out_features cannot be passed to Timm backbones
+ with self.assertRaises(ValueError):
+ _ = AutoBackbone.from_pretrained("resnet18", use_timm_backbone=True, out_features=["stage1"])
+
+ @slow
+ def test_auto_backbone_from_pretrained(self):
+ model = AutoBackbone.from_pretrained("microsoft/resnet-18")
+ model, loading_info = AutoBackbone.from_pretrained("microsoft/resnet-18", output_loading_info=True)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, ResNetBackbone)
+
+ # Check kwargs are correctly passed to the backbone
+ model = AutoBackbone.from_pretrained("microsoft/resnet-18", out_indices=[-2, -1])
+ self.assertEqual(model.out_indices, [-2, -1])
+ self.assertEqual(model.out_features, ["stage3", "stage4"])
+
+ model = AutoBackbone.from_pretrained("microsoft/resnet-18", out_features=["stage2", "stage4"])
+ self.assertEqual(model.out_indices, [2, 4])
+ self.assertEqual(model.out_features, ["stage2", "stage4"])
+
+ def test_from_pretrained_identifier(self):
+ model = AutoModelWithLMHead.from_pretrained(SMALL_MODEL_IDENTIFIER)
+ self.assertIsInstance(model, BertForMaskedLM)
+ self.assertEqual(model.num_parameters(), 14410)
+ self.assertEqual(model.num_parameters(only_trainable=True), 14410)
+
+ def test_from_identifier_from_model_type(self):
+ model = AutoModelWithLMHead.from_pretrained(DUMMY_UNKNOWN_IDENTIFIER)
+ self.assertIsInstance(model, RobertaForMaskedLM)
+ self.assertEqual(model.num_parameters(), 14410)
+ self.assertEqual(model.num_parameters(only_trainable=True), 14410)
+
+ def test_from_pretrained_with_tuple_values(self):
+ # For the auto model mapping, FunnelConfig has two models: FunnelModel and FunnelBaseModel
+ model = AutoModel.from_pretrained("sgugger/funnel-random-tiny")
+ self.assertIsInstance(model, FunnelModel)
+
+ config = copy.deepcopy(model.config)
+ config.architectures = ["FunnelBaseModel"]
+ model = AutoModel.from_config(config)
+ self.assertIsInstance(model, FunnelBaseModel)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ model.save_pretrained(tmp_dir)
+ model = AutoModel.from_pretrained(tmp_dir)
+ self.assertIsInstance(model, FunnelBaseModel)
+
+ def test_from_pretrained_dynamic_model_local(self):
+ try:
+ AutoConfig.register("custom", CustomConfig)
+ AutoModel.register(CustomConfig, CustomModel)
+
+ config = CustomConfig(hidden_size=32)
+ model = CustomModel(config)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ model.save_pretrained(tmp_dir)
+
+ new_model = AutoModel.from_pretrained(tmp_dir, trust_remote_code=True)
+ for p1, p2 in zip(model.parameters(), new_model.parameters()):
+ self.assertTrue(torch.equal(p1, p2))
+
+ finally:
+ if "custom" in CONFIG_MAPPING._extra_content:
+ del CONFIG_MAPPING._extra_content["custom"]
+ if CustomConfig in MODEL_MAPPING._extra_content:
+ del MODEL_MAPPING._extra_content[CustomConfig]
+
+ def test_from_pretrained_dynamic_model_distant(self):
+ # If remote code is not set, we will time out when asking whether to load the model.
+ with self.assertRaises(ValueError):
+ model = AutoModel.from_pretrained("hf-internal-testing/test_dynamic_model")
+ # If remote code is disabled, we can't load this config.
+ with self.assertRaises(ValueError):
+ model = AutoModel.from_pretrained("hf-internal-testing/test_dynamic_model", trust_remote_code=False)
+
+ model = AutoModel.from_pretrained("hf-internal-testing/test_dynamic_model", trust_remote_code=True)
+ self.assertEqual(model.__class__.__name__, "NewModel")
+
+ # Test the dynamic module is loaded only once.
+ reloaded_model = AutoModel.from_pretrained("hf-internal-testing/test_dynamic_model", trust_remote_code=True)
+ self.assertIs(model.__class__, reloaded_model.__class__)
+
+ # Test model can be reloaded.
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ model.save_pretrained(tmp_dir)
+ reloaded_model = AutoModel.from_pretrained(tmp_dir, trust_remote_code=True)
+
+ self.assertEqual(reloaded_model.__class__.__name__, "NewModel")
+ for p1, p2 in zip(model.parameters(), reloaded_model.parameters()):
+ self.assertTrue(torch.equal(p1, p2))
+
+ # The model file is cached in the snapshot directory. So the module file is not changed after dumping
+ # to a temp dir. Because the revision of the module file is not changed.
+ # Test the dynamic module is loaded only once if the module file is not changed.
+ self.assertIs(model.__class__, reloaded_model.__class__)
+
+ # Test the dynamic module is reloaded if we force it.
+ reloaded_model = AutoModel.from_pretrained(
+ "hf-internal-testing/test_dynamic_model", trust_remote_code=True, force_download=True
+ )
+ self.assertIsNot(model.__class__, reloaded_model.__class__)
+
+ # This one uses a relative import to a util file, this checks it is downloaded and used properly.
+ model = AutoModel.from_pretrained("hf-internal-testing/test_dynamic_model_with_util", trust_remote_code=True)
+ self.assertEqual(model.__class__.__name__, "NewModel")
+
+ # Test the dynamic module is loaded only once.
+ reloaded_model = AutoModel.from_pretrained(
+ "hf-internal-testing/test_dynamic_model_with_util", trust_remote_code=True
+ )
+ self.assertIs(model.__class__, reloaded_model.__class__)
+
+ # Test model can be reloaded.
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ model.save_pretrained(tmp_dir)
+ reloaded_model = AutoModel.from_pretrained(tmp_dir, trust_remote_code=True)
+
+ self.assertEqual(reloaded_model.__class__.__name__, "NewModel")
+ for p1, p2 in zip(model.parameters(), reloaded_model.parameters()):
+ self.assertTrue(torch.equal(p1, p2))
+
+ # The model file is cached in the snapshot directory. So the module file is not changed after dumping
+ # to a temp dir. Because the revision of the module file is not changed.
+ # Test the dynamic module is loaded only once if the module file is not changed.
+ self.assertIs(model.__class__, reloaded_model.__class__)
+
+ # Test the dynamic module is reloaded if we force it.
+ reloaded_model = AutoModel.from_pretrained(
+ "hf-internal-testing/test_dynamic_model_with_util", trust_remote_code=True, force_download=True
+ )
+ self.assertIsNot(model.__class__, reloaded_model.__class__)
+
+ def test_from_pretrained_dynamic_model_distant_with_ref(self):
+ model = AutoModel.from_pretrained("hf-internal-testing/ref_to_test_dynamic_model", trust_remote_code=True)
+ self.assertEqual(model.__class__.__name__, "NewModel")
+
+ # Test model can be reloaded.
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ model.save_pretrained(tmp_dir)
+ reloaded_model = AutoModel.from_pretrained(tmp_dir, trust_remote_code=True)
+
+ self.assertEqual(reloaded_model.__class__.__name__, "NewModel")
+ for p1, p2 in zip(model.parameters(), reloaded_model.parameters()):
+ self.assertTrue(torch.equal(p1, p2))
+
+ # This one uses a relative import to a util file, this checks it is downloaded and used properly.
+ model = AutoModel.from_pretrained(
+ "hf-internal-testing/ref_to_test_dynamic_model_with_util", trust_remote_code=True
+ )
+ self.assertEqual(model.__class__.__name__, "NewModel")
+
+ # Test model can be reloaded.
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ model.save_pretrained(tmp_dir)
+ reloaded_model = AutoModel.from_pretrained(tmp_dir, trust_remote_code=True)
+
+ self.assertEqual(reloaded_model.__class__.__name__, "NewModel")
+ for p1, p2 in zip(model.parameters(), reloaded_model.parameters()):
+ self.assertTrue(torch.equal(p1, p2))
+
+ def test_from_pretrained_dynamic_model_with_period(self):
+ # We used to have issues where repos with "." in the name would cause issues because the Python
+ # import machinery would treat that as a directory separator, so we test that case
+
+ # If remote code is not set, we will time out when asking whether to load the model.
+ with self.assertRaises(ValueError):
+ model = AutoModel.from_pretrained("hf-internal-testing/test_dynamic_model_v1.0")
+ # If remote code is disabled, we can't load this config.
+ with self.assertRaises(ValueError):
+ model = AutoModel.from_pretrained("hf-internal-testing/test_dynamic_model_v1.0", trust_remote_code=False)
+
+ model = AutoModel.from_pretrained("hf-internal-testing/test_dynamic_model_v1.0", trust_remote_code=True)
+ self.assertEqual(model.__class__.__name__, "NewModel")
+
+ # Test that it works with a custom cache dir too
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ model = AutoModel.from_pretrained(
+ "hf-internal-testing/test_dynamic_model_v1.0", trust_remote_code=True, cache_dir=tmp_dir
+ )
+ self.assertEqual(model.__class__.__name__, "NewModel")
+
+ def test_new_model_registration(self):
+ AutoConfig.register("custom", CustomConfig)
+
+ auto_classes = [
+ AutoModel,
+ AutoModelForCausalLM,
+ AutoModelForMaskedLM,
+ AutoModelForPreTraining,
+ AutoModelForQuestionAnswering,
+ AutoModelForSequenceClassification,
+ AutoModelForTokenClassification,
+ ]
+
+ try:
+ for auto_class in auto_classes:
+ with self.subTest(auto_class.__name__):
+ # Wrong config class will raise an error
+ with self.assertRaises(ValueError):
+ auto_class.register(BertConfig, CustomModel)
+ auto_class.register(CustomConfig, CustomModel)
+ # Trying to register something existing in the Transformers library will raise an error
+ with self.assertRaises(ValueError):
+ auto_class.register(BertConfig, BertModel)
+
+ # Now that the config is registered, it can be used as any other config with the auto-API
+ tiny_config = BertModelTester(self).get_config()
+ config = CustomConfig(**tiny_config.to_dict())
+ model = auto_class.from_config(config)
+ self.assertIsInstance(model, CustomModel)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ model.save_pretrained(tmp_dir)
+ new_model = auto_class.from_pretrained(tmp_dir)
+ # The model is a CustomModel but from the new dynamically imported class.
+ self.assertIsInstance(new_model, CustomModel)
+
+ finally:
+ if "custom" in CONFIG_MAPPING._extra_content:
+ del CONFIG_MAPPING._extra_content["custom"]
+ for mapping in (
+ MODEL_MAPPING,
+ MODEL_FOR_PRETRAINING_MAPPING,
+ MODEL_FOR_QUESTION_ANSWERING_MAPPING,
+ MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
+ MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
+ MODEL_FOR_CAUSAL_LM_MAPPING,
+ MODEL_FOR_MASKED_LM_MAPPING,
+ ):
+ if CustomConfig in mapping._extra_content:
+ del mapping._extra_content[CustomConfig]
+
+ def test_from_pretrained_dynamic_model_conflict(self):
+ class NewModelConfigLocal(BertConfig):
+ model_type = "new-model"
+
+ class NewModel(BertModel):
+ config_class = NewModelConfigLocal
+
+ try:
+ AutoConfig.register("new-model", NewModelConfigLocal)
+ AutoModel.register(NewModelConfigLocal, NewModel)
+ # If remote code is not set, the default is to use local
+ model = AutoModel.from_pretrained("hf-internal-testing/test_dynamic_model")
+ self.assertEqual(model.config.__class__.__name__, "NewModelConfigLocal")
+
+ # If remote code is disabled, we load the local one.
+ model = AutoModel.from_pretrained("hf-internal-testing/test_dynamic_model", trust_remote_code=False)
+ self.assertEqual(model.config.__class__.__name__, "NewModelConfigLocal")
+
+ # If remote is enabled, we load from the Hub
+ model = AutoModel.from_pretrained("hf-internal-testing/test_dynamic_model", trust_remote_code=True)
+ self.assertEqual(model.config.__class__.__name__, "NewModelConfig")
+
+ finally:
+ if "new-model" in CONFIG_MAPPING._extra_content:
+ del CONFIG_MAPPING._extra_content["new-model"]
+ if NewModelConfigLocal in MODEL_MAPPING._extra_content:
+ del MODEL_MAPPING._extra_content[NewModelConfigLocal]
+
+ def test_repo_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError, "bert-base is not a local folder and is not a valid model identifier"
+ ):
+ _ = AutoModel.from_pretrained("bert-base")
+
+ def test_revision_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError, r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"
+ ):
+ _ = AutoModel.from_pretrained(DUMMY_UNKNOWN_IDENTIFIER, revision="aaaaaa")
+
+ def test_model_file_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError,
+ "hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin",
+ ):
+ _ = AutoModel.from_pretrained("hf-internal-testing/config-no-model")
+
+ def test_model_from_tf_suggestion(self):
+ with self.assertRaisesRegex(EnvironmentError, "Use `from_tf=True` to load this model"):
+ _ = AutoModel.from_pretrained("hf-internal-testing/tiny-bert-tf-only")
+
+ def test_model_from_flax_suggestion(self):
+ with self.assertRaisesRegex(EnvironmentError, "Use `from_flax=True` to load this model"):
+ _ = AutoModel.from_pretrained("hf-internal-testing/tiny-bert-flax-only")
+
+ def test_cached_model_has_minimum_calls_to_head(self):
+ # Make sure we have cached the model.
+ _ = AutoModel.from_pretrained("hf-internal-testing/tiny-random-bert")
+ with RequestCounter() as counter:
+ _ = AutoModel.from_pretrained("hf-internal-testing/tiny-random-bert")
+ self.assertEqual(counter["GET"], 0)
+ self.assertEqual(counter["HEAD"], 1)
+ self.assertEqual(counter.total_calls, 1)
+
+ # With a sharded checkpoint
+ _ = AutoModel.from_pretrained("hf-internal-testing/tiny-random-bert-sharded")
+ with RequestCounter() as counter:
+ _ = AutoModel.from_pretrained("hf-internal-testing/tiny-random-bert-sharded")
+ self.assertEqual(counter["GET"], 0)
+ self.assertEqual(counter["HEAD"], 1)
+ self.assertEqual(counter.total_calls, 1)
+
+ def test_attr_not_existing(self):
+ from transformers.models.auto.auto_factory import _LazyAutoMapping
+
+ _CONFIG_MAPPING_NAMES = OrderedDict([("bert", "BertConfig")])
+ _MODEL_MAPPING_NAMES = OrderedDict([("bert", "GhostModel")])
+ _MODEL_MAPPING = _LazyAutoMapping(_CONFIG_MAPPING_NAMES, _MODEL_MAPPING_NAMES)
+
+ with pytest.raises(ValueError, match=r"Could not find GhostModel neither in .* nor in .*!"):
+ _MODEL_MAPPING[BertConfig]
+
+ _MODEL_MAPPING_NAMES = OrderedDict([("bert", "BertModel")])
+ _MODEL_MAPPING = _LazyAutoMapping(_CONFIG_MAPPING_NAMES, _MODEL_MAPPING_NAMES)
+ self.assertEqual(_MODEL_MAPPING[BertConfig], BertModel)
+
+ _MODEL_MAPPING_NAMES = OrderedDict([("bert", "GPT2Model")])
+ _MODEL_MAPPING = _LazyAutoMapping(_CONFIG_MAPPING_NAMES, _MODEL_MAPPING_NAMES)
+ self.assertEqual(_MODEL_MAPPING[BertConfig], GPT2Model)
+
+ def test_dynamic_saving_from_local_repo(self):
+ with tempfile.TemporaryDirectory() as tmp_dir, tempfile.TemporaryDirectory() as tmp_dir_out:
+ _ = Repository(local_dir=tmp_dir, clone_from="hf-internal-testing/tiny-random-custom-architecture")
+ model = AutoModelForCausalLM.from_pretrained(tmp_dir, trust_remote_code=True)
+ model.save_pretrained(tmp_dir_out)
+ _ = AutoModelForCausalLM.from_pretrained(tmp_dir_out, trust_remote_code=True)
+ self.assertTrue((Path(tmp_dir_out) / "modeling_fake_custom.py").is_file())
+ self.assertTrue((Path(tmp_dir_out) / "configuration_fake_custom.py").is_file())
+
+ def test_custom_model_patched_generation_inheritance(self):
+ """
+ Tests that our inheritance patching for generate-compatible models works as expected. Without this feature,
+ old Hub models lose the ability to call `generate`.
+ """
+ model = AutoModelForCausalLM.from_pretrained(
+ "hf-internal-testing/test_dynamic_model_generation", trust_remote_code=True
+ )
+ self.assertTrue(model.__class__.__name__ == "NewModelForCausalLM")
+
+ # It inherits from GenerationMixin. This means it can `generate`. Because `PreTrainedModel` is scheduled to
+ # stop inheriting from `GenerationMixin` in v4.50, this check will fail if patching is not present.
+ self.assertTrue(isinstance(model, GenerationMixin))
+ # More precisely, it directly inherits from GenerationMixin. This check would fail prior to v4.45 (inheritance
+ # patching was added in v4.45)
+ self.assertTrue("GenerationMixin" in str(model.__class__.__bases__))
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_modeling_flax_auto.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_modeling_flax_auto.py
new file mode 100644
index 0000000000000000000000000000000000000000..8880972e044e401c8a9a3ba63d80feab79bdc800
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_modeling_flax_auto.py
@@ -0,0 +1,102 @@
+# 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 unittest
+
+from transformers import AutoConfig, AutoTokenizer, BertConfig, TensorType, is_flax_available
+from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, slow
+
+
+if is_flax_available():
+ import jax
+
+ from transformers.models.auto.modeling_flax_auto import FlaxAutoModel
+ from transformers.models.bert.modeling_flax_bert import FlaxBertModel
+ from transformers.models.roberta.modeling_flax_roberta import FlaxRobertaModel
+
+
+@require_flax
+class FlaxAutoModelTest(unittest.TestCase):
+ @slow
+ def test_bert_from_pretrained(self):
+ for model_name in ["google-bert/bert-base-cased", "google-bert/bert-large-uncased"]:
+ with self.subTest(model_name):
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, BertConfig)
+
+ model = FlaxAutoModel.from_pretrained(model_name)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, FlaxBertModel)
+
+ @slow
+ def test_roberta_from_pretrained(self):
+ for model_name in ["FacebookAI/roberta-base", "FacebookAI/roberta-large"]:
+ with self.subTest(model_name):
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, BertConfig)
+
+ model = FlaxAutoModel.from_pretrained(model_name)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, FlaxRobertaModel)
+
+ @slow
+ def test_bert_jax_jit(self):
+ for model_name in ["google-bert/bert-base-cased", "google-bert/bert-large-uncased"]:
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
+ model = FlaxBertModel.from_pretrained(model_name)
+ tokens = tokenizer("Do you support jax jitted function?", return_tensors=TensorType.JAX)
+
+ @jax.jit
+ def eval(**kwargs):
+ return model(**kwargs)
+
+ eval(**tokens).block_until_ready()
+
+ @slow
+ def test_roberta_jax_jit(self):
+ for model_name in ["FacebookAI/roberta-base", "FacebookAI/roberta-large"]:
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
+ model = FlaxRobertaModel.from_pretrained(model_name)
+ tokens = tokenizer("Do you support jax jitted function?", return_tensors=TensorType.JAX)
+
+ @jax.jit
+ def eval(**kwargs):
+ return model(**kwargs)
+
+ eval(**tokens).block_until_ready()
+
+ def test_repo_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError, "bert-base is not a local folder and is not a valid model identifier"
+ ):
+ _ = FlaxAutoModel.from_pretrained("bert-base")
+
+ def test_revision_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError, r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"
+ ):
+ _ = FlaxAutoModel.from_pretrained(DUMMY_UNKNOWN_IDENTIFIER, revision="aaaaaa")
+
+ def test_model_file_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError,
+ "hf-internal-testing/config-no-model does not appear to have a file named flax_model.msgpack",
+ ):
+ _ = FlaxAutoModel.from_pretrained("hf-internal-testing/config-no-model")
+
+ def test_model_from_pt_suggestion(self):
+ with self.assertRaisesRegex(EnvironmentError, "Use `from_pt=True` to load this model"):
+ _ = FlaxAutoModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only")
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_modeling_tf_auto.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_modeling_tf_auto.py
new file mode 100644
index 0000000000000000000000000000000000000000..a63d9fbe4cf14c6bf65e290a4373710595de7182
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_modeling_tf_auto.py
@@ -0,0 +1,310 @@
+# coding=utf-8
+# 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 __future__ import annotations
+
+import copy
+import tempfile
+import unittest
+
+from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPT2Config, T5Config, TapasConfig, is_tf_available
+from transformers.testing_utils import (
+ DUMMY_UNKNOWN_IDENTIFIER,
+ SMALL_MODEL_IDENTIFIER,
+ RequestCounter,
+ require_tensorflow_probability,
+ require_tf,
+ slow,
+)
+
+from ..bert.test_modeling_bert import BertModelTester
+
+
+if is_tf_available():
+ from transformers import (
+ TFAutoModel,
+ TFAutoModelForCausalLM,
+ TFAutoModelForMaskedLM,
+ TFAutoModelForPreTraining,
+ TFAutoModelForQuestionAnswering,
+ TFAutoModelForSeq2SeqLM,
+ TFAutoModelForSequenceClassification,
+ TFAutoModelForTableQuestionAnswering,
+ TFAutoModelForTokenClassification,
+ TFAutoModelWithLMHead,
+ TFBertForMaskedLM,
+ TFBertForPreTraining,
+ TFBertForQuestionAnswering,
+ TFBertForSequenceClassification,
+ TFBertModel,
+ TFFunnelBaseModel,
+ TFFunnelModel,
+ TFGPT2LMHeadModel,
+ TFRobertaForMaskedLM,
+ TFT5ForConditionalGeneration,
+ TFTapasForQuestionAnswering,
+ )
+ from transformers.models.auto.modeling_tf_auto import (
+ TF_MODEL_FOR_CAUSAL_LM_MAPPING,
+ TF_MODEL_FOR_MASKED_LM_MAPPING,
+ TF_MODEL_FOR_PRETRAINING_MAPPING,
+ TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
+ TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
+ TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
+ TF_MODEL_MAPPING,
+ )
+
+
+class NewModelConfig(BertConfig):
+ model_type = "new-model"
+
+
+if is_tf_available():
+
+ class TFNewModel(TFBertModel):
+ config_class = NewModelConfig
+
+
+@require_tf
+class TFAutoModelTest(unittest.TestCase):
+ @slow
+ def test_model_from_pretrained(self):
+ model_name = "google-bert/bert-base-cased"
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, BertConfig)
+
+ model = TFAutoModel.from_pretrained(model_name)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, TFBertModel)
+
+ @slow
+ def test_model_for_pretraining_from_pretrained(self):
+ model_name = "google-bert/bert-base-cased"
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, BertConfig)
+
+ model = TFAutoModelForPreTraining.from_pretrained(model_name)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, TFBertForPreTraining)
+
+ @slow
+ def test_model_for_causal_lm(self):
+ model_name = "openai-community/gpt2"
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, GPT2Config)
+
+ model = TFAutoModelForCausalLM.from_pretrained(model_name)
+ model, loading_info = TFAutoModelForCausalLM.from_pretrained(model_name, output_loading_info=True)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, TFGPT2LMHeadModel)
+
+ @slow
+ def test_lmhead_model_from_pretrained(self):
+ model_name = "openai-community/gpt2"
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, GPT2Config)
+
+ model = TFAutoModelWithLMHead.from_pretrained(model_name)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, TFGPT2LMHeadModel)
+
+ @slow
+ def test_model_for_masked_lm(self):
+ model_name = "google-bert/bert-base-uncased"
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, BertConfig)
+
+ model = TFAutoModelForMaskedLM.from_pretrained(model_name)
+ model, loading_info = TFAutoModelForMaskedLM.from_pretrained(model_name, output_loading_info=True)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, TFBertForMaskedLM)
+
+ @slow
+ def test_model_for_encoder_decoder_lm(self):
+ model_name = "google-t5/t5-base"
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, T5Config)
+
+ model = TFAutoModelForSeq2SeqLM.from_pretrained(model_name)
+ model, loading_info = TFAutoModelForSeq2SeqLM.from_pretrained(model_name, output_loading_info=True)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, TFT5ForConditionalGeneration)
+
+ @slow
+ def test_sequence_classification_model_from_pretrained(self):
+ # model_name = 'openai-community/gpt2'
+ for model_name in ["google-bert/bert-base-uncased"]:
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, BertConfig)
+
+ model = TFAutoModelForSequenceClassification.from_pretrained(model_name)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, TFBertForSequenceClassification)
+
+ @slow
+ def test_question_answering_model_from_pretrained(self):
+ # model_name = 'openai-community/gpt2'
+ for model_name in ["google-bert/bert-base-uncased"]:
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, BertConfig)
+
+ model = TFAutoModelForQuestionAnswering.from_pretrained(model_name)
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, TFBertForQuestionAnswering)
+
+ @slow
+ @require_tensorflow_probability
+ def test_table_question_answering_model_from_pretrained(self):
+ model_name = "google/tapas-base"
+ config = AutoConfig.from_pretrained(model_name)
+ self.assertIsNotNone(config)
+ self.assertIsInstance(config, TapasConfig)
+
+ model = TFAutoModelForTableQuestionAnswering.from_pretrained(model_name)
+ model, loading_info = TFAutoModelForTableQuestionAnswering.from_pretrained(
+ model_name, output_loading_info=True
+ )
+ self.assertIsNotNone(model)
+ self.assertIsInstance(model, TFTapasForQuestionAnswering)
+
+ def test_from_pretrained_identifier(self):
+ model = TFAutoModelWithLMHead.from_pretrained(SMALL_MODEL_IDENTIFIER)
+ self.assertIsInstance(model, TFBertForMaskedLM)
+ self.assertEqual(model.num_parameters(), 14410)
+ self.assertEqual(model.num_parameters(only_trainable=True), 14410)
+
+ def test_from_identifier_from_model_type(self):
+ model = TFAutoModelWithLMHead.from_pretrained(DUMMY_UNKNOWN_IDENTIFIER)
+ self.assertIsInstance(model, TFRobertaForMaskedLM)
+ self.assertEqual(model.num_parameters(), 14410)
+ self.assertEqual(model.num_parameters(only_trainable=True), 14410)
+
+ def test_from_pretrained_with_tuple_values(self):
+ # For the auto model mapping, FunnelConfig has two models: FunnelModel and FunnelBaseModel
+ model = TFAutoModel.from_pretrained("sgugger/funnel-random-tiny")
+ self.assertIsInstance(model, TFFunnelModel)
+
+ config = copy.deepcopy(model.config)
+ config.architectures = ["FunnelBaseModel"]
+ model = TFAutoModel.from_config(config)
+ model.build_in_name_scope()
+
+ self.assertIsInstance(model, TFFunnelBaseModel)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ model.save_pretrained(tmp_dir)
+ model = TFAutoModel.from_pretrained(tmp_dir)
+ self.assertIsInstance(model, TFFunnelBaseModel)
+
+ def test_new_model_registration(self):
+ try:
+ AutoConfig.register("new-model", NewModelConfig)
+
+ auto_classes = [
+ TFAutoModel,
+ TFAutoModelForCausalLM,
+ TFAutoModelForMaskedLM,
+ TFAutoModelForPreTraining,
+ TFAutoModelForQuestionAnswering,
+ TFAutoModelForSequenceClassification,
+ TFAutoModelForTokenClassification,
+ ]
+
+ for auto_class in auto_classes:
+ with self.subTest(auto_class.__name__):
+ # Wrong config class will raise an error
+ with self.assertRaises(ValueError):
+ auto_class.register(BertConfig, TFNewModel)
+ auto_class.register(NewModelConfig, TFNewModel)
+ # Trying to register something existing in the Transformers library will raise an error
+ with self.assertRaises(ValueError):
+ auto_class.register(BertConfig, TFBertModel)
+
+ # Now that the config is registered, it can be used as any other config with the auto-API
+ tiny_config = BertModelTester(self).get_config()
+ config = NewModelConfig(**tiny_config.to_dict())
+
+ model = auto_class.from_config(config)
+ model.build_in_name_scope()
+
+ self.assertIsInstance(model, TFNewModel)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ model.save_pretrained(tmp_dir)
+ new_model = auto_class.from_pretrained(tmp_dir)
+ self.assertIsInstance(new_model, TFNewModel)
+
+ finally:
+ if "new-model" in CONFIG_MAPPING._extra_content:
+ del CONFIG_MAPPING._extra_content["new-model"]
+ for mapping in (
+ TF_MODEL_MAPPING,
+ TF_MODEL_FOR_PRETRAINING_MAPPING,
+ TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
+ TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
+ TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
+ TF_MODEL_FOR_CAUSAL_LM_MAPPING,
+ TF_MODEL_FOR_MASKED_LM_MAPPING,
+ ):
+ if NewModelConfig in mapping._extra_content:
+ del mapping._extra_content[NewModelConfig]
+
+ def test_repo_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError, "bert-base is not a local folder and is not a valid model identifier"
+ ):
+ _ = TFAutoModel.from_pretrained("bert-base")
+
+ def test_revision_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError, r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"
+ ):
+ _ = TFAutoModel.from_pretrained(DUMMY_UNKNOWN_IDENTIFIER, revision="aaaaaa")
+
+ def test_model_file_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError,
+ "hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin",
+ ):
+ _ = TFAutoModel.from_pretrained("hf-internal-testing/config-no-model")
+
+ def test_model_from_pt_suggestion(self):
+ with self.assertRaisesRegex(EnvironmentError, "Use `from_pt=True` to load this model"):
+ _ = TFAutoModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only")
+
+ def test_cached_model_has_minimum_calls_to_head(self):
+ # Make sure we have cached the model.
+ _ = TFAutoModel.from_pretrained("hf-internal-testing/tiny-random-bert")
+ with RequestCounter() as counter:
+ _ = TFAutoModel.from_pretrained("hf-internal-testing/tiny-random-bert")
+ self.assertEqual(counter["GET"], 0)
+ self.assertEqual(counter["HEAD"], 1)
+ self.assertEqual(counter.total_calls, 1)
+
+ # With a sharded checkpoint
+ _ = TFAutoModel.from_pretrained("ArthurZ/tiny-random-bert-sharded")
+ with RequestCounter() as counter:
+ _ = TFAutoModel.from_pretrained("ArthurZ/tiny-random-bert-sharded")
+ self.assertEqual(counter["GET"], 0)
+ self.assertEqual(counter["HEAD"], 1)
+ self.assertEqual(counter.total_calls, 1)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_processor_auto.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_processor_auto.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd361f160f2b9c61ef357220fb95c0ed2753e194
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_processor_auto.py
@@ -0,0 +1,453 @@
+# 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.
+
+import json
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from shutil import copyfile
+
+from huggingface_hub import HfFolder, Repository
+
+import transformers
+from transformers import (
+ CONFIG_MAPPING,
+ FEATURE_EXTRACTOR_MAPPING,
+ PROCESSOR_MAPPING,
+ TOKENIZER_MAPPING,
+ AutoConfig,
+ AutoFeatureExtractor,
+ AutoProcessor,
+ AutoTokenizer,
+ BertTokenizer,
+ ProcessorMixin,
+ Wav2Vec2Config,
+ Wav2Vec2FeatureExtractor,
+ Wav2Vec2Processor,
+)
+from transformers.testing_utils import TOKEN, TemporaryHubRepo, get_tests_dir, is_staging_test
+from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE
+from transformers.utils import FEATURE_EXTRACTOR_NAME, PROCESSOR_NAME, is_tokenizers_available
+
+
+sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils"))
+
+from test_module.custom_configuration import CustomConfig # noqa E402
+from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402
+from test_module.custom_processing import CustomProcessor # noqa E402
+from test_module.custom_tokenization import CustomTokenizer # noqa E402
+
+
+SAMPLE_PROCESSOR_CONFIG = get_tests_dir("fixtures/dummy_feature_extractor_config.json")
+SAMPLE_VOCAB = get_tests_dir("fixtures/vocab.json")
+SAMPLE_PROCESSOR_CONFIG_DIR = get_tests_dir("fixtures")
+
+
+class AutoFeatureExtractorTest(unittest.TestCase):
+ vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"]
+
+ def setUp(self):
+ transformers.dynamic_module_utils.TIME_OUT_REMOTE_CODE = 0
+
+ def test_processor_from_model_shortcut(self):
+ processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h")
+ self.assertIsInstance(processor, Wav2Vec2Processor)
+
+ def test_processor_from_local_directory_from_repo(self):
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ model_config = Wav2Vec2Config()
+ processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h")
+
+ # save in new folder
+ model_config.save_pretrained(tmpdirname)
+ processor.save_pretrained(tmpdirname)
+
+ processor = AutoProcessor.from_pretrained(tmpdirname)
+
+ self.assertIsInstance(processor, Wav2Vec2Processor)
+
+ def test_processor_from_local_directory_from_extractor_config(self):
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ # copy relevant files
+ copyfile(SAMPLE_PROCESSOR_CONFIG, os.path.join(tmpdirname, FEATURE_EXTRACTOR_NAME))
+ copyfile(SAMPLE_VOCAB, os.path.join(tmpdirname, "vocab.json"))
+
+ processor = AutoProcessor.from_pretrained(tmpdirname)
+
+ self.assertIsInstance(processor, Wav2Vec2Processor)
+
+ def test_processor_from_processor_class(self):
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ feature_extractor = Wav2Vec2FeatureExtractor()
+ tokenizer = AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h")
+
+ processor = Wav2Vec2Processor(feature_extractor, tokenizer)
+
+ # save in new folder
+ processor.save_pretrained(tmpdirname)
+
+ if not os.path.isfile(os.path.join(tmpdirname, PROCESSOR_NAME)):
+ # create one manually in order to perform this test's objective
+ config_dict = {"processor_class": "Wav2Vec2Processor"}
+ with open(os.path.join(tmpdirname, PROCESSOR_NAME), "w") as fp:
+ json.dump(config_dict, fp)
+
+ # drop `processor_class` in tokenizer config
+ with open(os.path.join(tmpdirname, TOKENIZER_CONFIG_FILE), "r") as f:
+ config_dict = json.load(f)
+ config_dict.pop("processor_class")
+
+ with open(os.path.join(tmpdirname, TOKENIZER_CONFIG_FILE), "w") as f:
+ f.write(json.dumps(config_dict))
+
+ processor = AutoProcessor.from_pretrained(tmpdirname)
+
+ self.assertIsInstance(processor, Wav2Vec2Processor)
+
+ def test_processor_from_feat_extr_processor_class(self):
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ feature_extractor = Wav2Vec2FeatureExtractor()
+ tokenizer = AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h")
+
+ processor = Wav2Vec2Processor(feature_extractor, tokenizer)
+
+ # save in new folder
+ processor.save_pretrained(tmpdirname)
+
+ if os.path.isfile(os.path.join(tmpdirname, PROCESSOR_NAME)):
+ # drop `processor_class` in processor
+ with open(os.path.join(tmpdirname, PROCESSOR_NAME), "r") as f:
+ config_dict = json.load(f)
+ config_dict.pop("processor_class")
+
+ with open(os.path.join(tmpdirname, PROCESSOR_NAME), "w") as f:
+ f.write(json.dumps(config_dict))
+
+ # drop `processor_class` in tokenizer
+ with open(os.path.join(tmpdirname, TOKENIZER_CONFIG_FILE), "r") as f:
+ config_dict = json.load(f)
+ config_dict.pop("processor_class")
+
+ with open(os.path.join(tmpdirname, TOKENIZER_CONFIG_FILE), "w") as f:
+ f.write(json.dumps(config_dict))
+
+ processor = AutoProcessor.from_pretrained(tmpdirname)
+
+ self.assertIsInstance(processor, Wav2Vec2Processor)
+
+ def test_processor_from_tokenizer_processor_class(self):
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ feature_extractor = Wav2Vec2FeatureExtractor()
+ tokenizer = AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h")
+
+ processor = Wav2Vec2Processor(feature_extractor, tokenizer)
+
+ # save in new folder
+ processor.save_pretrained(tmpdirname)
+
+ if os.path.isfile(os.path.join(tmpdirname, PROCESSOR_NAME)):
+ # drop `processor_class` in processor
+ with open(os.path.join(tmpdirname, PROCESSOR_NAME), "r") as f:
+ config_dict = json.load(f)
+ config_dict.pop("processor_class")
+
+ with open(os.path.join(tmpdirname, PROCESSOR_NAME), "w") as f:
+ f.write(json.dumps(config_dict))
+
+ # drop `processor_class` in feature extractor
+ with open(os.path.join(tmpdirname, FEATURE_EXTRACTOR_NAME), "r") as f:
+ config_dict = json.load(f)
+ config_dict.pop("processor_class")
+
+ with open(os.path.join(tmpdirname, FEATURE_EXTRACTOR_NAME), "w") as f:
+ f.write(json.dumps(config_dict))
+
+ processor = AutoProcessor.from_pretrained(tmpdirname)
+
+ self.assertIsInstance(processor, Wav2Vec2Processor)
+
+ def test_processor_from_local_directory_from_model_config(self):
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ model_config = Wav2Vec2Config(processor_class="Wav2Vec2Processor")
+ model_config.save_pretrained(tmpdirname)
+ # copy relevant files
+ copyfile(SAMPLE_VOCAB, os.path.join(tmpdirname, "vocab.json"))
+ # create emtpy sample processor
+ with open(os.path.join(tmpdirname, FEATURE_EXTRACTOR_NAME), "w") as f:
+ f.write("{}")
+
+ processor = AutoProcessor.from_pretrained(tmpdirname)
+
+ self.assertIsInstance(processor, Wav2Vec2Processor)
+
+ def test_from_pretrained_dynamic_processor(self):
+ # If remote code is not set, we will time out when asking whether to load the model.
+ with self.assertRaises(ValueError):
+ processor = AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor")
+ # If remote code is disabled, we can't load this config.
+ with self.assertRaises(ValueError):
+ processor = AutoProcessor.from_pretrained(
+ "hf-internal-testing/test_dynamic_processor", trust_remote_code=False
+ )
+
+ processor = AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor", trust_remote_code=True)
+ self.assertTrue(processor.special_attribute_present)
+ self.assertEqual(processor.__class__.__name__, "NewProcessor")
+
+ feature_extractor = processor.feature_extractor
+ self.assertTrue(feature_extractor.special_attribute_present)
+ self.assertEqual(feature_extractor.__class__.__name__, "NewFeatureExtractor")
+
+ tokenizer = processor.tokenizer
+ self.assertTrue(tokenizer.special_attribute_present)
+ if is_tokenizers_available():
+ self.assertEqual(tokenizer.__class__.__name__, "NewTokenizerFast")
+
+ # Test we can also load the slow version
+ new_processor = AutoProcessor.from_pretrained(
+ "hf-internal-testing/test_dynamic_processor", trust_remote_code=True, use_fast=False
+ )
+ new_tokenizer = new_processor.tokenizer
+ self.assertTrue(new_tokenizer.special_attribute_present)
+ self.assertEqual(new_tokenizer.__class__.__name__, "NewTokenizer")
+ else:
+ self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer")
+
+ def test_new_processor_registration(self):
+ try:
+ AutoConfig.register("custom", CustomConfig)
+ AutoFeatureExtractor.register(CustomConfig, CustomFeatureExtractor)
+ AutoTokenizer.register(CustomConfig, slow_tokenizer_class=CustomTokenizer)
+ AutoProcessor.register(CustomConfig, CustomProcessor)
+ # Trying to register something existing in the Transformers library will raise an error
+ with self.assertRaises(ValueError):
+ AutoProcessor.register(Wav2Vec2Config, Wav2Vec2Processor)
+
+ # Now that the config is registered, it can be used as any other config with the auto-API
+ feature_extractor = CustomFeatureExtractor.from_pretrained(SAMPLE_PROCESSOR_CONFIG_DIR)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ vocab_file = os.path.join(tmp_dir, "vocab.txt")
+ with open(vocab_file, "w", encoding="utf-8") as vocab_writer:
+ vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]))
+ tokenizer = CustomTokenizer(vocab_file)
+
+ processor = CustomProcessor(feature_extractor, tokenizer)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ processor.save_pretrained(tmp_dir)
+ new_processor = AutoProcessor.from_pretrained(tmp_dir)
+ self.assertIsInstance(new_processor, CustomProcessor)
+
+ finally:
+ if "custom" in CONFIG_MAPPING._extra_content:
+ del CONFIG_MAPPING._extra_content["custom"]
+ if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
+ del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
+ if CustomConfig in TOKENIZER_MAPPING._extra_content:
+ del TOKENIZER_MAPPING._extra_content[CustomConfig]
+ if CustomConfig in PROCESSOR_MAPPING._extra_content:
+ del PROCESSOR_MAPPING._extra_content[CustomConfig]
+
+ def test_from_pretrained_dynamic_processor_conflict(self):
+ class NewFeatureExtractor(Wav2Vec2FeatureExtractor):
+ special_attribute_present = False
+
+ class NewTokenizer(BertTokenizer):
+ special_attribute_present = False
+
+ class NewProcessor(ProcessorMixin):
+ feature_extractor_class = "AutoFeatureExtractor"
+ tokenizer_class = "AutoTokenizer"
+ special_attribute_present = False
+
+ try:
+ AutoConfig.register("custom", CustomConfig)
+ AutoFeatureExtractor.register(CustomConfig, NewFeatureExtractor)
+ AutoTokenizer.register(CustomConfig, slow_tokenizer_class=NewTokenizer)
+ AutoProcessor.register(CustomConfig, NewProcessor)
+ # If remote code is not set, the default is to use local classes.
+ processor = AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor")
+ self.assertEqual(processor.__class__.__name__, "NewProcessor")
+ self.assertFalse(processor.special_attribute_present)
+ self.assertFalse(processor.feature_extractor.special_attribute_present)
+ self.assertFalse(processor.tokenizer.special_attribute_present)
+
+ # If remote code is disabled, we load the local ones.
+ processor = AutoProcessor.from_pretrained(
+ "hf-internal-testing/test_dynamic_processor", trust_remote_code=False
+ )
+ self.assertEqual(processor.__class__.__name__, "NewProcessor")
+ self.assertFalse(processor.special_attribute_present)
+ self.assertFalse(processor.feature_extractor.special_attribute_present)
+ self.assertFalse(processor.tokenizer.special_attribute_present)
+
+ # If remote is enabled, we load from the Hub.
+ processor = AutoProcessor.from_pretrained(
+ "hf-internal-testing/test_dynamic_processor", trust_remote_code=True
+ )
+ self.assertEqual(processor.__class__.__name__, "NewProcessor")
+ self.assertTrue(processor.special_attribute_present)
+ self.assertTrue(processor.feature_extractor.special_attribute_present)
+ self.assertTrue(processor.tokenizer.special_attribute_present)
+
+ finally:
+ if "custom" in CONFIG_MAPPING._extra_content:
+ del CONFIG_MAPPING._extra_content["custom"]
+ if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
+ del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
+ if CustomConfig in TOKENIZER_MAPPING._extra_content:
+ del TOKENIZER_MAPPING._extra_content[CustomConfig]
+ if CustomConfig in PROCESSOR_MAPPING._extra_content:
+ del PROCESSOR_MAPPING._extra_content[CustomConfig]
+
+ def test_from_pretrained_dynamic_processor_with_extra_attributes(self):
+ class NewFeatureExtractor(Wav2Vec2FeatureExtractor):
+ pass
+
+ class NewTokenizer(BertTokenizer):
+ pass
+
+ class NewProcessor(ProcessorMixin):
+ feature_extractor_class = "AutoFeatureExtractor"
+ tokenizer_class = "AutoTokenizer"
+
+ def __init__(self, feature_extractor, tokenizer, processor_attr_1=1, processor_attr_2=True):
+ super().__init__(feature_extractor, tokenizer)
+
+ self.processor_attr_1 = processor_attr_1
+ self.processor_attr_2 = processor_attr_2
+
+ try:
+ AutoConfig.register("custom", CustomConfig)
+ AutoFeatureExtractor.register(CustomConfig, NewFeatureExtractor)
+ AutoTokenizer.register(CustomConfig, slow_tokenizer_class=NewTokenizer)
+ AutoProcessor.register(CustomConfig, NewProcessor)
+ # If remote code is not set, the default is to use local classes.
+ processor = AutoProcessor.from_pretrained(
+ "hf-internal-testing/test_dynamic_processor", processor_attr_2=False
+ )
+ self.assertEqual(processor.__class__.__name__, "NewProcessor")
+ self.assertEqual(processor.processor_attr_1, 1)
+ self.assertEqual(processor.processor_attr_2, False)
+ finally:
+ if "custom" in CONFIG_MAPPING._extra_content:
+ del CONFIG_MAPPING._extra_content["custom"]
+ if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
+ del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
+ if CustomConfig in TOKENIZER_MAPPING._extra_content:
+ del TOKENIZER_MAPPING._extra_content[CustomConfig]
+ if CustomConfig in PROCESSOR_MAPPING._extra_content:
+ del PROCESSOR_MAPPING._extra_content[CustomConfig]
+
+ def test_auto_processor_creates_tokenizer(self):
+ processor = AutoProcessor.from_pretrained("hf-internal-testing/tiny-random-bert")
+ self.assertEqual(processor.__class__.__name__, "BertTokenizerFast")
+
+ def test_auto_processor_creates_image_processor(self):
+ processor = AutoProcessor.from_pretrained("hf-internal-testing/tiny-random-convnext")
+ self.assertEqual(processor.__class__.__name__, "ConvNextImageProcessor")
+
+
+@is_staging_test
+class ProcessorPushToHubTester(unittest.TestCase):
+ vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"]
+
+ @classmethod
+ def setUpClass(cls):
+ cls._token = TOKEN
+ HfFolder.save_token(TOKEN)
+
+ def test_push_to_hub_via_save_pretrained(self):
+ with TemporaryHubRepo(token=self._token) as tmp_repo:
+ processor = Wav2Vec2Processor.from_pretrained(SAMPLE_PROCESSOR_CONFIG_DIR)
+ # Push to hub via save_pretrained
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ processor.save_pretrained(tmp_dir, repo_id=tmp_repo.repo_id, push_to_hub=True, token=self._token)
+
+ new_processor = Wav2Vec2Processor.from_pretrained(tmp_repo.repo_id)
+ for k, v in processor.feature_extractor.__dict__.items():
+ self.assertEqual(v, getattr(new_processor.feature_extractor, k))
+ self.assertDictEqual(new_processor.tokenizer.get_vocab(), processor.tokenizer.get_vocab())
+
+ def test_push_to_hub_in_organization_via_save_pretrained(self):
+ with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo:
+ processor = Wav2Vec2Processor.from_pretrained(SAMPLE_PROCESSOR_CONFIG_DIR)
+ # Push to hub via save_pretrained
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ processor.save_pretrained(
+ tmp_dir,
+ repo_id=tmp_repo.repo_id,
+ push_to_hub=True,
+ token=self._token,
+ )
+
+ new_processor = Wav2Vec2Processor.from_pretrained(tmp_repo.repo_id)
+ for k, v in processor.feature_extractor.__dict__.items():
+ self.assertEqual(v, getattr(new_processor.feature_extractor, k))
+ self.assertDictEqual(new_processor.tokenizer.get_vocab(), processor.tokenizer.get_vocab())
+
+ def test_push_to_hub_dynamic_processor(self):
+ with TemporaryHubRepo(token=self._token) as tmp_repo:
+ CustomFeatureExtractor.register_for_auto_class()
+ CustomTokenizer.register_for_auto_class()
+ CustomProcessor.register_for_auto_class()
+
+ feature_extractor = CustomFeatureExtractor.from_pretrained(SAMPLE_PROCESSOR_CONFIG_DIR)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ vocab_file = os.path.join(tmp_dir, "vocab.txt")
+ with open(vocab_file, "w", encoding="utf-8") as vocab_writer:
+ vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]))
+ tokenizer = CustomTokenizer(vocab_file)
+
+ processor = CustomProcessor(feature_extractor, tokenizer)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ repo = Repository(tmp_dir, clone_from=tmp_repo, token=self._token)
+ processor.save_pretrained(tmp_dir)
+
+ # This has added the proper auto_map field to the feature extractor config
+ self.assertDictEqual(
+ processor.feature_extractor.auto_map,
+ {
+ "AutoFeatureExtractor": "custom_feature_extraction.CustomFeatureExtractor",
+ "AutoProcessor": "custom_processing.CustomProcessor",
+ },
+ )
+
+ # This has added the proper auto_map field to the tokenizer config
+ with open(os.path.join(tmp_dir, "tokenizer_config.json")) as f:
+ tokenizer_config = json.load(f)
+ self.assertDictEqual(
+ tokenizer_config["auto_map"],
+ {
+ "AutoTokenizer": ["custom_tokenization.CustomTokenizer", None],
+ "AutoProcessor": "custom_processing.CustomProcessor",
+ },
+ )
+
+ # The code has been copied from fixtures
+ self.assertTrue(os.path.isfile(os.path.join(tmp_dir, "custom_feature_extraction.py")))
+ self.assertTrue(os.path.isfile(os.path.join(tmp_dir, "custom_tokenization.py")))
+ self.assertTrue(os.path.isfile(os.path.join(tmp_dir, "custom_processing.py")))
+
+ repo.push_to_hub()
+
+ new_processor = AutoProcessor.from_pretrained(tmp_repo.repo_id, trust_remote_code=True)
+ # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module
+ self.assertEqual(new_processor.__class__.__name__, "CustomProcessor")
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_tokenization_auto.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_tokenization_auto.py
new file mode 100644
index 0000000000000000000000000000000000000000..f49ece15fface24a1748470ddb185751cd22f573
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/auto/test_tokenization_auto.py
@@ -0,0 +1,519 @@
+# coding=utf-8
+# 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 json
+import os
+import shutil
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+import pytest
+
+import transformers
+from transformers import (
+ AutoTokenizer,
+ BertConfig,
+ BertTokenizer,
+ BertTokenizerFast,
+ CTRLTokenizer,
+ GPT2Tokenizer,
+ GPT2TokenizerFast,
+ PreTrainedTokenizerFast,
+ RobertaTokenizer,
+ RobertaTokenizerFast,
+ is_tokenizers_available,
+)
+from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
+from transformers.models.auto.tokenization_auto import (
+ TOKENIZER_MAPPING,
+ get_tokenizer_config,
+ tokenizer_class_from_name,
+)
+from transformers.models.roberta.configuration_roberta import RobertaConfig
+from transformers.testing_utils import (
+ DUMMY_DIFF_TOKENIZER_IDENTIFIER,
+ DUMMY_UNKNOWN_IDENTIFIER,
+ SMALL_MODEL_IDENTIFIER,
+ RequestCounter,
+ require_tokenizers,
+ slow,
+)
+
+
+sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils"))
+
+from test_module.custom_configuration import CustomConfig # noqa E402
+from test_module.custom_tokenization import CustomTokenizer # noqa E402
+
+
+if is_tokenizers_available():
+ from test_module.custom_tokenization_fast import CustomTokenizerFast
+
+
+class AutoTokenizerTest(unittest.TestCase):
+ def setUp(self):
+ transformers.dynamic_module_utils.TIME_OUT_REMOTE_CODE = 0
+
+ @slow
+ def test_tokenizer_from_pretrained(self):
+ for model_name in {"google-bert/bert-base-uncased", "google-bert/bert-base-cased"}:
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
+ self.assertIsNotNone(tokenizer)
+ self.assertIsInstance(tokenizer, (BertTokenizer, BertTokenizerFast))
+ self.assertGreater(len(tokenizer), 0)
+
+ for model_name in ["openai-community/gpt2", "openai-community/gpt2-medium"]:
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
+ self.assertIsNotNone(tokenizer)
+ self.assertIsInstance(tokenizer, (GPT2Tokenizer, GPT2TokenizerFast))
+ self.assertGreater(len(tokenizer), 0)
+
+ def test_tokenizer_from_pretrained_identifier(self):
+ tokenizer = AutoTokenizer.from_pretrained(SMALL_MODEL_IDENTIFIER)
+ self.assertIsInstance(tokenizer, (BertTokenizer, BertTokenizerFast))
+ self.assertEqual(tokenizer.vocab_size, 12)
+
+ def test_tokenizer_from_model_type(self):
+ tokenizer = AutoTokenizer.from_pretrained(DUMMY_UNKNOWN_IDENTIFIER)
+ self.assertIsInstance(tokenizer, (RobertaTokenizer, RobertaTokenizerFast))
+ self.assertEqual(tokenizer.vocab_size, 20)
+
+ def test_tokenizer_from_tokenizer_class(self):
+ config = AutoConfig.from_pretrained(DUMMY_DIFF_TOKENIZER_IDENTIFIER)
+ self.assertIsInstance(config, RobertaConfig)
+ # Check that tokenizer_type ≠ model_type
+ tokenizer = AutoTokenizer.from_pretrained(DUMMY_DIFF_TOKENIZER_IDENTIFIER, config=config)
+ self.assertIsInstance(tokenizer, (BertTokenizer, BertTokenizerFast))
+ self.assertEqual(tokenizer.vocab_size, 12)
+
+ def test_tokenizer_from_type(self):
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ shutil.copy("./tests/fixtures/vocab.txt", os.path.join(tmp_dir, "vocab.txt"))
+
+ tokenizer = AutoTokenizer.from_pretrained(tmp_dir, tokenizer_type="bert", use_fast=False)
+ self.assertIsInstance(tokenizer, BertTokenizer)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ shutil.copy("./tests/fixtures/vocab.json", os.path.join(tmp_dir, "vocab.json"))
+ shutil.copy("./tests/fixtures/merges.txt", os.path.join(tmp_dir, "merges.txt"))
+
+ tokenizer = AutoTokenizer.from_pretrained(tmp_dir, tokenizer_type="gpt2", use_fast=False)
+ self.assertIsInstance(tokenizer, GPT2Tokenizer)
+
+ @require_tokenizers
+ def test_tokenizer_from_type_fast(self):
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ shutil.copy("./tests/fixtures/vocab.txt", os.path.join(tmp_dir, "vocab.txt"))
+
+ tokenizer = AutoTokenizer.from_pretrained(tmp_dir, tokenizer_type="bert")
+ self.assertIsInstance(tokenizer, BertTokenizerFast)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ shutil.copy("./tests/fixtures/vocab.json", os.path.join(tmp_dir, "vocab.json"))
+ shutil.copy("./tests/fixtures/merges.txt", os.path.join(tmp_dir, "merges.txt"))
+
+ tokenizer = AutoTokenizer.from_pretrained(tmp_dir, tokenizer_type="gpt2")
+ self.assertIsInstance(tokenizer, GPT2TokenizerFast)
+
+ def test_tokenizer_from_type_incorrect_name(self):
+ with pytest.raises(ValueError):
+ AutoTokenizer.from_pretrained("./", tokenizer_type="xxx")
+
+ @require_tokenizers
+ def test_tokenizer_identifier_with_correct_config(self):
+ for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]:
+ tokenizer = tokenizer_class.from_pretrained("wietsedv/bert-base-dutch-cased")
+ self.assertIsInstance(tokenizer, (BertTokenizer, BertTokenizerFast))
+
+ if isinstance(tokenizer, BertTokenizer):
+ self.assertEqual(tokenizer.basic_tokenizer.do_lower_case, False)
+ else:
+ self.assertEqual(tokenizer.do_lower_case, False)
+
+ self.assertEqual(tokenizer.model_max_length, 512)
+
+ @require_tokenizers
+ def test_tokenizer_identifier_non_existent(self):
+ for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]:
+ with self.assertRaisesRegex(
+ EnvironmentError,
+ "julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier",
+ ):
+ _ = tokenizer_class.from_pretrained("julien-c/herlolip-not-exists")
+
+ def test_model_name_edge_cases_in_mappings(self):
+ # tests: https://github.com/huggingface/transformers/pull/13251
+ # 1. models with `-`, e.g. xlm-roberta -> xlm_roberta
+ # 2. models that don't remap 1-1 from model-name to model file, e.g., openai-gpt -> openai
+ tokenizers = TOKENIZER_MAPPING.values()
+ tokenizer_names = []
+
+ for slow_tok, fast_tok in tokenizers:
+ if slow_tok is not None:
+ tokenizer_names.append(slow_tok.__name__)
+
+ if fast_tok is not None:
+ tokenizer_names.append(fast_tok.__name__)
+
+ for tokenizer_name in tokenizer_names:
+ # must find the right class
+ tokenizer_class_from_name(tokenizer_name)
+
+ @require_tokenizers
+ def test_from_pretrained_use_fast_toggle(self):
+ self.assertIsInstance(
+ AutoTokenizer.from_pretrained("google-bert/bert-base-cased", use_fast=False), BertTokenizer
+ )
+ self.assertIsInstance(AutoTokenizer.from_pretrained("google-bert/bert-base-cased"), BertTokenizerFast)
+
+ @require_tokenizers
+ def test_do_lower_case(self):
+ tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased", do_lower_case=False)
+ sample = "Hello, world. How are you?"
+ tokens = tokenizer.tokenize(sample)
+ self.assertEqual("[UNK]", tokens[0])
+
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/mpnet-base", do_lower_case=False)
+ tokens = tokenizer.tokenize(sample)
+ self.assertEqual("[UNK]", tokens[0])
+
+ @require_tokenizers
+ def test_PreTrainedTokenizerFast_from_pretrained(self):
+ tokenizer = AutoTokenizer.from_pretrained("robot-test/dummy-tokenizer-fast-with-model-config")
+ self.assertEqual(type(tokenizer), PreTrainedTokenizerFast)
+ self.assertEqual(tokenizer.model_max_length, 512)
+ self.assertEqual(tokenizer.vocab_size, 30000)
+ self.assertEqual(tokenizer.unk_token, "[UNK]")
+ self.assertEqual(tokenizer.padding_side, "right")
+ self.assertEqual(tokenizer.truncation_side, "right")
+
+ def test_auto_tokenizer_from_local_folder(self):
+ tokenizer = AutoTokenizer.from_pretrained(SMALL_MODEL_IDENTIFIER)
+ self.assertIsInstance(tokenizer, (BertTokenizer, BertTokenizerFast))
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ tokenizer.save_pretrained(tmp_dir)
+ tokenizer2 = AutoTokenizer.from_pretrained(tmp_dir)
+
+ self.assertIsInstance(tokenizer2, tokenizer.__class__)
+ self.assertEqual(tokenizer2.vocab_size, 12)
+
+ def test_auto_tokenizer_fast_no_slow(self):
+ tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
+ # There is no fast CTRL so this always gives us a slow tokenizer.
+ self.assertIsInstance(tokenizer, CTRLTokenizer)
+
+ def test_get_tokenizer_config(self):
+ # Check we can load the tokenizer config of an online model.
+ config = get_tokenizer_config("google-bert/bert-base-cased")
+ _ = config.pop("_commit_hash", None)
+ # If we ever update google-bert/bert-base-cased tokenizer config, this dict here will need to be updated.
+ self.assertEqual(config, {"do_lower_case": False, "model_max_length": 512})
+
+ # This model does not have a tokenizer_config so we get back an empty dict.
+ config = get_tokenizer_config(SMALL_MODEL_IDENTIFIER)
+ self.assertDictEqual(config, {})
+
+ # A tokenizer saved with `save_pretrained` always creates a tokenizer config.
+ tokenizer = AutoTokenizer.from_pretrained(SMALL_MODEL_IDENTIFIER)
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ tokenizer.save_pretrained(tmp_dir)
+ config = get_tokenizer_config(tmp_dir)
+
+ # Check the class of the tokenizer was properly saved (note that it always saves the slow class).
+ self.assertEqual(config["tokenizer_class"], "BertTokenizer")
+
+ def test_new_tokenizer_registration(self):
+ try:
+ AutoConfig.register("custom", CustomConfig)
+
+ AutoTokenizer.register(CustomConfig, slow_tokenizer_class=CustomTokenizer)
+ # Trying to register something existing in the Transformers library will raise an error
+ with self.assertRaises(ValueError):
+ AutoTokenizer.register(BertConfig, slow_tokenizer_class=BertTokenizer)
+
+ tokenizer = CustomTokenizer.from_pretrained(SMALL_MODEL_IDENTIFIER)
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ tokenizer.save_pretrained(tmp_dir)
+
+ new_tokenizer = AutoTokenizer.from_pretrained(tmp_dir)
+ self.assertIsInstance(new_tokenizer, CustomTokenizer)
+
+ finally:
+ if "custom" in CONFIG_MAPPING._extra_content:
+ del CONFIG_MAPPING._extra_content["custom"]
+ if CustomConfig in TOKENIZER_MAPPING._extra_content:
+ del TOKENIZER_MAPPING._extra_content[CustomConfig]
+
+ @require_tokenizers
+ def test_new_tokenizer_fast_registration(self):
+ try:
+ AutoConfig.register("custom", CustomConfig)
+
+ # Can register in two steps
+ AutoTokenizer.register(CustomConfig, slow_tokenizer_class=CustomTokenizer)
+ self.assertEqual(TOKENIZER_MAPPING[CustomConfig], (CustomTokenizer, None))
+ AutoTokenizer.register(CustomConfig, fast_tokenizer_class=CustomTokenizerFast)
+ self.assertEqual(TOKENIZER_MAPPING[CustomConfig], (CustomTokenizer, CustomTokenizerFast))
+
+ del TOKENIZER_MAPPING._extra_content[CustomConfig]
+ # Can register in one step
+ AutoTokenizer.register(
+ CustomConfig, slow_tokenizer_class=CustomTokenizer, fast_tokenizer_class=CustomTokenizerFast
+ )
+ self.assertEqual(TOKENIZER_MAPPING[CustomConfig], (CustomTokenizer, CustomTokenizerFast))
+
+ # Trying to register something existing in the Transformers library will raise an error
+ with self.assertRaises(ValueError):
+ AutoTokenizer.register(BertConfig, fast_tokenizer_class=BertTokenizerFast)
+
+ # We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer
+ # and that model does not have a tokenizer.json
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ bert_tokenizer = BertTokenizerFast.from_pretrained(SMALL_MODEL_IDENTIFIER)
+ bert_tokenizer.save_pretrained(tmp_dir)
+ tokenizer = CustomTokenizerFast.from_pretrained(tmp_dir)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ tokenizer.save_pretrained(tmp_dir)
+
+ new_tokenizer = AutoTokenizer.from_pretrained(tmp_dir)
+ self.assertIsInstance(new_tokenizer, CustomTokenizerFast)
+
+ new_tokenizer = AutoTokenizer.from_pretrained(tmp_dir, use_fast=False)
+ self.assertIsInstance(new_tokenizer, CustomTokenizer)
+
+ finally:
+ if "custom" in CONFIG_MAPPING._extra_content:
+ del CONFIG_MAPPING._extra_content["custom"]
+ if CustomConfig in TOKENIZER_MAPPING._extra_content:
+ del TOKENIZER_MAPPING._extra_content[CustomConfig]
+
+ def test_from_pretrained_dynamic_tokenizer(self):
+ # If remote code is not set, we will time out when asking whether to load the model.
+ with self.assertRaises(ValueError):
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/test_dynamic_tokenizer")
+ # If remote code is disabled, we can't load this config.
+ with self.assertRaises(ValueError):
+ tokenizer = AutoTokenizer.from_pretrained(
+ "hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=False
+ )
+
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=True)
+ self.assertTrue(tokenizer.special_attribute_present)
+
+ # Test the dynamic module is loaded only once.
+ reloaded_tokenizer = AutoTokenizer.from_pretrained(
+ "hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=True
+ )
+ self.assertIs(tokenizer.__class__, reloaded_tokenizer.__class__)
+
+ # Test tokenizer can be reloaded.
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ tokenizer.save_pretrained(tmp_dir)
+ reloaded_tokenizer = AutoTokenizer.from_pretrained(tmp_dir, trust_remote_code=True)
+ self.assertTrue(reloaded_tokenizer.special_attribute_present)
+
+ if is_tokenizers_available():
+ self.assertEqual(tokenizer.__class__.__name__, "NewTokenizerFast")
+ self.assertEqual(reloaded_tokenizer.__class__.__name__, "NewTokenizerFast")
+
+ # Test we can also load the slow version
+ tokenizer = AutoTokenizer.from_pretrained(
+ "hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=True, use_fast=False
+ )
+ self.assertTrue(tokenizer.special_attribute_present)
+ self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer")
+ # Test tokenizer can be reloaded.
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ tokenizer.save_pretrained(tmp_dir)
+ reloaded_tokenizer = AutoTokenizer.from_pretrained(tmp_dir, trust_remote_code=True, use_fast=False)
+ self.assertEqual(reloaded_tokenizer.__class__.__name__, "NewTokenizer")
+ self.assertTrue(reloaded_tokenizer.special_attribute_present)
+ else:
+ self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer")
+ self.assertEqual(reloaded_tokenizer.__class__.__name__, "NewTokenizer")
+
+ # The tokenizer file is cached in the snapshot directory. So the module file is not changed after dumping
+ # to a temp dir. Because the revision of the module file is not changed.
+ # Test the dynamic module is loaded only once if the module file is not changed.
+ self.assertIs(tokenizer.__class__, reloaded_tokenizer.__class__)
+
+ # Test the dynamic module is reloaded if we force it.
+ reloaded_tokenizer = AutoTokenizer.from_pretrained(
+ "hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=True, force_download=True
+ )
+ self.assertIsNot(tokenizer.__class__, reloaded_tokenizer.__class__)
+ self.assertTrue(reloaded_tokenizer.special_attribute_present)
+
+ @require_tokenizers
+ def test_from_pretrained_dynamic_tokenizer_conflict(self):
+ class NewTokenizer(BertTokenizer):
+ special_attribute_present = False
+
+ class NewTokenizerFast(BertTokenizerFast):
+ slow_tokenizer_class = NewTokenizer
+ special_attribute_present = False
+
+ try:
+ AutoConfig.register("custom", CustomConfig)
+ AutoTokenizer.register(CustomConfig, slow_tokenizer_class=NewTokenizer)
+ AutoTokenizer.register(CustomConfig, fast_tokenizer_class=NewTokenizerFast)
+ # If remote code is not set, the default is to use local
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/test_dynamic_tokenizer")
+ self.assertEqual(tokenizer.__class__.__name__, "NewTokenizerFast")
+ self.assertFalse(tokenizer.special_attribute_present)
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/test_dynamic_tokenizer", use_fast=False)
+ self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer")
+ self.assertFalse(tokenizer.special_attribute_present)
+
+ # If remote code is disabled, we load the local one.
+ tokenizer = AutoTokenizer.from_pretrained(
+ "hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=False
+ )
+ self.assertEqual(tokenizer.__class__.__name__, "NewTokenizerFast")
+ self.assertFalse(tokenizer.special_attribute_present)
+ tokenizer = AutoTokenizer.from_pretrained(
+ "hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=False, use_fast=False
+ )
+ self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer")
+ self.assertFalse(tokenizer.special_attribute_present)
+
+ # If remote is enabled, we load from the Hub
+ tokenizer = AutoTokenizer.from_pretrained(
+ "hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=True
+ )
+ self.assertEqual(tokenizer.__class__.__name__, "NewTokenizerFast")
+ self.assertTrue(tokenizer.special_attribute_present)
+ tokenizer = AutoTokenizer.from_pretrained(
+ "hf-internal-testing/test_dynamic_tokenizer", trust_remote_code=True, use_fast=False
+ )
+ self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer")
+ self.assertTrue(tokenizer.special_attribute_present)
+
+ finally:
+ if "custom" in CONFIG_MAPPING._extra_content:
+ del CONFIG_MAPPING._extra_content["custom"]
+ if CustomConfig in TOKENIZER_MAPPING._extra_content:
+ del TOKENIZER_MAPPING._extra_content[CustomConfig]
+
+ def test_from_pretrained_dynamic_tokenizer_legacy_format(self):
+ tokenizer = AutoTokenizer.from_pretrained(
+ "hf-internal-testing/test_dynamic_tokenizer_legacy", trust_remote_code=True
+ )
+ self.assertTrue(tokenizer.special_attribute_present)
+ if is_tokenizers_available():
+ self.assertEqual(tokenizer.__class__.__name__, "NewTokenizerFast")
+
+ # Test we can also load the slow version
+ tokenizer = AutoTokenizer.from_pretrained(
+ "hf-internal-testing/test_dynamic_tokenizer_legacy", trust_remote_code=True, use_fast=False
+ )
+ self.assertTrue(tokenizer.special_attribute_present)
+ self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer")
+ else:
+ self.assertEqual(tokenizer.__class__.__name__, "NewTokenizer")
+
+ def test_repo_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError, "bert-base is not a local folder and is not a valid model identifier"
+ ):
+ _ = AutoTokenizer.from_pretrained("bert-base")
+
+ def test_revision_not_found(self):
+ with self.assertRaisesRegex(
+ EnvironmentError, r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"
+ ):
+ _ = AutoTokenizer.from_pretrained(DUMMY_UNKNOWN_IDENTIFIER, revision="aaaaaa")
+
+ def test_cached_tokenizer_has_minimum_calls_to_head(self):
+ # Make sure we have cached the tokenizer.
+ _ = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert")
+ with RequestCounter() as counter:
+ _ = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert")
+ self.assertEqual(counter["GET"], 0)
+ self.assertEqual(counter["HEAD"], 1)
+ self.assertEqual(counter.total_calls, 1)
+
+ def test_init_tokenizer_with_trust(self):
+ nop_tokenizer_code = """
+import transformers
+
+class NopTokenizer(transformers.PreTrainedTokenizer):
+ def get_vocab(self):
+ return {}
+"""
+
+ nop_config_code = """
+from transformers import PretrainedConfig
+
+class NopConfig(PretrainedConfig):
+ model_type = "test_unregistered_dynamic"
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+"""
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ fake_model_id = "hf-internal-testing/test_unregistered_dynamic"
+ fake_repo = os.path.join(tmp_dir, fake_model_id)
+ os.makedirs(fake_repo)
+
+ tokenizer_src_file = os.path.join(fake_repo, "tokenizer.py")
+ with open(tokenizer_src_file, "w") as wfp:
+ wfp.write(nop_tokenizer_code)
+
+ model_config_src_file = os.path.join(fake_repo, "config.py")
+ with open(model_config_src_file, "w") as wfp:
+ wfp.write(nop_config_code)
+
+ config = {
+ "model_type": "test_unregistered_dynamic",
+ "auto_map": {"AutoConfig": f"{fake_model_id}--config.NopConfig"},
+ }
+
+ config_file = os.path.join(fake_repo, "config.json")
+ with open(config_file, "w") as wfp:
+ json.dump(config, wfp, indent=2)
+
+ tokenizer_config = {
+ "auto_map": {
+ "AutoTokenizer": [
+ f"{fake_model_id}--tokenizer.NopTokenizer",
+ None,
+ ]
+ }
+ }
+
+ tokenizer_config_file = os.path.join(fake_repo, "tokenizer_config.json")
+ with open(tokenizer_config_file, "w") as wfp:
+ json.dump(tokenizer_config, wfp, indent=2)
+
+ prev_dir = os.getcwd()
+ try:
+ # it looks like subdir= is broken in the from_pretrained also, so this is necessary
+ os.chdir(tmp_dir)
+
+ # this should work because we trust the code
+ _ = AutoTokenizer.from_pretrained(fake_model_id, local_files_only=True, trust_remote_code=True)
+ try:
+ # this should fail because we don't trust and we're not at a terminal for interactive response
+ _ = AutoTokenizer.from_pretrained(fake_model_id, local_files_only=True, trust_remote_code=False)
+ self.fail("AutoTokenizer.from_pretrained with trust_remote_code=False should raise ValueException")
+ except ValueError:
+ pass
+ finally:
+ os.chdir(prev_dir)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/autoformer/__init__.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/autoformer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/autoformer/test_modeling_autoformer.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/autoformer/test_modeling_autoformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..92aa1ad4c9d62b9e35068094b38dd190f8dbe97f
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/autoformer/test_modeling_autoformer.py
@@ -0,0 +1,483 @@
+# coding=utf-8
+# Copyright 2023 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.
+"""Testing suite for the PyTorch Autoformer model."""
+
+import inspect
+import tempfile
+import unittest
+
+from huggingface_hub import hf_hub_download
+
+from transformers import is_torch_available
+from transformers.testing_utils import is_flaky, require_torch, slow, torch_device
+
+from ...test_configuration_common import ConfigTester
+from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
+from ...test_pipeline_mixin import PipelineTesterMixin
+
+
+TOLERANCE = 1e-4
+
+if is_torch_available():
+ import torch
+
+ from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel
+ from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder
+
+
+@require_torch
+class AutoformerModelTester:
+ def __init__(
+ self,
+ parent,
+ d_model=16,
+ batch_size=13,
+ prediction_length=7,
+ context_length=14,
+ label_length=10,
+ cardinality=19,
+ embedding_dimension=5,
+ num_time_features=4,
+ is_training=True,
+ hidden_size=16,
+ num_hidden_layers=2,
+ num_attention_heads=4,
+ intermediate_size=4,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.1,
+ attention_probs_dropout_prob=0.1,
+ lags_sequence=[1, 2, 3, 4, 5],
+ moving_average=25,
+ autocorrelation_factor=5,
+ ):
+ self.d_model = d_model
+ self.parent = parent
+ self.batch_size = batch_size
+ self.prediction_length = prediction_length
+ self.context_length = context_length
+ self.cardinality = cardinality
+ self.num_time_features = num_time_features
+ self.lags_sequence = lags_sequence
+ self.embedding_dimension = embedding_dimension
+ self.is_training = is_training
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.intermediate_size = intermediate_size
+ self.hidden_act = hidden_act
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+
+ self.encoder_seq_length = context_length
+ self.decoder_seq_length = prediction_length + label_length
+ self.label_length = label_length
+
+ self.moving_average = moving_average
+ self.autocorrelation_factor = autocorrelation_factor
+
+ def get_config(self):
+ return AutoformerConfig(
+ d_model=self.d_model,
+ encoder_layers=self.num_hidden_layers,
+ decoder_layers=self.num_hidden_layers,
+ encoder_attention_heads=self.num_attention_heads,
+ decoder_attention_heads=self.num_attention_heads,
+ encoder_ffn_dim=self.intermediate_size,
+ decoder_ffn_dim=self.intermediate_size,
+ dropout=self.hidden_dropout_prob,
+ attention_dropout=self.attention_probs_dropout_prob,
+ prediction_length=self.prediction_length,
+ context_length=self.context_length,
+ label_length=self.label_length,
+ lags_sequence=self.lags_sequence,
+ num_time_features=self.num_time_features,
+ num_static_categorical_features=1,
+ cardinality=[self.cardinality],
+ embedding_dimension=[self.embedding_dimension],
+ moving_average=self.moving_average,
+ scaling="std", # we need std to get non-zero `loc`
+ )
+
+ def prepare_autoformer_inputs_dict(self, config):
+ _past_length = config.context_length + max(config.lags_sequence)
+
+ static_categorical_features = ids_tensor([self.batch_size, 1], config.cardinality[0])
+ past_time_features = floats_tensor([self.batch_size, _past_length, config.num_time_features])
+ past_values = floats_tensor([self.batch_size, _past_length])
+ past_observed_mask = floats_tensor([self.batch_size, _past_length]) > 0.5
+
+ # decoder inputs
+ future_time_features = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features])
+ future_values = floats_tensor([self.batch_size, config.prediction_length])
+
+ inputs_dict = {
+ "past_values": past_values,
+ "static_categorical_features": static_categorical_features,
+ "past_time_features": past_time_features,
+ "past_observed_mask": past_observed_mask,
+ "future_time_features": future_time_features,
+ "future_values": future_values,
+ }
+ return inputs_dict
+
+ def prepare_config_and_inputs(self):
+ config = self.get_config()
+ inputs_dict = self.prepare_autoformer_inputs_dict(config)
+ return config, inputs_dict
+
+ def prepare_config_and_inputs_for_common(self):
+ config, inputs_dict = self.prepare_config_and_inputs()
+ return config, inputs_dict
+
+ def check_encoder_decoder_model_standalone(self, config, inputs_dict):
+ model = AutoformerModel(config=config).to(torch_device).eval()
+ outputs = model(**inputs_dict)
+
+ encoder_last_hidden_state = outputs.encoder_last_hidden_state
+ last_hidden_state = outputs.last_hidden_state
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ encoder = model.get_encoder()
+ encoder.save_pretrained(tmpdirname)
+ encoder = AutoformerEncoder.from_pretrained(tmpdirname).to(torch_device)
+
+ transformer_inputs, feature, _, _, _ = model.create_network_inputs(**inputs_dict)
+ seasonal_input, trend_input = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...])
+
+ enc_input = torch.cat(
+ (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]),
+ dim=-1,
+ )
+ encoder_last_hidden_state_2 = encoder(inputs_embeds=enc_input)[0]
+ self.parent.assertTrue((encoder_last_hidden_state_2 - encoder_last_hidden_state).abs().max().item() < 1e-3)
+
+ mean = (
+ torch.mean(transformer_inputs[:, : config.context_length, ...], dim=1)
+ .unsqueeze(1)
+ .repeat(1, config.prediction_length, 1)
+ )
+ zeros = torch.zeros(
+ [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]],
+ device=enc_input.device,
+ )
+
+ dec_input = torch.cat(
+ (
+ torch.cat((seasonal_input[:, -config.label_length :, ...], zeros), dim=1),
+ feature[:, config.context_length - config.label_length :, ...],
+ ),
+ dim=-1,
+ )
+ trend_init = torch.cat(
+ (
+ torch.cat((trend_input[:, -config.label_length :, ...], mean), dim=1),
+ feature[:, config.context_length - config.label_length :, ...],
+ ),
+ dim=-1,
+ )
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ decoder = model.get_decoder()
+ decoder.save_pretrained(tmpdirname)
+ decoder = AutoformerDecoder.from_pretrained(tmpdirname).to(torch_device)
+
+ last_hidden_state_2 = decoder(
+ trend=trend_init,
+ inputs_embeds=dec_input,
+ encoder_hidden_states=encoder_last_hidden_state,
+ )[0]
+
+ self.parent.assertTrue((last_hidden_state_2 - last_hidden_state).abs().max().item() < 1e-3)
+
+
+@require_torch
+class AutoformerModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
+ all_model_classes = (AutoformerModel, AutoformerForPrediction) if is_torch_available() else ()
+ pipeline_model_mapping = {"feature-extraction": AutoformerModel} if is_torch_available() else {}
+ test_pruning = False
+ test_head_masking = False
+ test_missing_keys = False
+ test_torchscript = False
+ test_inputs_embeds = False
+
+ def setUp(self):
+ self.model_tester = AutoformerModelTester(self)
+ self.config_tester = ConfigTester(self, config_class=AutoformerConfig, has_text_modality=False)
+
+ # TODO: (ydshieh) Fix the wrong logic for `tmp_delay` is possible
+ @unittest.skip(
+ reason="The computation of `tmp_delay` in `AutoformerAttention.forward` seems wrong, see PR #12345. Also `topk` is used to compute indices which is not stable."
+ )
+ def test_batching_equivalence(self):
+ super().test_batching_equivalence()
+
+ def test_config(self):
+ self.config_tester.run_common_tests()
+
+ def test_save_load_strict(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ model.save_pretrained(tmpdirname)
+ model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
+ self.assertEqual(info["missing_keys"], [])
+
+ def test_encoder_decoder_model_standalone(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
+ self.model_tester.check_encoder_decoder_model_standalone(*config_and_inputs)
+
+ @unittest.skip(reason="Model has no tokens embeddings")
+ def test_resize_tokens_embeddings(self):
+ pass
+
+ @unittest.skip(
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
+ )
+ def test_training_gradient_checkpointing(self):
+ pass
+
+ @unittest.skip(
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
+ )
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
+ pass
+
+ @unittest.skip(
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
+ )
+ def test_training_gradient_checkpointing_use_reentrant(self):
+ pass
+
+ # # Input is 'static_categorical_features' not 'input_ids'
+ def test_model_main_input_name(self):
+ model_signature = inspect.signature(getattr(AutoformerModel, "forward"))
+ # The main input is the name of the argument after `self`
+ observed_main_input_name = list(model_signature.parameters.keys())[1]
+ self.assertEqual(AutoformerModel.main_input_name, observed_main_input_name)
+
+ def test_forward_signature(self):
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+ signature = inspect.signature(model.forward)
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
+ arg_names = [*signature.parameters.keys()]
+
+ expected_arg_names = [
+ "past_values",
+ "past_time_features",
+ "past_observed_mask",
+ "static_categorical_features",
+ "static_real_features",
+ "future_values",
+ "future_time_features",
+ ]
+
+ if model.__class__.__name__ in ["AutoformerForPrediction"]:
+ expected_arg_names.append("future_observed_mask")
+
+ expected_arg_names.extend(
+ [
+ "decoder_attention_mask",
+ "head_mask",
+ "decoder_head_mask",
+ "cross_attn_head_mask",
+ "encoder_outputs",
+ "past_key_values",
+ "output_hidden_states",
+ "output_attentions",
+ "use_cache",
+ "return_dict",
+ ]
+ )
+
+ self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names)
+
+ def test_attention_outputs(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+ config.return_dict = True
+
+ seq_len = getattr(self.model_tester, "seq_length", None)
+ decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len)
+ encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len)
+ d_model = getattr(self.model_tester, "d_model", None)
+ num_attention_heads = getattr(self.model_tester, "num_attention_heads", None)
+ dim = d_model // num_attention_heads
+
+ for model_class in self.all_model_classes:
+ inputs_dict["output_attentions"] = True
+ inputs_dict["output_hidden_states"] = False
+ config.return_dict = True
+ model = model_class(config)
+ model.to(torch_device)
+ model.eval()
+ with torch.no_grad():
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
+ attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
+ self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
+
+ # check that output_attentions also work using config
+ del inputs_dict["output_attentions"]
+ config.output_attentions = True
+ model = model_class(config)
+ model.to(torch_device)
+ model.eval()
+ with torch.no_grad():
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
+ attentions = outputs.encoder_attentions
+ self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
+
+ self.assertListEqual(
+ list(attentions[0].shape[-3:]),
+ [self.model_tester.num_attention_heads, encoder_seq_length, dim],
+ )
+ out_len = len(outputs)
+
+ correct_outlen = 7
+
+ if "last_hidden_state" in outputs:
+ correct_outlen += 1
+
+ if "trend" in outputs:
+ correct_outlen += 1
+
+ if "past_key_values" in outputs:
+ correct_outlen += 1 # past_key_values have been returned
+
+ if "loss" in outputs:
+ correct_outlen += 1
+
+ if "params" in outputs:
+ correct_outlen += 1
+
+ self.assertEqual(out_len, correct_outlen)
+
+ # decoder attentions
+ decoder_attentions = outputs.decoder_attentions
+ self.assertIsInstance(decoder_attentions, (list, tuple))
+ self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers)
+ self.assertListEqual(
+ list(decoder_attentions[0].shape[-3:]),
+ [self.model_tester.num_attention_heads, decoder_seq_length, dim],
+ )
+
+ # cross attentions
+ cross_attentions = outputs.cross_attentions
+ self.assertIsInstance(cross_attentions, (list, tuple))
+ self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers)
+ self.assertListEqual(
+ list(cross_attentions[0].shape[-3:]),
+ [self.model_tester.num_attention_heads, decoder_seq_length, dim],
+ )
+
+ # Check attention is always last and order is fine
+ inputs_dict["output_attentions"] = True
+ inputs_dict["output_hidden_states"] = True
+ model = model_class(config)
+ model.to(torch_device)
+ model.eval()
+ with torch.no_grad():
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
+
+ self.assertEqual(out_len + 2, len(outputs))
+
+ self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
+
+ self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers)
+ self.assertListEqual(
+ list(self_attentions[0].shape[-3:]),
+ [self.model_tester.num_attention_heads, encoder_seq_length, dim],
+ )
+
+ @is_flaky()
+ def test_retain_grad_hidden_states_attentions(self):
+ super().test_retain_grad_hidden_states_attentions()
+
+ @unittest.skip(reason="Model does not have input embeddings")
+ def test_model_get_set_embeddings(self):
+ pass
+
+
+def prepare_batch(filename="train-batch.pt"):
+ file = hf_hub_download(repo_id="hf-internal-testing/tourism-monthly-batch", filename=filename, repo_type="dataset")
+ batch = torch.load(file, map_location=torch_device)
+ return batch
+
+
+@require_torch
+@slow
+class AutoformerModelIntegrationTests(unittest.TestCase):
+ def test_inference_no_head(self):
+ model = AutoformerModel.from_pretrained("huggingface/autoformer-tourism-monthly").to(torch_device)
+ batch = prepare_batch()
+
+ with torch.no_grad():
+ output = model(
+ past_values=batch["past_values"],
+ past_time_features=batch["past_time_features"],
+ past_observed_mask=batch["past_observed_mask"],
+ static_categorical_features=batch["static_categorical_features"],
+ future_values=batch["future_values"],
+ future_time_features=batch["future_time_features"],
+ )[0]
+
+ expected_shape = torch.Size(
+ (64, model.config.prediction_length + model.config.label_length, model.config.feature_size)
+ )
+ self.assertEqual(output.shape, expected_shape)
+
+ expected_slice = torch.tensor(
+ [[0.3593, -1.3398, 0.6330], [0.2279, 1.5396, -0.1792], [0.0450, 1.3225, -0.2335]], device=torch_device
+ )
+ torch.testing.assert_close(output[0, :3, :3], expected_slice, rtol=TOLERANCE, atol=TOLERANCE)
+
+ def test_inference_head(self):
+ model = AutoformerForPrediction.from_pretrained("huggingface/autoformer-tourism-monthly").to(torch_device)
+ batch = prepare_batch("val-batch.pt")
+ with torch.no_grad():
+ output = model(
+ past_values=batch["past_values"],
+ past_time_features=batch["past_time_features"],
+ past_observed_mask=batch["past_observed_mask"],
+ static_categorical_features=batch["static_categorical_features"],
+ ).encoder_last_hidden_state
+ expected_shape = torch.Size((64, model.config.context_length, model.config.d_model))
+ self.assertEqual(output.shape, expected_shape)
+
+ expected_slice = torch.tensor(
+ [[-0.0734, -0.9036, 0.8358], [4.7186, 2.4113, 1.9581], [1.7953, 2.3558, 1.2970]], device=torch_device
+ )
+ torch.testing.assert_close(output[0, :3, :3], expected_slice, rtol=TOLERANCE, atol=TOLERANCE)
+
+ def test_seq_to_seq_generation(self):
+ model = AutoformerForPrediction.from_pretrained("huggingface/autoformer-tourism-monthly").to(torch_device)
+ batch = prepare_batch("val-batch.pt")
+ with torch.no_grad():
+ outputs = model.generate(
+ static_categorical_features=batch["static_categorical_features"],
+ past_time_features=batch["past_time_features"],
+ past_values=batch["past_values"],
+ future_time_features=batch["future_time_features"],
+ past_observed_mask=batch["past_observed_mask"],
+ )
+ expected_shape = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length))
+ self.assertEqual(outputs.sequences.shape, expected_shape)
+
+ expected_slice = torch.tensor([3130.6763, 4056.5293, 7053.0786], device=torch_device)
+ mean_prediction = outputs.sequences.mean(dim=1)
+ torch.testing.assert_close(mean_prediction[0, -3:], expected_slice, rtol=1e-1, atol=1e-1)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/aya_vision/__init__.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/aya_vision/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/aya_vision/test_modeling_aya_vision.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/aya_vision/test_modeling_aya_vision.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc8fe2503df1c9c2e3553f54d4353bcc8e30d2b5
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/aya_vision/test_modeling_aya_vision.py
@@ -0,0 +1,576 @@
+# 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.
+"""Testing suite for the PyTorch GotOcr2 model."""
+
+import unittest
+
+from parameterized import parameterized
+
+from transformers import (
+ AutoProcessor,
+ AyaVisionConfig,
+ is_torch_available,
+ is_vision_available,
+)
+from transformers.testing_utils import (
+ cleanup,
+ require_read_token,
+ require_torch,
+ require_torch_gpu,
+ slow,
+ torch_device,
+)
+
+from ...generation.test_utils import GenerationTesterMixin
+from ...test_configuration_common import ConfigTester
+from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
+from ...test_pipeline_mixin import PipelineTesterMixin
+
+
+if is_torch_available():
+ import torch
+
+ from transformers import (
+ AyaVisionForConditionalGeneration,
+ )
+
+
+if is_vision_available():
+ pass
+
+
+class AyaVisionVisionText2TextModelTester:
+ def __init__(
+ self,
+ parent,
+ batch_size=3,
+ seq_length=7,
+ vision_feature_layer=-1,
+ downsample_factor=2,
+ ignore_index=-100,
+ bos_token_id=0,
+ eos_token_id=0,
+ pad_token_id=0,
+ image_token_index=1,
+ num_channels=3,
+ image_size=64,
+ model_type="aya_vision",
+ is_training=True,
+ text_config={
+ "model_type": "cohere2",
+ "vocab_size": 99,
+ "hidden_size": 128,
+ "intermediate_size": 37,
+ "num_hidden_layers": 4,
+ "num_attention_heads": 4,
+ "output_channels": 64,
+ "hidden_act": "silu",
+ "max_position_embeddings": 512,
+ "tie_word_embeddings": True,
+ "bos_token_id": 0,
+ "eos_token_id": 0,
+ "pad_token_id": 0,
+ },
+ vision_config={
+ "model_type": "siglip_vision_model",
+ "hidden_size": 32,
+ "num_hidden_layers": 2,
+ "num_attention_heads": 4,
+ "intermediate_size": 128,
+ "image_size": 64,
+ "patch_size": 8,
+ "vision_use_head": False,
+ },
+ ):
+ self.parent = parent
+ self.ignore_index = ignore_index
+ self.bos_token_id = bos_token_id
+ self.eos_token_id = eos_token_id
+ self.pad_token_id = pad_token_id
+ self.image_token_index = image_token_index
+ self.model_type = model_type
+ self.text_config = text_config
+ self.vision_config = vision_config
+ self.batch_size = batch_size
+ self.vision_feature_layer = vision_feature_layer
+ self.downsample_factor = downsample_factor
+ self.is_training = is_training
+ self.num_channels = num_channels
+ self.image_size = image_size
+ self.image_seq_length = (image_size // (vision_config["patch_size"] * downsample_factor)) ** 2
+ self.seq_length = seq_length + self.image_seq_length
+
+ self.num_hidden_layers = text_config["num_hidden_layers"]
+ self.vocab_size = text_config["vocab_size"]
+ self.hidden_size = text_config["hidden_size"]
+ self.num_attention_heads = text_config["num_attention_heads"]
+
+ def get_config(self):
+ return AyaVisionConfig(
+ text_config=self.text_config,
+ vision_config=self.vision_config,
+ model_type=self.model_type,
+ bos_token_id=self.bos_token_id,
+ eos_token_id=self.eos_token_id,
+ pad_token_id=self.pad_token_id,
+ image_token_index=self.image_token_index,
+ vision_feature_layer=self.vision_feature_layer,
+ downsample_factor=self.downsample_factor,
+ )
+
+ def prepare_config_and_inputs(self):
+ config = self.get_config()
+ pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
+
+ return config, pixel_values
+
+ def prepare_config_and_inputs_for_common(self):
+ config_and_inputs = self.prepare_config_and_inputs()
+ config, pixel_values = config_and_inputs
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
+ attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
+ print("attention_mask", attention_mask.shape)
+ # input_ids[:, -1] = self.pad_token_id
+ input_ids[input_ids == self.image_token_index] = self.pad_token_id
+ input_ids[:, : self.image_seq_length] = self.image_token_index
+
+ inputs_dict = {
+ "pixel_values": pixel_values,
+ "input_ids": input_ids,
+ "attention_mask": attention_mask,
+ }
+ return config, inputs_dict
+
+ def create_and_check_model_fp16_forward(self, config, input_ids, pixel_values, attention_mask):
+ model = AyaVisionForConditionalGeneration(config=config)
+ model.to(torch_device)
+ model.half()
+ model.eval()
+ logits = model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ pixel_values=pixel_values,
+ return_dict=True,
+ )["logits"]
+ self.parent.assertFalse(torch.isnan(logits).any().item())
+
+ def create_and_check_model_fp16_autocast_forward(self, config, input_ids, pixel_values, attention_mask):
+ config.torch_dtype = torch.float16
+ model = AyaVisionForConditionalGeneration(config=config)
+ model.to(torch_device)
+ model.eval()
+ with torch.autocast(device_type="cuda", dtype=torch.float16):
+ logits = model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ pixel_values=pixel_values,
+ return_dict=True,
+ )["logits"]
+ self.parent.assertFalse(torch.isnan(logits).any().item())
+
+
+@require_torch
+class AyaVisionModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
+ all_model_classes = (AyaVisionForConditionalGeneration,) if is_torch_available() else ()
+ all_generative_model_classes = (AyaVisionForConditionalGeneration,) if is_torch_available() else ()
+ pipeline_model_mapping = (
+ {
+ "image-text-to-text": AyaVisionForConditionalGeneration,
+ }
+ if is_torch_available()
+ else {}
+ )
+ fx_compatible = False
+ test_pruning = False
+ test_torchscript = False
+ test_head_masking = False
+ _is_composite = True
+
+ def setUp(self):
+ self.model_tester = AyaVisionVisionText2TextModelTester(self)
+ self.config_tester = ConfigTester(self, config_class=AyaVisionConfig, has_text_modality=False)
+
+ def test_config(self):
+ self.config_tester.run_common_tests()
+
+ # overwrite inputs_embeds tests because we need to delete "pixel values" for LVLMs
+ def test_inputs_embeds(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+ model.to(torch_device)
+ model.eval()
+
+ inputs = self._prepare_for_class(inputs_dict, model_class)
+
+ input_ids = inputs["input_ids"]
+ del inputs["input_ids"]
+ del inputs["pixel_values"]
+
+ wte = model.get_input_embeddings()
+ inputs["inputs_embeds"] = wte(input_ids)
+
+ with torch.no_grad():
+ model(**inputs)
+
+ # overwrite inputs_embeds tests because we need to delete "pixel values" for LVLMs
+ # while some other models require pixel_values to be present
+ def test_inputs_embeds_matches_input_ids(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+ model.to(torch_device)
+ model.eval()
+
+ inputs = self._prepare_for_class(inputs_dict, model_class)
+ input_ids = inputs["input_ids"]
+ del inputs["input_ids"]
+ del inputs["pixel_values"]
+
+ inputs_embeds = model.get_input_embeddings()(input_ids)
+
+ with torch.no_grad():
+ out_ids = model(input_ids=input_ids, **inputs)[0]
+ out_embeds = model(inputs_embeds=inputs_embeds, **inputs)[0]
+ torch.testing.assert_close(out_embeds, out_ids)
+
+ @unittest.skip("Failing because of unique cache (HybridCache)")
+ def test_model_outputs_equivalence(self, **kwargs):
+ pass
+
+ @unittest.skip("Cohere2's forcefully disables sdpa due to softcapping")
+ def test_sdpa_can_dispatch_non_composite_models(self):
+ pass
+
+ @parameterized.expand([("float16",), ("bfloat16",), ("float32",)])
+ @unittest.skip("Cohere2's eager attn/sdpa attn outputs are expected to be different")
+ def test_eager_matches_sdpa_inference(self):
+ pass
+
+ @unittest.skip("Cohere2's eager attn/sdpa attn outputs are expected to be different")
+ def test_eager_matches_sdpa_generate(self):
+ pass
+
+ @parameterized.expand([("random",), ("same",)])
+ @unittest.skip("Cohere2 has HybridCache which is not compatible with assisted decoding")
+ def test_assisted_decoding_matches_greedy_search(self, assistant_type):
+ pass
+
+ @unittest.skip("Cohere2 has HybridCache which is not compatible with assisted decoding")
+ def test_prompt_lookup_decoding_matches_greedy_search(self, assistant_type):
+ pass
+
+ @unittest.skip("Cohere2 has HybridCache which is not compatible with assisted decoding")
+ def test_assisted_decoding_sample(self):
+ pass
+
+ @unittest.skip("Cohere2 has HybridCache which is not compatible with dola decoding")
+ def test_dola_decoding_sample(self):
+ pass
+
+ @unittest.skip("Cohere2 has HybridCache and doesn't support continue from past kv")
+ def test_generate_continue_from_past_key_values(self):
+ pass
+
+ @unittest.skip("Cohere2 has HybridCache and doesn't support low_memory generation")
+ def test_beam_search_low_memory(self):
+ pass
+
+ @unittest.skip("Cohere2 has HybridCache and doesn't support contrastive generation")
+ def test_contrastive_generate(self):
+ pass
+
+ @unittest.skip("Cohere2 has HybridCache and doesn't support contrastive generation")
+ def test_contrastive_generate_dict_outputs_use_cache(self):
+ pass
+
+ @unittest.skip("Cohere2 has HybridCache and doesn't support contrastive generation")
+ def test_contrastive_generate_low_memory(self):
+ pass
+
+ @unittest.skip("Cohere2 has HybridCache and doesn't support StaticCache. Though it could, it shouldn't support.")
+ def test_generate_with_static_cache(self):
+ pass
+
+ @unittest.skip("Cohere2 has HybridCache and doesn't support StaticCache. Though it could, it shouldn't support.")
+ def test_generate_from_inputs_embeds_with_static_cache(self):
+ pass
+
+ @unittest.skip("Cohere2 has HybridCache and doesn't support progressive generation using input embeds.")
+ def test_generate_continue_from_inputs_embeds(self):
+ pass
+
+ @unittest.skip("Failing because of unique cache (HybridCache)")
+ def test_multi_gpu_data_parallel_forward(self):
+ pass
+
+ @unittest.skip("Cohere2's eager attn/sdpa attn outputs are expected to be different")
+ def test_sdpa_equivalence(self):
+ pass
+
+ @unittest.skip(reason="SiglipVisionModel does not support standalone training")
+ def test_training(self):
+ pass
+
+ @unittest.skip(reason="SiglipVisionModel does not support standalone training")
+ def test_training_gradient_checkpointing(self):
+ pass
+
+ @unittest.skip(reason="SiglipVisionModel does not support standalone training")
+ def test_training_gradient_checkpointing_use_reentrant(self):
+ pass
+
+ @unittest.skip(reason="SiglipVisionModel does not support standalone training")
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
+ pass
+
+ @unittest.skip(reason="Siglip uses the same initialization scheme as the Flax original implementation")
+ def test_initialization(self):
+ pass
+
+ @unittest.skip(reason="Compile not yet supported because in LLava models")
+ def test_sdpa_can_compile_dynamic(self):
+ pass
+
+ @unittest.skip("FlashAttention only support fp16 and bf16 data type")
+ def test_flash_attn_2_fp32_ln(self):
+ pass
+
+ # todo: yoni - fix or improve the test
+ @unittest.skip("Difference is slightly higher than the threshold")
+ def test_batching_equivalence(self):
+ pass
+
+
+@require_read_token
+@require_torch
+class AyaVisionIntegrationTest(unittest.TestCase):
+ def setUp(self):
+ self.model_checkpoint = "CohereForAI/aya-vision-8b"
+
+ def tearDown(self):
+ cleanup(torch_device, gc_collect=True)
+
+ @slow
+ @require_torch_gpu
+ def test_small_model_integration_forward(self):
+ processor = AutoProcessor.from_pretrained(self.model_checkpoint)
+ model = AyaVisionForConditionalGeneration.from_pretrained(
+ self.model_checkpoint, device_map=torch_device, torch_dtype=torch.float16
+ )
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"},
+ {"type": "text", "text": "Please describe the image explicitly."},
+ ],
+ }
+ ]
+
+ inputs = processor.apply_chat_template(
+ messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
+ ).to(torch_device, dtype=torch.float16)
+ # Forward
+ with torch.inference_mode():
+ output = model(**inputs)
+
+ actual_logits = output.logits[0, -1, :5].cpu()
+ print("actual_logits", actual_logits)
+ expected_logits = torch.tensor([0.4109, 0.1532, 0.8018, 2.1328, 0.5483], dtype=torch.float16)
+ self.assertTrue(
+ torch.allclose(actual_logits, expected_logits, atol=0.1),
+ f"Actual logits: {actual_logits}"
+ f"\nExpected logits: {expected_logits}"
+ f"\nDifference: {torch.abs(actual_logits - expected_logits)}",
+ )
+
+ @slow
+ @require_torch_gpu
+ def test_small_model_integration_generate_text_only(self):
+ processor = AutoProcessor.from_pretrained(self.model_checkpoint)
+ model = AyaVisionForConditionalGeneration.from_pretrained(
+ self.model_checkpoint, device_map=torch_device, torch_dtype=torch.float16
+ )
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Write a haiku"},
+ ],
+ }
+ ]
+
+ inputs = processor.apply_chat_template(
+ messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
+ ).to(torch_device, dtype=torch.float16)
+ with torch.no_grad():
+ generate_ids = model.generate(**inputs, max_new_tokens=25, do_sample=False)
+ decoded_output = processor.decode(
+ generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True
+ )
+ print("decoded_output", decoded_output)
+ expected_output = "Whispers on the breeze,\nLeaves dance under moonlit skies,\nNature's quiet song."
+ self.assertEqual(decoded_output, expected_output)
+
+ @slow
+ @require_torch_gpu
+ def test_small_model_integration_generate_chat_template(self):
+ processor = AutoProcessor.from_pretrained(self.model_checkpoint)
+ model = AyaVisionForConditionalGeneration.from_pretrained(
+ self.model_checkpoint, device_map=torch_device, torch_dtype=torch.float16
+ )
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"},
+ {"type": "text", "text": "Please describe the image explicitly."},
+ ],
+ }
+ ]
+
+ inputs = processor.apply_chat_template(
+ messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
+ ).to(torch_device, dtype=torch.float16)
+ with torch.no_grad():
+ generate_ids = model.generate(**inputs, max_new_tokens=20, do_sample=False)
+ decoded_output = processor.decode(
+ generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True
+ )
+ print("decoded_output", decoded_output)
+ expected_output = "The image depicts a cozy scene of two cats resting on a bright pink blanket. The cats," # fmt: skip
+ self.assertEqual(decoded_output, expected_output)
+
+ @slow
+ @require_torch_gpu
+ def test_small_model_integration_batched_generate(self):
+ processor = AutoProcessor.from_pretrained(self.model_checkpoint)
+ model = AyaVisionForConditionalGeneration.from_pretrained(
+ self.model_checkpoint, device_map=torch_device, torch_dtype=torch.float16
+ )
+ # Prepare inputs
+ 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.float16)
+
+ output = model.generate(**inputs, do_sample=False, max_new_tokens=25)
+
+ # Check first output
+ decoded_output = processor.decode(output[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True)
+ print("decoded_output", decoded_output)
+ expected_output = "Wooden path to water,\nMountains echo in stillness,\nPeaceful forest scene." # fmt: skip
+ self.assertEqual(
+ decoded_output,
+ expected_output,
+ f"Decoded output: {decoded_output}\nExpected output: {expected_output}",
+ )
+
+ # Check second output
+ decoded_output = processor.decode(output[1, inputs["input_ids"].shape[1] :], skip_special_tokens=True)
+ print("decoded_output", decoded_output)
+ expected_output = 'This image captures a vibrant street scene in a bustling urban area, likely in an Asian city. The focal point is a' # fmt: skip
+
+ self.assertEqual(
+ decoded_output,
+ expected_output,
+ f"Decoded output: {decoded_output}\nExpected output: {expected_output}",
+ )
+
+ @slow
+ @require_torch_gpu
+ def test_small_model_integration_batched_generate_multi_image(self):
+ processor = AutoProcessor.from_pretrained(self.model_checkpoint)
+ model = AyaVisionForConditionalGeneration.from_pretrained(
+ self.model_checkpoint, device_map=torch_device, torch_dtype=torch.float16
+ )
+ # Prepare inputs
+ 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.float16)
+ output = model.generate(**inputs, do_sample=False, max_new_tokens=25)
+
+ # Check first output
+ decoded_output = processor.decode(output[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True)
+ # Batching seems to alter the output slightly, but it is also the case in the original implementation. This seems to be expected: https://github.com/huggingface/transformers/issues/23017#issuecomment-1649630232
+ expected_output = "Wooden path to water,\nMountains echo in stillness,\nPeaceful forest scene." # fmt: skip
+ print("decoded_output", decoded_output)
+ self.assertEqual(
+ decoded_output,
+ expected_output,
+ f"Decoded output: {decoded_output}\nExpected output: {expected_output}",
+ )
+
+ # Check second output
+ decoded_output = processor.decode(output[1, inputs["input_ids"].shape[1] :], skip_special_tokens=True)
+ print("decoded_output", decoded_output)
+ expected_output = "The first image showcases the Statue of Liberty, a colossal neoclassical sculpture on Liberty Island in New York Harbor. Standing at a" # fmt: skip
+ self.assertEqual(
+ decoded_output,
+ expected_output,
+ f"Decoded output: {decoded_output}\nExpected output: {expected_output}",
+ )
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/aya_vision/test_processor_aya_vision.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/aya_vision/test_processor_aya_vision.py
new file mode 100644
index 0000000000000000000000000000000000000000..8830f85c50c1e2e439d35b362dddc20d7ea780e9
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/aya_vision/test_processor_aya_vision.py
@@ -0,0 +1,164 @@
+# coding=utf-8
+# 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.
+
+import shutil
+import tempfile
+import unittest
+from typing import Optional
+
+from transformers import AutoProcessor, AutoTokenizer, AyaVisionProcessor
+from transformers.testing_utils import require_read_token, require_torch, require_vision
+from transformers.utils import is_torch_available, is_vision_available
+
+from ...test_processing_common import ProcessorTesterMixin
+
+
+if is_torch_available():
+ import torch
+
+
+if is_vision_available():
+ from transformers import GotOcr2ImageProcessor
+
+
+@require_read_token
+@require_vision
+class AyaVisionProcessorTest(ProcessorTesterMixin, unittest.TestCase):
+ processor_class = AyaVisionProcessor
+
+ def setUp(self):
+ self.tmpdirname = tempfile.mkdtemp()
+
+ image_processor = GotOcr2ImageProcessor(
+ do_resize=True,
+ size={"height": 20, "width": 20},
+ max_patches=2,
+ do_rescale=True,
+ rescale_factor=1 / 255,
+ do_normalize=True,
+ image_mean=[0.485, 0.456, 0.406],
+ image_std=[0.229, 0.224, 0.225],
+ do_convert_rgb=True,
+ )
+ tokenizer = AutoTokenizer.from_pretrained("CohereForAI/aya-vision-8b", padding_side="left")
+ processor_kwargs = self.prepare_processor_dict()
+ processor = AyaVisionProcessor.from_pretrained(
+ "CohereForAI/aya-vision-8b",
+ image_processor=image_processor,
+ tokenizer=tokenizer,
+ **processor_kwargs,
+ )
+ processor.save_pretrained(self.tmpdirname)
+
+ def prepare_processor_dict(self):
+ return {"patch_size": 10, "img_size": 20}
+
+ def get_tokenizer(self, **kwargs):
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).tokenizer
+
+ def get_image_processor(self, **kwargs):
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor
+
+ def get_processor(self, **kwargs):
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs)
+
+ def tearDown(self):
+ shutil.rmtree(self.tmpdirname)
+
+ # todo: yoni, fix this test
+ @unittest.skip("Chat template has long system prompt")
+ def test_chat_template_accepts_processing_kwargs(self, **kwargs):
+ pass
+
+ # Override as AyaVisionProcessor needs image tokens in prompts
+ def prepare_text_inputs(self, batch_size: Optional[int] = None):
+ if batch_size is None:
+ return "lower newer "
+
+ if batch_size < 1:
+ raise ValueError("batch_size must be greater than 0")
+
+ if batch_size == 1:
+ return ["lower newer "]
+ return ["lower newer ", " upper older longer string"] + [" lower newer"] * (
+ batch_size - 2
+ )
+
+ @require_torch
+ def test_process_interleaved_images_videos(self):
+ processor = self.get_processor()
+
+ 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": "What are the differences between these two images?"},
+ ],
+ },
+ ],
+ [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "image",
+ "url": "https://llava-vl.github.io/static/images/view.jpg",
+ },
+ {"type": "text", "text": "Write a haiku for this image"},
+ ],
+ }
+ ],
+ ]
+
+ inputs_batched = processor.apply_chat_template(
+ messages,
+ add_generation_prompt=True,
+ tokenize=True,
+ return_dict=True,
+ return_tensors="pt",
+ padding=True,
+ )
+
+ # Process non batched inputs to check if the pixel_values and input_ids are reconstructed in the correct order when batched together
+ images_patches_index = 0
+ for i, message in enumerate(messages):
+ inputs = processor.apply_chat_template(
+ message,
+ add_generation_prompt=True,
+ tokenize=True,
+ return_dict=True,
+ return_tensors="pt",
+ padding=True,
+ )
+ # We slice with [-inputs["input_ids"].shape[1] :] as the input_ids are left padded
+ torch.testing.assert_close(
+ inputs["input_ids"][0], inputs_batched["input_ids"][i][-inputs["input_ids"].shape[1] :]
+ )
+ torch.testing.assert_close(
+ inputs["pixel_values"],
+ inputs_batched["pixel_values"][
+ images_patches_index : images_patches_index + inputs["pixel_values"].shape[0]
+ ],
+ )
+ images_patches_index += inputs["pixel_values"].shape[0]
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/bamba/__init__.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/bamba/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/bamba/test_modeling_bamba.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/bamba/test_modeling_bamba.py
new file mode 100644
index 0000000000000000000000000000000000000000..3cbc239a5e2224570de035162065f30d5bb944f9
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/bamba/test_modeling_bamba.py
@@ -0,0 +1,594 @@
+# 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.
+"""Testing suite for the PyTorch Bamba model."""
+
+import inspect
+import unittest
+
+import pytest
+
+from transformers import AutoTokenizer, BambaConfig, is_torch_available
+from transformers.testing_utils import (
+ require_torch,
+ require_torch_gpu,
+ slow,
+ torch_device,
+)
+
+from ...generation.test_utils import GenerationTesterMixin
+from ...test_configuration_common import ConfigTester
+from ...test_modeling_common import ModelTesterMixin, _config_zero_init, ids_tensor
+from ...test_pipeline_mixin import PipelineTesterMixin
+
+
+if is_torch_available():
+ import torch
+
+ from transformers import (
+ BambaForCausalLM,
+ BambaModel,
+ )
+ from transformers.models.bamba.modeling_bamba import (
+ HybridMambaAttentionDynamicCache,
+ )
+
+
+class BambaModelTester:
+ def __init__(
+ self,
+ parent,
+ batch_size=13,
+ seq_length=7,
+ is_training=True,
+ use_input_mask=True,
+ use_labels=True,
+ vocab_size=99,
+ hidden_size=32,
+ num_hidden_layers=4,
+ num_attention_heads=4,
+ num_key_value_heads=2,
+ intermediate_size=64,
+ hidden_act="silu",
+ attention_dropout=0.0,
+ attn_layer_indices=None,
+ attn_rotary_emb=8,
+ max_position_embeddings=512,
+ type_vocab_size=16,
+ initializer_range=0.02,
+ num_labels=3,
+ pad_token_id=0,
+ mamba_n_groups=1,
+ mamba_n_heads=16,
+ mamba_d_state=16,
+ mamba_d_conv=4,
+ mamba_expand=2,
+ mamba_chunk_size=16,
+ scope=None,
+ ):
+ self.parent = parent
+ self.batch_size = batch_size
+ self.seq_length = seq_length
+ self.is_training = is_training
+ self.use_input_mask = use_input_mask
+ self.use_labels = use_labels
+ self.vocab_size = vocab_size
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.num_key_value_heads = num_key_value_heads
+ self.intermediate_size = intermediate_size
+ self.hidden_act = hidden_act
+ self.attention_dropout = attention_dropout
+ self.attn_layer_indices = attn_layer_indices
+ self.attn_rotary_emb = attn_rotary_emb
+ self.max_position_embeddings = max_position_embeddings
+ self.type_vocab_size = type_vocab_size
+ self.initializer_range = initializer_range
+ self.num_labels = num_labels
+ self.pad_token_id = pad_token_id
+ self.scope = scope
+ self.mamba_n_groups = mamba_n_groups
+ self.mamba_n_heads = mamba_n_heads
+ self.mamba_d_state = mamba_d_state
+ self.mamba_d_conv = mamba_d_conv
+ self.mamba_expand = mamba_expand
+ self.mamba_chunk_size = mamba_chunk_size
+
+ def prepare_config_and_inputs(self):
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
+
+ input_mask = None
+ if self.use_input_mask:
+ input_mask = torch.tril(torch.ones_like(input_ids).to(torch_device))
+
+ token_labels = None
+ if self.use_labels:
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
+
+ config = self.get_config()
+
+ return config, input_ids, input_mask, token_labels
+
+ def prepare_config_and_inputs_for_common(self):
+ config_and_inputs = self.prepare_config_and_inputs()
+ (
+ config,
+ input_ids,
+ input_mask,
+ token_labels,
+ ) = config_and_inputs
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
+ return config, inputs_dict
+
+ def get_config(self):
+ # Fix for SDPA tests, force at least 4 layers
+ if self.num_hidden_layers < 4:
+ self.num_hidden_layers = 4
+ if self.attn_layer_indices is None:
+ d = [x for x in range(2, self.num_hidden_layers) if self.num_hidden_layers % x == 0]
+ if len(d) == 0:
+ raise ValueError("num_hidden_layers is prime, cannot automatically set attn_layer_indices.")
+ d = d[-1] # get the largest divisor
+ self.attn_layer_indices = [x + 1 for x in range(0, self.num_hidden_layers, d)]
+
+ return BambaConfig(
+ vocab_size=self.vocab_size,
+ hidden_size=self.hidden_size,
+ num_hidden_layers=self.num_hidden_layers,
+ num_attention_heads=self.num_attention_heads,
+ num_key_value_heads=self.num_key_value_heads,
+ intermediate_size=self.intermediate_size,
+ hidden_act=self.hidden_act,
+ attention_dropout=self.attention_dropout,
+ attn_layer_indices=self.attn_layer_indices,
+ attn_rotary_emb=self.attn_rotary_emb,
+ max_position_embeddings=self.max_position_embeddings,
+ initializer_range=self.initializer_range,
+ pad_token_id=self.pad_token_id,
+ mamba_n_groups=self.mamba_n_groups,
+ mamba_n_heads=self.mamba_n_heads,
+ mamba_d_state=self.mamba_d_state,
+ mamba_d_conv=self.mamba_d_conv,
+ mamba_expand=self.mamba_expand,
+ mamba_chunk_size=self.mamba_chunk_size,
+ )
+
+ def create_and_check_model(
+ self,
+ config,
+ input_ids,
+ input_mask,
+ token_labels,
+ ):
+ model = BambaModel(config=config)
+ model.to(torch_device)
+ model.eval()
+ result = model(input_ids, attention_mask=input_mask)
+ result = model(input_ids)
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
+
+ def create_and_check_for_causal_lm(
+ self,
+ config,
+ input_ids,
+ input_mask,
+ token_labels,
+ ):
+ model = BambaForCausalLM(config=config)
+ model.to(torch_device)
+ model.eval()
+ result = model(input_ids, attention_mask=input_mask, labels=token_labels)
+ result = model(input_ids, attention_mask=input_mask)
+ result = model(input_ids, labels=token_labels)
+ result = model(input_ids)
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
+
+ def create_and_check_decoder_model_past_large_inputs(
+ self,
+ config,
+ input_ids,
+ input_mask,
+ token_labels,
+ ):
+ # config.is_decoder = True
+ # config.add_cross_attention = True
+ model = BambaForCausalLM(config=config)
+ model.to(torch_device)
+ model.eval()
+
+ # first forward pass
+ # Attention: Jamba needs the cache to be initialized to return a cache!
+ past_key_values = HybridMambaAttentionDynamicCache(
+ config, input_ids.shape[0], model.dtype, device=model.device
+ )
+ outputs = model(
+ input_ids,
+ attention_mask=input_mask,
+ past_key_values=past_key_values,
+ use_cache=True,
+ )
+ past_key_values = outputs.past_key_values
+
+ # create hypothetical multiple next token and extent to next_input_ids
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
+
+ # append to next input_ids and
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
+
+ output_from_no_past = model(
+ next_input_ids,
+ attention_mask=next_attention_mask,
+ output_hidden_states=True,
+ )["hidden_states"][0]
+ output_from_past = model(
+ next_tokens,
+ attention_mask=next_attention_mask,
+ past_key_values=past_key_values,
+ output_hidden_states=True,
+ cache_position=torch.arange(
+ input_ids.shape[1], input_ids.shape[1] + next_tokens.shape[1], device=model.device
+ ),
+ )["hidden_states"][0]
+
+ # select random slice
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
+
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
+
+ # test that outputs are equal for slice
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
+
+
+@require_torch
+class BambaModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
+ all_model_classes = (BambaModel, BambaForCausalLM) if is_torch_available() else ()
+ pipeline_model_mapping = (
+ {
+ "feature-extraction": BambaModel,
+ "text-generation": BambaForCausalLM,
+ }
+ if is_torch_available()
+ else {}
+ )
+ test_headmasking = False
+ test_pruning = False
+ fx_compatible = False
+
+ # Need to use `0.8` instead of `0.9` for `test_cpu_offload`
+ # This is because we are hitting edge cases with the causal_mask buffer
+ model_split_percents = [0.5, 0.7, 0.8]
+
+ def setUp(self):
+ self.model_tester = BambaModelTester(self)
+ self.config_tester = ConfigTester(self, config_class=BambaConfig, hidden_size=64)
+
+ def test_config(self):
+ self.config_tester.run_common_tests()
+
+ def test_model(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_model(*config_and_inputs)
+
+ def test_for_casual_lm(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_for_causal_lm(*config_and_inputs)
+
+ def test_decoder_model_past_with_large_inputs(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
+
+ def test_initialization(self):
+ r"""
+ Overriding the test_initialization test as the A_log and D params of the Bamba mixer are initialized differently
+ """
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+
+ configs_no_init = _config_zero_init(config)
+ for model_class in self.all_model_classes:
+ model = model_class(config=configs_no_init)
+ for name, param in model.named_parameters():
+ if param.requires_grad:
+ if "A_log" in name:
+ A = torch.arange(1, config.mamba_n_heads + 1, dtype=torch.float32)
+ torch.testing.assert_close(param.data, torch.log(A), rtol=1e-5, atol=1e-5)
+ elif "D" in name:
+ D = torch.ones(config.mamba_n_heads, dtype=torch.float32)
+ torch.testing.assert_close(param.data, D, rtol=1e-5, atol=1e-5)
+ else:
+ self.assertIn(
+ ((param.data.mean() * 1e9).round() / 1e9).item(),
+ [0.0, 1.0],
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
+ )
+
+ def test_mismatched_shapes_have_properly_initialized_weights(self):
+ r"""
+ Overriding the test_mismatched_shapes_have_properly_initialized_weights test because A_log and D params of the
+ Bamba mixer are initialized differently and we tested that in test_initialization
+ """
+ self.skipTest(reason="Cumbersome and redundant for Bamba")
+
+ def test_attention_outputs(self):
+ r"""
+ Overriding the test_attention_outputs test as the Bamba model outputs attention only for its attention layers
+ """
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+ config.return_dict = True
+
+ seq_len = getattr(self.model_tester, "seq_length", None)
+ encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len)
+ encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length)
+
+ expected_num_attentions = self.model_tester.num_hidden_layers - len(self.model_tester.attn_layer_indices)
+
+ for model_class in self.all_model_classes:
+ inputs_dict["output_attentions"] = True
+ inputs_dict["output_hidden_states"] = False
+ config.return_dict = True
+ model = model_class(config)
+ model.to(torch_device)
+ model.eval()
+
+ with torch.no_grad():
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
+ attentions = outputs.attentions
+ self.assertEqual(len(attentions), expected_num_attentions)
+
+ # check that output_attentions also work using config
+ del inputs_dict["output_attentions"]
+ config.output_attentions = True
+ model = model_class(config)
+ model.to(torch_device)
+ model.eval()
+ with torch.no_grad():
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
+ attentions = outputs.attentions
+ self.assertEqual(len(attentions), expected_num_attentions)
+
+ self.assertListEqual(
+ list(attentions[0].shape[-3:]),
+ [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],
+ )
+ out_len = len(outputs)
+
+ # Check attention is always last and order is fine
+ inputs_dict["output_attentions"] = True
+ inputs_dict["output_hidden_states"] = True
+ model = model_class(config)
+ model.to(torch_device)
+ model.eval()
+ with torch.no_grad():
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
+
+ added_hidden_states = 1
+ self.assertEqual(out_len + added_hidden_states, len(outputs))
+
+ self_attentions = outputs.attentions
+
+ self.assertEqual(len(self_attentions), expected_num_attentions)
+ self.assertListEqual(
+ list(self_attentions[0].shape[-3:]),
+ [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],
+ )
+
+ def test_batching_equivalence(self):
+ # need to disable the tril input mask
+ orig = self.model_tester.use_input_mask
+ self.model_tester.use_input_mask = False
+ super().test_batching_equivalence()
+ self.model_tester.use_input_mask = orig
+
+ # essentially the same test in test_utils, just adjustment for rtol for this model
+ @pytest.mark.generate
+ def test_left_padding_compatibility(self):
+ # NOTE: left-padding results in small numerical differences. This is expected.
+ # See https://github.com/huggingface/transformers/issues/25420#issuecomment-1775317535
+
+ # First, filter out models that don't support left padding
+ # - The model must have generative capabilities
+ if len(self.all_generative_model_classes) == 0:
+ self.skipTest(reason="No generative architecture available for this model.")
+
+ # - The model must support padding
+ if not self.has_attentions:
+ self.skipTest(reason="This model doesn't support padding.")
+
+ # - The model must be a decoder-only architecture (encoder-based architectures use right-padding)
+ decoder_only_classes = []
+ for model_class in self.all_generative_model_classes:
+ config, _ = self.prepare_config_and_inputs_for_generate()
+ if config.is_encoder_decoder:
+ continue
+ else:
+ decoder_only_classes.append(model_class)
+ if len(decoder_only_classes) == 0:
+ self.skipTest(reason="No decoder-only architecture available for this model.")
+
+ # - Decoder-only architectures derived from encoder-decoder models could support it in theory, but we haven't
+ # added support for it yet. We skip these models for now.
+ has_encoder_attributes = any(
+ attr_name
+ for attr_name in config.to_dict().keys()
+ if attr_name.startswith("encoder") and attr_name != "encoder_no_repeat_ngram_size"
+ )
+ if has_encoder_attributes:
+ self.skipTest(
+ reason="The decoder-only derived from encoder-decoder models are not expected to support left-padding."
+ )
+
+ # Then, test left-padding
+ def _prepare_model_kwargs(input_ids, attention_mask, signature):
+ model_kwargs = {"input_ids": input_ids, "attention_mask": attention_mask}
+ if "position_ids" in signature:
+ position_ids = torch.cumsum(attention_mask, dim=-1) - 1
+ position_ids.masked_fill_(attention_mask == 0, 1)
+ model_kwargs["position_ids"] = position_ids
+ if "cache_position" in signature:
+ cache_position = torch.arange(input_ids.shape[-1], device=torch_device)
+ model_kwargs["cache_position"] = cache_position
+ return model_kwargs
+
+ for model_class in decoder_only_classes:
+ config, inputs_dict = self.prepare_config_and_inputs_for_generate()
+ input_ids = inputs_dict["input_ids"]
+
+ # - for left padding we absolutely need to use an all ones
+ # attention mask, so we do not use the one in inputs_dict
+ attention_mask = torch.ones_like(input_ids)
+
+ model = model_class(config).to(torch_device).eval()
+ signature = inspect.signature(model.forward).parameters.keys()
+
+ # no cache as some models require special cache classes to be init outside forward
+ model.generation_config.use_cache = False
+
+ # Without padding
+ model_kwargs = _prepare_model_kwargs(input_ids, attention_mask, signature)
+ next_logits_wo_padding = model(**model_kwargs).logits[:, -1, :]
+
+ # With left-padding (length 32)
+ # can hardcode pad_token to be 0 as we'll do attn masking anyway
+ pad_token_id = (
+ config.get_text_config().pad_token_id if config.get_text_config().pad_token_id is not None else 0
+ )
+ pad_size = (input_ids.shape[0], 32)
+ padding = torch.ones(pad_size, dtype=input_ids.dtype, device=torch_device) * pad_token_id
+ padded_input_ids = torch.cat((padding, input_ids), dim=1)
+ padded_attention_mask = torch.cat((torch.zeros_like(padding), attention_mask), dim=1)
+ model_kwargs = _prepare_model_kwargs(padded_input_ids, padded_attention_mask, signature)
+ next_logits_with_padding = model(**model_kwargs).logits[:, -1, :]
+
+ # They should result in very similar logits
+ torch.testing.assert_close(next_logits_wo_padding, next_logits_with_padding, rtol=1e-5, atol=1e-5)
+
+
+@slow
+@require_torch
+@require_torch_gpu
+class BambaModelIntegrationTest(unittest.TestCase):
+ model = None
+ tokenizer = None
+ # This variable is used to determine which CUDA device are we using for our runners (A10 or T4)
+ # Depending on the hardware we get different logits / generations
+ cuda_compute_capability_major_version = None
+
+ @classmethod
+ def setUpClass(cls):
+ model_id = "ibm-fms/Bamba-9B"
+ cls.model = BambaForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True)
+ cls.tokenizer = AutoTokenizer.from_pretrained(model_id)
+
+ # feels a bit forced to have to do this for the generation test
+ cls.tokenizer.pad_token_id = cls.model.config.pad_token_id
+ cls.tokenizer.padding_side = "left"
+
+ if is_torch_available() and torch.cuda.is_available():
+ # 8 is for A100 / A10 and 7 for T4
+ cls.cuda_compute_capability_major_version = torch.cuda.get_device_capability()[0]
+
+ def test_simple_generate(self):
+ # Key 9 for MI300, Key 8 for A100/A10, and Key 7 for T4.
+ #
+ # Note: Key 9 is currently set for MI300, but may need potential future adjustments for H100s,
+ # considering differences in hardware processing and potential deviations in generated text.
+ EXPECTED_TEXTS = {
+ # 7: "",
+ 8: "<|begin_of_text|>Hey how are you doing on this lovely evening? I hope you are all having a good time.",
+ 9: "<|begin_of_text|>Hey how are you doing on this lovely evening? I hope you are doing well. I am here",
+ }
+
+ self.model.to(torch_device)
+
+ input_ids = self.tokenizer("Hey how are you doing on this lovely evening?", return_tensors="pt")[
+ "input_ids"
+ ].to(torch_device)
+ out = self.model.generate(input_ids, do_sample=False, max_new_tokens=10)
+ output_sentence = self.tokenizer.decode(out[0, :])
+ self.assertEqual(output_sentence, EXPECTED_TEXTS[self.cuda_compute_capability_major_version])
+
+ # TODO: there are significant differences in the logits across major cuda versions, which shouldn't exist
+ if self.cuda_compute_capability_major_version == 8:
+ with torch.no_grad():
+ logits = self.model(input_ids=input_ids, logits_to_keep=40).logits
+
+ EXPECTED_LOGITS_NO_GRAD = torch.tensor(
+ [
+ 149., 142., 146., 142., 143., 144., 142., 145.,
+ 142., 146., 144., 146., 147., 147., 148., 145.,
+ 147., 145., 145., 145., 145., 144., 144., 144.,
+ 144., 145., 147., 146., 144., 144., 148., 147.,
+ 148., 147., 147., 147., 146., 146., 148., 148.
+ ], dtype=torch.bfloat16) # fmt: skip
+
+ torch.testing.assert_close(logits[0, -1, :40].cpu(), EXPECTED_LOGITS_NO_GRAD, rtol=1e-3, atol=1)
+
+ def test_simple_batched_generate_with_padding(self):
+ # Key 9 for MI300, Key 8 for A100/A10, and Key 7 for T4.
+ #
+ # Note: Key 9 is currently set for MI300, but may need potential future adjustments for H100s,
+ # considering differences in hardware processing and potential deviations in generated text.
+ EXPECTED_TEXTS = {
+ 7: [],
+ 8: [
+ "<|begin_of_text|>Hey how are you doing on this lovely evening? I hope you are doing well. I am here",
+ "!!!<|begin_of_text|>I am late! I need to get to work! I have to get to the",
+ ],
+ 9: [
+ "<|begin_of_text|>Hey how are you doing on this lovely evening? I hope you are doing well. I am here",
+ "!!!<|begin_of_text|>I am late! I need to be at the airport in 20 minutes! I",
+ ],
+ }
+
+ self.model.to(torch_device)
+
+ inputs = self.tokenizer(
+ ["Hey how are you doing on this lovely evening?", "I am late! I need to"],
+ padding=True,
+ return_tensors="pt",
+ ).to(torch_device)
+ out = self.model.generate(**inputs, do_sample=False, max_new_tokens=10)
+ output_sentences = self.tokenizer.batch_decode(out)
+ self.assertEqual(output_sentences[0], EXPECTED_TEXTS[self.cuda_compute_capability_major_version][0])
+ self.assertEqual(output_sentences[1], EXPECTED_TEXTS[self.cuda_compute_capability_major_version][1])
+
+ # TODO: there are significant differences in the logits across major cuda versions, which shouldn't exist
+ if self.cuda_compute_capability_major_version == 8:
+ with torch.no_grad():
+ logits = self.model(input_ids=inputs["input_ids"]).logits
+
+ EXPECTED_LOGITS_NO_GRAD_0 = torch.tensor(
+ [
+ 149., 142., 146., 142., 143., 144., 142., 145.,
+ 142., 146., 144., 146., 147., 147., 148., 145.,
+ 147., 145., 145., 145., 145., 144., 144., 144.,
+ 144., 145., 147., 146., 144., 144., 148., 147.,
+ 148., 147., 147., 147., 146., 146., 148., 148.
+ ], dtype=torch.bfloat16) # fmt: skip
+
+ EXPECTED_LOGITS_NO_GRAD_1 = torch.tensor(
+ [
+ 182., 178., 177., 174., 176., 176., 178., 178.,
+ 177., 179., 176., 183., 180., 182., 179., 174.,
+ 178., 176., 176., 175., 175., 175., 174., 173.,
+ 174., 182., 180., 176., 177., 177., 180., 176.,
+ 178., 177., 177., 175., 176., 177., 175., 177.
+ ], dtype=torch.bfloat16) # fmt: skip
+
+ torch.testing.assert_close(logits[0, -1, :40].cpu(), EXPECTED_LOGITS_NO_GRAD_0, rtol=1e-3, atol=1)
+ torch.testing.assert_close(logits[1, -1, :40].cpu(), EXPECTED_LOGITS_NO_GRAD_1, rtol=1e-3, atol=1)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/bark/__init__.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/bark/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/bark/test_modeling_bark.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/bark/test_modeling_bark.py
new file mode 100644
index 0000000000000000000000000000000000000000..d94f6d26d6e8762da55349e26e857dc831bb86ca
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/bark/test_modeling_bark.py
@@ -0,0 +1,1337 @@
+# coding=utf-8
+# Copyright 2023 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.
+"""Testing suite for the PyTorch Bark model."""
+
+import copy
+import inspect
+import tempfile
+import unittest
+
+import pytest
+
+from transformers import (
+ BarkCausalModel,
+ BarkCoarseConfig,
+ BarkConfig,
+ BarkFineConfig,
+ BarkSemanticConfig,
+ is_torch_available,
+)
+from transformers.models.bark.generation_configuration_bark import (
+ BarkCoarseGenerationConfig,
+ BarkFineGenerationConfig,
+ BarkSemanticGenerationConfig,
+)
+from transformers.testing_utils import (
+ require_flash_attn,
+ require_torch,
+ require_torch_fp16,
+ require_torch_gpu,
+ slow,
+ torch_device,
+)
+from transformers.utils import cached_property
+
+from ...generation.test_utils import GenerationTesterMixin
+from ...test_configuration_common import ConfigTester
+from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
+from ..encodec.test_modeling_encodec import EncodecModelTester
+
+
+if is_torch_available():
+ import torch
+
+ from transformers import (
+ BarkCoarseModel,
+ BarkFineModel,
+ BarkModel,
+ BarkProcessor,
+ BarkSemanticModel,
+ )
+
+
+class BarkSemanticModelTester:
+ def __init__(
+ self,
+ parent,
+ batch_size=3, # need batch_size != num_hidden_layers
+ seq_length=4,
+ is_training=False, # for now training is not supported
+ use_input_mask=True,
+ use_labels=True,
+ vocab_size=33,
+ output_vocab_size=33,
+ hidden_size=16,
+ num_hidden_layers=2,
+ num_attention_heads=2,
+ intermediate_size=15,
+ dropout=0.1,
+ window_size=256,
+ initializer_range=0.02,
+ n_codes_total=8, # for BarkFineModel
+ n_codes_given=1, # for BarkFineModel
+ ):
+ self.parent = parent
+ self.batch_size = batch_size
+ self.seq_length = seq_length
+ self.is_training = is_training
+ self.use_input_mask = use_input_mask
+ self.use_labels = use_labels
+ self.vocab_size = vocab_size
+ self.output_vocab_size = output_vocab_size
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.intermediate_size = intermediate_size
+ self.dropout = dropout
+ self.window_size = window_size
+ self.initializer_range = initializer_range
+ self.bos_token_id = output_vocab_size - 1
+ self.eos_token_id = output_vocab_size - 1
+ self.pad_token_id = output_vocab_size - 1
+
+ self.n_codes_total = n_codes_total
+ self.n_codes_given = n_codes_given
+
+ self.is_encoder_decoder = False
+
+ def prepare_config_and_inputs(self):
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
+
+ input_mask = None
+ if self.use_input_mask:
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
+
+ config = self.get_config()
+
+ head_mask = ids_tensor([self.num_hidden_layers, self.num_attention_heads], 2)
+
+ inputs_dict = {
+ "input_ids": input_ids,
+ "head_mask": head_mask,
+ "attention_mask": input_mask,
+ }
+
+ return config, inputs_dict
+
+ def get_config(self):
+ return BarkSemanticConfig(
+ vocab_size=self.vocab_size,
+ output_vocab_size=self.output_vocab_size,
+ hidden_size=self.hidden_size,
+ num_layers=self.num_hidden_layers,
+ num_heads=self.num_attention_heads,
+ use_cache=True,
+ bos_token_id=self.bos_token_id,
+ eos_token_id=self.eos_token_id,
+ pad_token_id=self.pad_token_id,
+ window_size=self.window_size,
+ )
+
+ def get_pipeline_config(self):
+ config = self.get_config()
+ config.vocab_size = 300
+ config.output_vocab_size = 300
+ return config
+
+ def prepare_config_and_inputs_for_common(self):
+ config, inputs_dict = self.prepare_config_and_inputs()
+ return config, inputs_dict
+
+ def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict):
+ model = BarkSemanticModel(config=config).to(torch_device).eval()
+
+ input_ids = inputs_dict["input_ids"]
+ attention_mask = inputs_dict["attention_mask"]
+
+ # first forward pass
+ outputs = model(input_ids, attention_mask=attention_mask, use_cache=True)
+
+ output, past_key_values = outputs.to_tuple()
+
+ # create hypothetical multiple next token and extent to next_input_ids
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
+ next_attn_mask = ids_tensor((self.batch_size, 3), 2)
+
+ # append to next input_ids and
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
+ next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1)
+
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["logits"]
+ output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[
+ "logits"
+ ]
+
+ # select random slice
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
+
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
+
+ # test that outputs are equal for slice
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
+
+ # test no attention_mask works
+ outputs = model(input_ids, use_cache=True)
+ _, past_key_values = outputs.to_tuple()
+ output_from_no_past = model(next_input_ids)["logits"]
+
+ output_from_past = model(next_tokens, past_key_values=past_key_values)["logits"]
+
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
+ # test that outputs are equal for slice
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
+
+
+class BarkCoarseModelTester:
+ def __init__(
+ self,
+ parent,
+ batch_size=3, # need batch_size != num_hidden_layers
+ seq_length=4,
+ is_training=False, # for now training is not supported
+ use_input_mask=True,
+ use_labels=True,
+ vocab_size=33,
+ output_vocab_size=33,
+ hidden_size=16,
+ num_hidden_layers=2,
+ num_attention_heads=2,
+ intermediate_size=15,
+ dropout=0.1,
+ window_size=256,
+ initializer_range=0.02,
+ n_codes_total=8, # for BarkFineModel
+ n_codes_given=1, # for BarkFineModel
+ ):
+ self.parent = parent
+ self.batch_size = batch_size
+ self.seq_length = seq_length
+ self.is_training = is_training
+ self.use_input_mask = use_input_mask
+ self.use_labels = use_labels
+ self.vocab_size = vocab_size
+ self.output_vocab_size = output_vocab_size
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.intermediate_size = intermediate_size
+ self.dropout = dropout
+ self.window_size = window_size
+ self.initializer_range = initializer_range
+ self.bos_token_id = output_vocab_size - 1
+ self.eos_token_id = output_vocab_size - 1
+ self.pad_token_id = output_vocab_size - 1
+
+ self.n_codes_total = n_codes_total
+ self.n_codes_given = n_codes_given
+
+ self.is_encoder_decoder = False
+
+ def prepare_config_and_inputs(self):
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
+
+ input_mask = None
+ if self.use_input_mask:
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
+
+ config = self.get_config()
+
+ head_mask = ids_tensor([self.num_hidden_layers, self.num_attention_heads], 2)
+
+ inputs_dict = {
+ "input_ids": input_ids,
+ "head_mask": head_mask,
+ "attention_mask": input_mask,
+ }
+
+ return config, inputs_dict
+
+ def get_config(self):
+ return BarkCoarseConfig(
+ vocab_size=self.vocab_size,
+ output_vocab_size=self.output_vocab_size,
+ hidden_size=self.hidden_size,
+ num_layers=self.num_hidden_layers,
+ num_heads=self.num_attention_heads,
+ use_cache=True,
+ bos_token_id=self.bos_token_id,
+ eos_token_id=self.eos_token_id,
+ pad_token_id=self.pad_token_id,
+ window_size=self.window_size,
+ )
+
+ def get_pipeline_config(self):
+ config = self.get_config()
+ config.vocab_size = 300
+ config.output_vocab_size = 300
+ return config
+
+ def prepare_config_and_inputs_for_common(self):
+ config, inputs_dict = self.prepare_config_and_inputs()
+ return config, inputs_dict
+
+ def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict):
+ model = BarkCoarseModel(config=config).to(torch_device).eval()
+
+ input_ids = inputs_dict["input_ids"]
+ attention_mask = inputs_dict["attention_mask"]
+
+ # first forward pass
+ outputs = model(input_ids, attention_mask=attention_mask, use_cache=True)
+
+ output, past_key_values = outputs.to_tuple()
+
+ # create hypothetical multiple next token and extent to next_input_ids
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
+ next_attn_mask = ids_tensor((self.batch_size, 3), 2)
+
+ # append to next input_ids and
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
+ next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1)
+
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["logits"]
+ output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[
+ "logits"
+ ]
+
+ # select random slice
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
+
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
+
+ # test that outputs are equal for slice
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
+
+ # test no attention_mask works
+ outputs = model(input_ids, use_cache=True)
+ _, past_key_values = outputs.to_tuple()
+ output_from_no_past = model(next_input_ids)["logits"]
+
+ output_from_past = model(next_tokens, past_key_values=past_key_values)["logits"]
+
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
+ # test that outputs are equal for slice
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
+
+
+class BarkFineModelTester:
+ def __init__(
+ self,
+ parent,
+ batch_size=3, # need batch_size != num_hidden_layers
+ seq_length=4,
+ is_training=False, # for now training is not supported
+ use_input_mask=True,
+ use_labels=True,
+ vocab_size=33,
+ output_vocab_size=33,
+ hidden_size=16,
+ num_hidden_layers=2,
+ num_attention_heads=2,
+ intermediate_size=15,
+ dropout=0.1,
+ window_size=256,
+ initializer_range=0.02,
+ n_codes_total=8, # for BarkFineModel
+ n_codes_given=1, # for BarkFineModel
+ ):
+ self.parent = parent
+ self.batch_size = batch_size
+ self.seq_length = seq_length
+ self.is_training = is_training
+ self.use_input_mask = use_input_mask
+ self.use_labels = use_labels
+ self.vocab_size = vocab_size
+ self.output_vocab_size = output_vocab_size
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.intermediate_size = intermediate_size
+ self.dropout = dropout
+ self.window_size = window_size
+ self.initializer_range = initializer_range
+ self.bos_token_id = output_vocab_size - 1
+ self.eos_token_id = output_vocab_size - 1
+ self.pad_token_id = output_vocab_size - 1
+
+ self.n_codes_total = n_codes_total
+ self.n_codes_given = n_codes_given
+
+ self.is_encoder_decoder = False
+
+ def prepare_config_and_inputs(self):
+ input_ids = ids_tensor([self.batch_size, self.seq_length, self.n_codes_total], self.vocab_size)
+
+ input_mask = None
+ if self.use_input_mask:
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
+
+ config = self.get_config()
+
+ head_mask = ids_tensor([self.num_hidden_layers, self.num_attention_heads], 2)
+
+ # randint between self.n_codes_given - 1 and self.n_codes_total - 1
+ codebook_idx = ids_tensor((1,), self.n_codes_total - self.n_codes_given).item() + self.n_codes_given
+
+ inputs_dict = {
+ "codebook_idx": codebook_idx,
+ "input_ids": input_ids,
+ "head_mask": head_mask,
+ "attention_mask": input_mask,
+ }
+
+ return config, inputs_dict
+
+ def get_config(self):
+ return BarkFineConfig(
+ vocab_size=self.vocab_size,
+ output_vocab_size=self.output_vocab_size,
+ hidden_size=self.hidden_size,
+ num_layers=self.num_hidden_layers,
+ num_heads=self.num_attention_heads,
+ use_cache=True,
+ bos_token_id=self.bos_token_id,
+ eos_token_id=self.eos_token_id,
+ pad_token_id=self.pad_token_id,
+ window_size=self.window_size,
+ )
+
+ def get_pipeline_config(self):
+ config = self.get_config()
+ config.vocab_size = 300
+ config.output_vocab_size = 300
+ return config
+
+ def prepare_config_and_inputs_for_common(self):
+ config, inputs_dict = self.prepare_config_and_inputs()
+ return config, inputs_dict
+
+ def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict):
+ model = BarkFineModel(config=config).to(torch_device).eval()
+
+ input_ids = inputs_dict["input_ids"]
+ attention_mask = inputs_dict["attention_mask"]
+
+ # first forward pass
+ outputs = model(input_ids, attention_mask=attention_mask, use_cache=True)
+
+ output, past_key_values = outputs.to_tuple()
+
+ # create hypothetical multiple next token and extent to next_input_ids
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
+ next_attn_mask = ids_tensor((self.batch_size, 3), 2)
+
+ # append to next input_ids and
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
+ next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1)
+
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["logits"]
+ output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[
+ "logits"
+ ]
+
+ # select random slice
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
+
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
+
+ # test that outputs are equal for slice
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
+
+ # test no attention_mask works
+ outputs = model(input_ids, use_cache=True)
+ _, past_key_values = outputs.to_tuple()
+ output_from_no_past = model(next_input_ids)["logits"]
+
+ output_from_past = model(next_tokens, past_key_values=past_key_values)["logits"]
+
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
+ # test that outputs are equal for slice
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
+
+
+class BarkModelTester:
+ def __init__(
+ self,
+ parent,
+ semantic_kwargs=None,
+ coarse_acoustics_kwargs=None,
+ fine_acoustics_kwargs=None,
+ codec_kwargs=None,
+ is_training=False, # for now training is not supported
+ ):
+ if semantic_kwargs is None:
+ semantic_kwargs = {}
+ if coarse_acoustics_kwargs is None:
+ coarse_acoustics_kwargs = {}
+ if fine_acoustics_kwargs is None:
+ fine_acoustics_kwargs = {}
+ if codec_kwargs is None:
+ codec_kwargs = {}
+
+ self.parent = parent
+ self.semantic_model_tester = BarkSemanticModelTester(parent, **semantic_kwargs)
+ self.coarse_acoustics_model_tester = BarkCoarseModelTester(parent, **coarse_acoustics_kwargs)
+ self.fine_acoustics_model_tester = BarkFineModelTester(parent, **fine_acoustics_kwargs)
+ self.codec_model_tester = EncodecModelTester(parent, **codec_kwargs)
+
+ self.is_training = is_training
+
+ def get_config(self):
+ return BarkConfig.from_sub_model_configs(
+ self.semantic_model_tester.get_config(),
+ self.coarse_acoustics_model_tester.get_config(),
+ self.fine_acoustics_model_tester.get_config(),
+ self.codec_model_tester.get_config(),
+ )
+
+ def get_pipeline_config(self):
+ config = self.get_config()
+
+ # follow the `get_pipeline_config` of the sub component models
+ config.semantic_config.vocab_size = 300
+ config.coarse_acoustics_config.vocab_size = 300
+ config.fine_acoustics_config.vocab_size = 300
+
+ config.semantic_config.output_vocab_size = 300
+ config.coarse_acoustics_config.output_vocab_size = 300
+ config.fine_acoustics_config.output_vocab_size = 300
+
+ return config
+
+
+@require_torch
+class BarkSemanticModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
+ all_model_classes = (BarkSemanticModel,) if is_torch_available() else ()
+ # `BarkSemanticModel` inherits from `BarkCausalModel`, but requires an advanced generation config.
+ # `BarkCausalModel` does not, so we run generation tests there.
+ all_generative_model_classes = (BarkCausalModel,) if is_torch_available() else ()
+
+ is_encoder_decoder = False
+ fx_compatible = False
+ test_missing_keys = False
+ test_pruning = False
+ test_model_parallel = False
+ # no model_parallel for now
+
+ test_resize_embeddings = True
+
+ def setUp(self):
+ self.model_tester = BarkSemanticModelTester(self)
+ self.config_tester = ConfigTester(self, config_class=BarkSemanticConfig, n_embd=37)
+
+ def test_config(self):
+ self.config_tester.run_common_tests()
+
+ def test_save_load_strict(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ model.save_pretrained(tmpdirname)
+ model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
+ self.assertEqual(info["missing_keys"], [])
+
+ def test_decoder_model_past_with_large_inputs(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
+
+ def test_inputs_embeds(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+ model.to(torch_device)
+ model.eval()
+
+ inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class))
+
+ input_ids = inputs["input_ids"]
+ del inputs["input_ids"]
+
+ wte = model.get_input_embeddings()
+ inputs["input_embeds"] = wte(input_ids)
+
+ with torch.no_grad():
+ model(**inputs)[0]
+
+ # override as the input arg is called "input_embeds", not "inputs_embeds"
+ def test_inputs_embeds_matches_input_ids(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+ model.to(torch_device)
+ model.eval()
+
+ inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class))
+ with torch.no_grad():
+ out_ids = model(**inputs)[0]
+
+ input_ids = inputs["input_ids"]
+ del inputs["input_ids"]
+
+ wte = model.get_input_embeddings()
+ inputs["input_embeds"] = wte(input_ids)
+ with torch.no_grad():
+ out_embeds = model(**inputs)[0]
+
+ torch.testing.assert_close(out_embeds, out_ids)
+
+ @require_torch_fp16
+ def test_generate_fp16(self):
+ config, input_dict = self.model_tester.prepare_config_and_inputs()
+ input_ids = input_dict["input_ids"]
+ attention_mask = input_ids.ne(1).to(torch_device)
+ model = self.all_generative_model_classes[0](config).eval().to(torch_device)
+ model.half()
+ model.generate(input_ids, attention_mask=attention_mask)
+ model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)
+
+
+@require_torch
+class BarkCoarseModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
+ all_model_classes = (BarkCoarseModel,) if is_torch_available() else ()
+ # `BarkCoarseModel` inherits from `BarkCausalModel`, but requires an advanced generation config.
+ # `BarkCausalModel` does not, so we run generation tests there.
+ all_generative_model_classes = (BarkCausalModel,) if is_torch_available() else ()
+
+ is_encoder_decoder = False
+ fx_compatible = False
+ test_missing_keys = False
+ test_pruning = False
+ test_model_parallel = False
+ # no model_parallel for now
+
+ test_resize_embeddings = True
+
+ def setUp(self):
+ self.model_tester = BarkCoarseModelTester(self)
+ self.config_tester = ConfigTester(self, config_class=BarkCoarseConfig, n_embd=37)
+
+ def test_config(self):
+ self.config_tester.run_common_tests()
+
+ def test_save_load_strict(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ model.save_pretrained(tmpdirname)
+ model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
+ self.assertEqual(info["missing_keys"], [])
+
+ def test_decoder_model_past_with_large_inputs(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
+
+ def test_inputs_embeds(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+ model.to(torch_device)
+ model.eval()
+
+ inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class))
+
+ input_ids = inputs["input_ids"]
+ del inputs["input_ids"]
+
+ wte = model.get_input_embeddings()
+ inputs["input_embeds"] = wte(input_ids)
+
+ with torch.no_grad():
+ model(**inputs)[0]
+
+ # override as the input arg is called "input_embeds", not "inputs_embeds"
+ def test_inputs_embeds_matches_input_ids(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+ model.to(torch_device)
+ model.eval()
+
+ inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class))
+ with torch.no_grad():
+ out_ids = model(**inputs)[0]
+
+ input_ids = inputs["input_ids"]
+ del inputs["input_ids"]
+
+ wte = model.get_input_embeddings()
+ inputs["input_embeds"] = wte(input_ids)
+ with torch.no_grad():
+ out_embeds = model(**inputs)[0]
+
+ torch.testing.assert_close(out_embeds, out_ids)
+
+ @require_torch_fp16
+ def test_generate_fp16(self):
+ config, input_dict = self.model_tester.prepare_config_and_inputs()
+ input_ids = input_dict["input_ids"]
+ attention_mask = input_ids.ne(1).to(torch_device)
+ model = self.all_generative_model_classes[0](config).eval().to(torch_device)
+ model.half()
+ model.generate(input_ids, attention_mask=attention_mask)
+ model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)
+
+
+@require_torch
+class BarkFineModelTest(ModelTesterMixin, unittest.TestCase):
+ all_model_classes = (BarkFineModel,) if is_torch_available() else ()
+
+ is_encoder_decoder = False
+ fx_compatible = False
+ test_missing_keys = False
+ test_pruning = False
+ # no model_parallel for now
+ test_model_parallel = False
+
+ # torchscript disabled for now because forward with an int
+ test_torchscript = False
+
+ test_resize_embeddings = True
+
+ def setUp(self):
+ self.model_tester = BarkFineModelTester(self)
+ self.config_tester = ConfigTester(self, config_class=BarkFineConfig, n_embd=37)
+
+ def test_config(self):
+ self.config_tester.run_common_tests()
+
+ def test_save_load_strict(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ model.save_pretrained(tmpdirname)
+ model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
+ self.assertEqual(info["missing_keys"], [])
+
+ def test_inputs_embeds(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+ model.to(torch_device)
+ model.eval()
+
+ inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class))
+
+ input_ids = inputs["input_ids"]
+ del inputs["input_ids"]
+
+ wte = model.get_input_embeddings()[inputs_dict["codebook_idx"]]
+
+ inputs["input_embeds"] = wte(input_ids[:, :, inputs_dict["codebook_idx"]])
+
+ with torch.no_grad():
+ model(**inputs)[0]
+
+ @unittest.skip(reason="FineModel relies on codebook idx and does not return same logits")
+ def test_inputs_embeds_matches_input_ids(self):
+ pass
+
+ @require_torch_fp16
+ def test_generate_fp16(self):
+ config, input_dict = self.model_tester.prepare_config_and_inputs()
+ input_ids = input_dict["input_ids"]
+ # take first codebook channel
+
+ model = self.all_model_classes[0](config).eval().to(torch_device)
+ model.half()
+
+ # toy generation_configs
+ semantic_generation_config = BarkSemanticGenerationConfig(semantic_vocab_size=0)
+ coarse_generation_config = BarkCoarseGenerationConfig(n_coarse_codebooks=config.n_codes_given)
+ fine_generation_config = BarkFineGenerationConfig(
+ max_fine_history_length=config.block_size // 2,
+ max_fine_input_length=config.block_size,
+ n_fine_codebooks=config.n_codes_total,
+ )
+ codebook_size = config.vocab_size - 1
+
+ model.generate(
+ input_ids,
+ history_prompt=None,
+ temperature=None,
+ semantic_generation_config=semantic_generation_config,
+ coarse_generation_config=coarse_generation_config,
+ fine_generation_config=fine_generation_config,
+ codebook_size=codebook_size,
+ )
+
+ model.generate(
+ input_ids,
+ history_prompt=None,
+ temperature=0.7,
+ semantic_generation_config=semantic_generation_config,
+ coarse_generation_config=coarse_generation_config,
+ fine_generation_config=fine_generation_config,
+ codebook_size=codebook_size,
+ )
+
+ def test_forward_signature(self):
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+ signature = inspect.signature(model.forward)
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
+ arg_names = [*signature.parameters.keys()]
+
+ expected_arg_names = ["codebook_idx", "input_ids"]
+ self.assertListEqual(arg_names[:2], expected_arg_names)
+
+ def test_model_get_set_embeddings(self):
+ # one embedding layer per codebook
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+ self.assertIsInstance(model.get_input_embeddings()[0], (torch.nn.Embedding))
+ model.set_input_embeddings(
+ torch.nn.ModuleList([torch.nn.Embedding(10, 10) for _ in range(config.n_codes_total)])
+ )
+ x = model.get_output_embeddings()
+ self.assertTrue(x is None or isinstance(x[0], torch.nn.Linear))
+
+ def test_resize_tokens_embeddings(self):
+ # resizing tokens_embeddings of a ModuleList
+ original_config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+ if not self.test_resize_embeddings:
+ self.skipTest(reason="test_resize_embeddings is False")
+
+ for model_class in self.all_model_classes:
+ config = copy.deepcopy(original_config)
+ model = model_class(config)
+ model.to(torch_device)
+
+ if self.model_tester.is_training is False:
+ model.eval()
+
+ model_vocab_size = config.vocab_size
+ # Retrieve the embeddings and clone theme
+ model_embed_list = model.resize_token_embeddings(model_vocab_size)
+ cloned_embeddings_list = [model_embed.weight.clone() for model_embed in model_embed_list]
+
+ # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size
+ model_embed_list = model.resize_token_embeddings(model_vocab_size + 10)
+ self.assertEqual(model.config.vocab_size, model_vocab_size + 10)
+
+ # Check that it actually resizes the embeddings matrix for each codebook
+ for model_embed, cloned_embeddings in zip(model_embed_list, cloned_embeddings_list):
+ self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] + 10)
+
+ # Check that the model can still do a forward pass successfully (every parameter should be resized)
+ model(**self._prepare_for_class(inputs_dict, model_class))
+
+ # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size
+ model_embed_list = model.resize_token_embeddings(model_vocab_size - 15)
+ self.assertEqual(model.config.vocab_size, model_vocab_size - 15)
+ for model_embed, cloned_embeddings in zip(model_embed_list, cloned_embeddings_list):
+ self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] - 15)
+
+ # Check that the model can still do a forward pass successfully (every parameter should be resized)
+ # Input ids should be clamped to the maximum size of the vocabulary
+ inputs_dict["input_ids"].clamp_(max=model_vocab_size - 15 - 1)
+
+ model(**self._prepare_for_class(inputs_dict, model_class))
+
+ # Check that adding and removing tokens has not modified the first part of the embedding matrix.
+ # only check for the first embedding matrix
+ models_equal = True
+ for p1, p2 in zip(cloned_embeddings_list[0], model_embed_list[0].weight):
+ if p1.data.ne(p2.data).sum() > 0:
+ models_equal = False
+
+ self.assertTrue(models_equal)
+
+ def test_resize_embeddings_untied(self):
+ # resizing tokens_embeddings of a ModuleList
+ original_config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+ if not self.test_resize_embeddings:
+ self.skipTest(reason="test_resize_embeddings is False")
+
+ original_config.tie_word_embeddings = False
+
+ for model_class in self.all_model_classes:
+ config = copy.deepcopy(original_config)
+ model = model_class(config).to(torch_device)
+
+ # if no output embeddings -> leave test
+ if model.get_output_embeddings() is None:
+ continue
+
+ # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size
+ model_vocab_size = config.vocab_size
+ model.resize_token_embeddings(model_vocab_size + 10)
+ self.assertEqual(model.config.vocab_size, model_vocab_size + 10)
+ output_embeds_list = model.get_output_embeddings()
+
+ for output_embeds in output_embeds_list:
+ self.assertEqual(output_embeds.weight.shape[0], model_vocab_size + 10)
+
+ # Check bias if present
+ if output_embeds.bias is not None:
+ self.assertEqual(output_embeds.bias.shape[0], model_vocab_size + 10)
+
+ # Check that the model can still do a forward pass successfully (every parameter should be resized)
+ model(**self._prepare_for_class(inputs_dict, model_class))
+
+ # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size
+ model.resize_token_embeddings(model_vocab_size - 15)
+ self.assertEqual(model.config.vocab_size, model_vocab_size - 15)
+ # Check that it actually resizes the embeddings matrix
+ output_embeds_list = model.get_output_embeddings()
+
+ for output_embeds in output_embeds_list:
+ self.assertEqual(output_embeds.weight.shape[0], model_vocab_size - 15)
+ # Check bias if present
+ if output_embeds.bias is not None:
+ self.assertEqual(output_embeds.bias.shape[0], model_vocab_size - 15)
+
+ # Check that the model can still do a forward pass successfully (every parameter should be resized)
+ # Input ids should be clamped to the maximum size of the vocabulary
+ inputs_dict["input_ids"].clamp_(max=model_vocab_size - 15 - 1)
+
+ # Check that the model can still do a forward pass successfully (every parameter should be resized)
+ model(**self._prepare_for_class(inputs_dict, model_class))
+
+ @require_flash_attn
+ @require_torch_gpu
+ @pytest.mark.flash_attn_test
+ @slow
+ def test_flash_attn_2_inference_equivalence(self):
+ for model_class in self.all_model_classes:
+ if not model_class._supports_flash_attn_2:
+ self.skipTest(reason="Model does not support flash_attention_2")
+
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+ model = model_class(config)
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ model.save_pretrained(tmpdirname)
+ model_fa = model_class.from_pretrained(
+ tmpdirname, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2"
+ )
+ model_fa.to(torch_device)
+
+ model = model_class.from_pretrained(tmpdirname, torch_dtype=torch.bfloat16)
+ model.to(torch_device)
+
+ dummy_input = inputs_dict["input_ids"][:1]
+ if dummy_input.dtype in [torch.float32, torch.float16]:
+ dummy_input = dummy_input.to(torch.bfloat16)
+
+ dummy_attention_mask = inputs_dict.get("attention_mask", None)
+
+ if dummy_attention_mask is not None:
+ dummy_attention_mask = dummy_attention_mask[:1]
+ dummy_attention_mask[:, 1:] = 1
+ dummy_attention_mask[:, :1] = 0
+
+ outputs = model(inputs_dict["codebook_idx"], dummy_input, output_hidden_states=True)
+ outputs_fa = model_fa(inputs_dict["codebook_idx"], dummy_input, output_hidden_states=True)
+
+ logits = outputs.hidden_states[-1]
+ logits_fa = outputs_fa.hidden_states[-1]
+
+ assert torch.allclose(logits_fa, logits, atol=4e-2, rtol=4e-2)
+
+ other_inputs = {"output_hidden_states": True}
+ if dummy_attention_mask is not None:
+ other_inputs["attention_mask"] = dummy_attention_mask
+
+ outputs = model(inputs_dict["codebook_idx"], dummy_input, **other_inputs)
+ outputs_fa = model_fa(inputs_dict["codebook_idx"], dummy_input, **other_inputs)
+
+ logits = outputs.hidden_states[-1]
+ logits_fa = outputs_fa.hidden_states[-1]
+
+ assert torch.allclose(logits_fa[1:], logits[1:], atol=4e-2, rtol=4e-2)
+
+ # check with inference + dropout
+ model.train()
+ _ = model_fa(inputs_dict["codebook_idx"], dummy_input, **other_inputs)
+
+ @require_flash_attn
+ @require_torch_gpu
+ @pytest.mark.flash_attn_test
+ @slow
+ def test_flash_attn_2_inference_equivalence_right_padding(self):
+ for model_class in self.all_model_classes:
+ if not model_class._supports_flash_attn_2:
+ self.skipTest(reason="Model does not support flash_attention_2")
+
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+ model = model_class(config)
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ model.save_pretrained(tmpdirname)
+ model_fa = model_class.from_pretrained(
+ tmpdirname, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2"
+ )
+ model_fa.to(torch_device)
+
+ model = model_class.from_pretrained(
+ tmpdirname,
+ torch_dtype=torch.bfloat16,
+ )
+ model.to(torch_device)
+
+ dummy_input = inputs_dict["input_ids"][:1]
+ if dummy_input.dtype in [torch.float32, torch.float16]:
+ dummy_input = dummy_input.to(torch.bfloat16)
+
+ dummy_attention_mask = inputs_dict.get("attention_mask", None)
+
+ if dummy_attention_mask is not None:
+ dummy_attention_mask = dummy_attention_mask[:1]
+ dummy_attention_mask[:, :-1] = 1
+ dummy_attention_mask[:, -1:] = 0
+
+ outputs = model(inputs_dict["codebook_idx"], dummy_input, output_hidden_states=True)
+ outputs_fa = model_fa(inputs_dict["codebook_idx"], dummy_input, output_hidden_states=True)
+
+ logits = outputs.hidden_states[-1]
+ logits_fa = outputs_fa.hidden_states[-1]
+
+ assert torch.allclose(logits_fa, logits, atol=4e-2, rtol=4e-2)
+
+ other_inputs = {
+ "output_hidden_states": True,
+ }
+ if dummy_attention_mask is not None:
+ other_inputs["attention_mask"] = dummy_attention_mask
+
+ outputs = model(inputs_dict["codebook_idx"], dummy_input, **other_inputs)
+ outputs_fa = model_fa(inputs_dict["codebook_idx"], dummy_input, **other_inputs)
+
+ logits = outputs.hidden_states[-1]
+ logits_fa = outputs_fa.hidden_states[-1]
+
+ assert torch.allclose(logits_fa[:-1], logits[:-1], atol=4e-2, rtol=4e-2)
+
+
+@require_torch
+class BarkModelIntegrationTests(unittest.TestCase):
+ @cached_property
+ def model(self):
+ return BarkModel.from_pretrained("suno/bark").to(torch_device)
+
+ @cached_property
+ def processor(self):
+ return BarkProcessor.from_pretrained("suno/bark")
+
+ @cached_property
+ def inputs(self):
+ input_ids = self.processor("In the light of the moon, a little egg lay on a leaf", voice_preset="en_speaker_6")
+
+ input_ids = input_ids.to(torch_device)
+
+ return input_ids
+
+ @cached_property
+ def semantic_generation_config(self):
+ semantic_generation_config = BarkSemanticGenerationConfig(**self.model.generation_config.semantic_config)
+ return semantic_generation_config
+
+ @cached_property
+ def coarse_generation_config(self):
+ coarse_generation_config = BarkCoarseGenerationConfig(**self.model.generation_config.coarse_acoustics_config)
+ return coarse_generation_config
+
+ @cached_property
+ def fine_generation_config(self):
+ fine_generation_config = BarkFineGenerationConfig(**self.model.generation_config.fine_acoustics_config)
+ return fine_generation_config
+
+ @slow
+ def test_generate_semantic(self):
+ input_ids = self.inputs
+
+ # check first ids
+ expected_output_ids = [7363, 321, 41, 1461, 6915, 952, 326, 41, 41, 927,] # fmt: skip
+
+ # greedy decoding
+ with torch.no_grad():
+ output_ids = self.model.semantic.generate(
+ **input_ids,
+ do_sample=False,
+ temperature=1.0,
+ semantic_generation_config=self.semantic_generation_config,
+ )
+ self.assertListEqual(output_ids[0, : len(expected_output_ids)].tolist(), expected_output_ids)
+
+ @slow
+ def test_generate_semantic_early_stop(self):
+ input_ids = self.inputs
+ min_eos_p = 0.01
+
+ # check first ids
+ expected_output_ids = [7363, 321, 41, 1461, 6915, 952, 326, 41, 41, 927,] # fmt: skip
+
+ # Should be able to read min_eos_p from kwargs
+ with torch.no_grad():
+ torch.manual_seed(0)
+ output_ids_without_min_eos_p = self.model.semantic.generate(
+ **input_ids,
+ do_sample=False,
+ temperature=0.9,
+ semantic_generation_config=self.semantic_generation_config,
+ )
+ torch.manual_seed(0)
+ output_ids_kwargs = self.model.semantic.generate(
+ **input_ids,
+ do_sample=False,
+ temperature=0.9,
+ semantic_generation_config=self.semantic_generation_config,
+ min_eos_p=min_eos_p,
+ )
+ self.assertListEqual(output_ids_without_min_eos_p[0, : len(expected_output_ids)].tolist(), expected_output_ids)
+ self.assertLess(len(output_ids_kwargs[0, :].tolist()), len(output_ids_without_min_eos_p[0, :].tolist()))
+
+ # Should be able to read min_eos_p from the semantic generation config
+ self.semantic_generation_config.min_eos_p = min_eos_p
+ with torch.no_grad():
+ torch.manual_seed(0)
+ output_ids = self.model.semantic.generate(
+ **input_ids,
+ do_sample=False,
+ temperature=0.9,
+ semantic_generation_config=self.semantic_generation_config,
+ )
+
+ self.assertEqual(output_ids.shape, output_ids_kwargs.shape)
+ self.assertLess(len(output_ids[0, :].tolist()), len(output_ids_without_min_eos_p[0, :].tolist()))
+ self.assertListEqual(output_ids[0, : len(expected_output_ids)].tolist(), expected_output_ids)
+
+ @slow
+ def test_generate_coarse(self):
+ input_ids = self.inputs
+
+ history_prompt = input_ids["history_prompt"]
+
+ # check first ids
+ expected_output_ids = [11018, 11391, 10651, 11418, 10857, 11620, 10642, 11366, 10312, 11528, 10531, 11516, 10474, 11051, 10524, 11051, ] # fmt: skip
+
+ with torch.no_grad():
+ output_ids = self.model.semantic.generate(
+ **input_ids,
+ do_sample=False,
+ temperature=1.0,
+ semantic_generation_config=self.semantic_generation_config,
+ )
+
+ output_ids = self.model.coarse_acoustics.generate(
+ output_ids,
+ history_prompt=history_prompt,
+ do_sample=False,
+ temperature=1.0,
+ semantic_generation_config=self.semantic_generation_config,
+ coarse_generation_config=self.coarse_generation_config,
+ codebook_size=self.model.generation_config.codebook_size,
+ )
+
+ self.assertListEqual(output_ids[0, : len(expected_output_ids)].tolist(), expected_output_ids)
+
+ @slow
+ def test_generate_fine(self):
+ input_ids = self.inputs
+
+ history_prompt = input_ids["history_prompt"]
+
+ # fmt: off
+ expected_output_ids = [
+ [1018, 651, 857, 642, 312, 531, 474, 524, 524, 776,],
+ [367, 394, 596, 342, 504, 492, 27, 27, 822, 822,],
+ [961, 955, 221, 955, 955, 686, 939, 939, 479, 176,],
+ [638, 365, 218, 944, 853, 363, 639, 22, 884, 456,],
+ [302, 912, 524, 38, 174, 209, 879, 23, 910, 227,],
+ [440, 673, 861, 666, 372, 558, 49, 172, 232, 342,],
+ [244, 358, 123, 356, 586, 520, 499, 877, 542, 637,],
+ [806, 685, 905, 848, 803, 810, 921, 208, 625, 203,],
+ ]
+ # fmt: on
+
+ with torch.no_grad():
+ output_ids = self.model.semantic.generate(
+ **input_ids,
+ do_sample=False,
+ temperature=1.0,
+ semantic_generation_config=self.semantic_generation_config,
+ )
+
+ output_ids = self.model.coarse_acoustics.generate(
+ output_ids,
+ history_prompt=history_prompt,
+ do_sample=False,
+ temperature=1.0,
+ semantic_generation_config=self.semantic_generation_config,
+ coarse_generation_config=self.coarse_generation_config,
+ codebook_size=self.model.generation_config.codebook_size,
+ )
+
+ # greedy decoding
+ output_ids = self.model.fine_acoustics.generate(
+ output_ids,
+ history_prompt=history_prompt,
+ temperature=None,
+ semantic_generation_config=self.semantic_generation_config,
+ coarse_generation_config=self.coarse_generation_config,
+ fine_generation_config=self.fine_generation_config,
+ codebook_size=self.model.generation_config.codebook_size,
+ )
+
+ self.assertListEqual(output_ids[0, :, : len(expected_output_ids[0])].tolist(), expected_output_ids)
+
+ @slow
+ def test_generate_end_to_end(self):
+ input_ids = self.inputs
+
+ with torch.no_grad():
+ self.model.generate(**input_ids)
+ self.model.generate(**{key: val for (key, val) in input_ids.items() if key != "history_prompt"})
+
+ @slow
+ def test_generate_end_to_end_with_args(self):
+ input_ids = self.inputs
+
+ with torch.no_grad():
+ self.model.generate(**input_ids, do_sample=True, temperature=0.6, penalty_alpha=0.6)
+ self.model.generate(**input_ids, do_sample=True, temperature=0.6, num_beams=4)
+
+ @slow
+ def test_generate_batching(self):
+ args = {"do_sample": False, "temperature": None}
+
+ s1 = "I love HuggingFace"
+ s2 = "In the light of the moon, a little egg lay on a leaf"
+ voice_preset = "en_speaker_6"
+ input_ids = self.processor([s1, s2], voice_preset=voice_preset).to(torch_device)
+
+ # generate in batch
+ outputs, audio_lengths = self.model.generate(**input_ids, **args, return_output_lengths=True)
+
+ # generate one-by-one
+ s1 = self.processor(s1, voice_preset=voice_preset).to(torch_device)
+ s2 = self.processor(s2, voice_preset=voice_preset).to(torch_device)
+ output1 = self.model.generate(**s1, **args)
+ output2 = self.model.generate(**s2, **args)
+
+ # up until the coarse acoustic model (included), results are the same
+ # the fine acoustic model introduces small differences
+ # first verify if same length (should be the same because it's decided in the coarse model)
+ self.assertEqual(tuple(audio_lengths), (output1.shape[1], output2.shape[1]))
+
+ # then assert almost equal
+ torch.testing.assert_close(outputs[0, : audio_lengths[0]], output1.squeeze(), rtol=2e-3, atol=2e-3)
+ torch.testing.assert_close(outputs[1, : audio_lengths[1]], output2.squeeze(), rtol=2e-3, atol=2e-3)
+
+ # now test single input with return_output_lengths = True
+ outputs, _ = self.model.generate(**s1, **args, return_output_lengths=True)
+ self.assertTrue((outputs == output1).all().item())
+
+ @slow
+ def test_generate_end_to_end_with_sub_models_args(self):
+ input_ids = self.inputs
+
+ with torch.no_grad():
+ torch.manual_seed(0)
+ self.model.generate(
+ **input_ids, do_sample=False, temperature=1.0, coarse_do_sample=True, coarse_temperature=0.7
+ )
+ output_ids_without_min_eos_p = self.model.generate(
+ **input_ids,
+ do_sample=True,
+ temperature=0.9,
+ coarse_do_sample=True,
+ coarse_temperature=0.7,
+ fine_temperature=0.3,
+ )
+
+ output_ids_with_min_eos_p = self.model.generate(
+ **input_ids,
+ do_sample=True,
+ temperature=0.9,
+ coarse_temperature=0.7,
+ fine_temperature=0.3,
+ min_eos_p=0.1,
+ )
+ self.assertLess(
+ len(output_ids_with_min_eos_p[0, :].tolist()), len(output_ids_without_min_eos_p[0, :].tolist())
+ )
+
+ @require_torch_gpu
+ @slow
+ def test_generate_end_to_end_with_offload(self):
+ input_ids = self.inputs
+
+ with torch.no_grad():
+ # standard generation
+ output_with_no_offload = self.model.generate(**input_ids, do_sample=False, temperature=1.0)
+
+ torch.cuda.empty_cache()
+
+ memory_before_offload = torch.cuda.memory_allocated()
+ model_memory_footprint = self.model.get_memory_footprint()
+
+ # activate cpu offload
+ self.model.enable_cpu_offload()
+
+ memory_after_offload = torch.cuda.memory_allocated()
+
+ # checks if the model have been offloaded
+
+ # CUDA memory usage after offload should be near 0, leaving room to small differences
+ room_for_difference = 1.1
+ self.assertGreater(
+ (memory_before_offload - model_memory_footprint) * room_for_difference, memory_after_offload
+ )
+
+ # checks if device is the correct one
+ self.assertEqual(self.model.device.type, torch_device)
+
+ # checks if hooks exist
+ self.assertTrue(hasattr(self.model.semantic, "_hf_hook"))
+
+ # output with cpu offload
+ output_with_offload = self.model.generate(**input_ids, do_sample=False, temperature=1.0)
+
+ # checks if same output
+ self.assertListAlmostEqual(output_with_no_offload.squeeze().tolist(), output_with_offload.squeeze().tolist())
+
+ def assertListAlmostEqual(self, list1, list2, tol=1e-6):
+ self.assertEqual(len(list1), len(list2))
+ for a, b in zip(list1, list2):
+ self.assertAlmostEqual(a, b, delta=tol)
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/bark/test_processor_bark.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/bark/test_processor_bark.py
new file mode 100644
index 0000000000000000000000000000000000000000..15b0871d81448dc13602c2614e7908736673acb0
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/bark/test_processor_bark.py
@@ -0,0 +1,127 @@
+# Copyright 2023 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 os
+import shutil
+import tempfile
+import unittest
+
+import numpy as np
+
+from transformers import AutoTokenizer, BarkProcessor
+from transformers.testing_utils import require_torch, slow
+
+
+@require_torch
+class BarkProcessorTest(unittest.TestCase):
+ def setUp(self):
+ self.checkpoint = "suno/bark-small"
+ self.tmpdirname = tempfile.mkdtemp()
+ self.voice_preset = "en_speaker_1"
+ self.input_string = "This is a test string"
+ self.speaker_embeddings_dict_path = "speaker_embeddings_path.json"
+ self.speaker_embeddings_directory = "speaker_embeddings"
+
+ def get_tokenizer(self, **kwargs):
+ return AutoTokenizer.from_pretrained(self.checkpoint, **kwargs)
+
+ def tearDown(self):
+ shutil.rmtree(self.tmpdirname)
+
+ def test_save_load_pretrained_default(self):
+ tokenizer = self.get_tokenizer()
+
+ processor = BarkProcessor(tokenizer=tokenizer)
+
+ processor.save_pretrained(self.tmpdirname)
+ processor = BarkProcessor.from_pretrained(self.tmpdirname)
+
+ self.assertEqual(processor.tokenizer.get_vocab(), tokenizer.get_vocab())
+
+ @slow
+ def test_save_load_pretrained_additional_features(self):
+ processor = BarkProcessor.from_pretrained(
+ pretrained_processor_name_or_path=self.checkpoint,
+ speaker_embeddings_dict_path=self.speaker_embeddings_dict_path,
+ )
+ processor.save_pretrained(
+ self.tmpdirname,
+ speaker_embeddings_dict_path=self.speaker_embeddings_dict_path,
+ speaker_embeddings_directory=self.speaker_embeddings_directory,
+ )
+
+ tokenizer_add_kwargs = self.get_tokenizer(bos_token="(BOS)", eos_token="(EOS)")
+
+ processor = BarkProcessor.from_pretrained(
+ self.tmpdirname,
+ self.speaker_embeddings_dict_path,
+ bos_token="(BOS)",
+ eos_token="(EOS)",
+ )
+
+ self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab())
+
+ def test_speaker_embeddings(self):
+ processor = BarkProcessor.from_pretrained(
+ pretrained_processor_name_or_path=self.checkpoint,
+ speaker_embeddings_dict_path=self.speaker_embeddings_dict_path,
+ )
+
+ seq_len = 35
+ nb_codebooks_coarse = 2
+ nb_codebooks_total = 8
+
+ voice_preset = {
+ "semantic_prompt": np.ones(seq_len),
+ "coarse_prompt": np.ones((nb_codebooks_coarse, seq_len)),
+ "fine_prompt": np.ones((nb_codebooks_total, seq_len)),
+ }
+
+ # test providing already loaded voice_preset
+ inputs = processor(text=self.input_string, voice_preset=voice_preset)
+
+ processed_voice_preset = inputs["history_prompt"]
+ for key in voice_preset:
+ self.assertListEqual(voice_preset[key].tolist(), processed_voice_preset.get(key, np.array([])).tolist())
+
+ # test loading voice preset from npz file
+ tmpfilename = os.path.join(self.tmpdirname, "file.npz")
+ np.savez(tmpfilename, **voice_preset)
+ inputs = processor(text=self.input_string, voice_preset=tmpfilename)
+ processed_voice_preset = inputs["history_prompt"]
+
+ for key in voice_preset:
+ self.assertListEqual(voice_preset[key].tolist(), processed_voice_preset.get(key, np.array([])).tolist())
+
+ # test loading voice preset from the hub
+ inputs = processor(text=self.input_string, voice_preset=self.voice_preset)
+
+ def test_tokenizer(self):
+ tokenizer = self.get_tokenizer()
+
+ processor = BarkProcessor(tokenizer=tokenizer)
+
+ encoded_processor = processor(text=self.input_string)
+
+ encoded_tok = tokenizer(
+ self.input_string,
+ padding="max_length",
+ max_length=256,
+ add_special_tokens=False,
+ return_attention_mask=True,
+ return_token_type_ids=False,
+ )
+
+ for key in encoded_tok.keys():
+ self.assertListEqual(encoded_tok[key], encoded_processor[key].squeeze().tolist())
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/bart/__init__.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/bart/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-441eeab80047/tests/source/tests/models/bart/test_modeling_bart.py b/tasks/tasksmith-441eeab80047/tests/source/tests/models/bart/test_modeling_bart.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6173de20e40b91c117020e78be26fc70fc65459
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/tests/source/tests/models/bart/test_modeling_bart.py
@@ -0,0 +1,1532 @@
+# coding=utf-8
+# Copyright 2021, 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.
+"""Testing suite for the PyTorch BART model."""
+
+import copy
+import tempfile
+import unittest
+
+import timeout_decorator # noqa
+
+from transformers import BartConfig, is_torch_available
+from transformers.testing_utils import (
+ require_sentencepiece,
+ require_tokenizers,
+ require_torch,
+ require_torch_fp16,
+ slow,
+ torch_device,
+)
+from transformers.utils import cached_property
+
+from ...generation.test_utils import GenerationTesterMixin
+from ...test_configuration_common import ConfigTester
+from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
+from ...test_pipeline_mixin import PipelineTesterMixin
+
+
+if is_torch_available():
+ import torch
+
+ from transformers import (
+ AutoModelForSequenceClassification,
+ BartForCausalLM,
+ BartForConditionalGeneration,
+ BartForQuestionAnswering,
+ BartForSequenceClassification,
+ BartModel,
+ BartTokenizer,
+ pipeline,
+ )
+ from transformers.models.bart.modeling_bart import BartDecoder, BartEncoder, shift_tokens_right
+
+
+def prepare_bart_inputs_dict(
+ config,
+ input_ids,
+ decoder_input_ids=None,
+ attention_mask=None,
+ decoder_attention_mask=None,
+ head_mask=None,
+ decoder_head_mask=None,
+ cross_attn_head_mask=None,
+):
+ if attention_mask is None:
+ attention_mask = input_ids.ne(config.pad_token_id)
+ if decoder_attention_mask is None:
+ decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id)
+ if head_mask is None:
+ head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads, device=torch_device)
+ if decoder_head_mask is None:
+ decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device)
+ if cross_attn_head_mask is None:
+ cross_attn_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device)
+ return {
+ "input_ids": input_ids,
+ "decoder_input_ids": decoder_input_ids,
+ "attention_mask": attention_mask,
+ "decoder_attention_mask": attention_mask,
+ "head_mask": head_mask,
+ "decoder_head_mask": decoder_head_mask,
+ "cross_attn_head_mask": cross_attn_head_mask,
+ }
+
+
+class BartModelTester:
+ def __init__(
+ self,
+ parent,
+ batch_size=13,
+ seq_length=7,
+ is_training=True,
+ use_labels=False,
+ vocab_size=99,
+ hidden_size=16,
+ num_hidden_layers=2,
+ num_attention_heads=4,
+ intermediate_size=4,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.1,
+ attention_probs_dropout_prob=0.1,
+ max_position_embeddings=20,
+ eos_token_id=2,
+ pad_token_id=1,
+ bos_token_id=0,
+ ):
+ self.parent = parent
+ self.batch_size = batch_size
+ self.seq_length = seq_length
+ self.is_training = is_training
+ self.use_labels = use_labels
+ self.vocab_size = vocab_size
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.intermediate_size = intermediate_size
+ self.hidden_act = hidden_act
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.max_position_embeddings = max_position_embeddings
+ self.eos_token_id = eos_token_id
+ self.pad_token_id = pad_token_id
+ self.bos_token_id = bos_token_id
+
+ def prepare_config_and_inputs(self):
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size).clamp(
+ 3,
+ )
+ input_ids[:, -1] = self.eos_token_id # Eos Token
+
+ decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
+
+ config = self.get_config()
+ inputs_dict = prepare_bart_inputs_dict(config, input_ids, decoder_input_ids)
+ return config, inputs_dict
+
+ def get_config(self):
+ return BartConfig(
+ vocab_size=self.vocab_size,
+ d_model=self.hidden_size,
+ encoder_layers=self.num_hidden_layers,
+ decoder_layers=self.num_hidden_layers,
+ encoder_attention_heads=self.num_attention_heads,
+ decoder_attention_heads=self.num_attention_heads,
+ encoder_ffn_dim=self.intermediate_size,
+ decoder_ffn_dim=self.intermediate_size,
+ dropout=self.hidden_dropout_prob,
+ attention_dropout=self.attention_probs_dropout_prob,
+ max_position_embeddings=self.max_position_embeddings,
+ eos_token_id=self.eos_token_id,
+ bos_token_id=self.bos_token_id,
+ pad_token_id=self.pad_token_id,
+ )
+
+ def get_pipeline_config(self):
+ config = self.get_config()
+ config.max_position_embeddings = 100
+ config.vocab_size = 300
+ return config
+
+ def prepare_config_and_inputs_for_common(self):
+ config, inputs_dict = self.prepare_config_and_inputs()
+ return config, inputs_dict
+
+ def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict):
+ model = BartModel(config=config).get_decoder().to(torch_device).eval()
+ input_ids = inputs_dict["input_ids"]
+ attention_mask = inputs_dict["attention_mask"]
+ head_mask = inputs_dict["head_mask"]
+
+ # first forward pass
+ outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True)
+
+ output, past_key_values = outputs.to_tuple()
+
+ # create hypothetical multiple next token and extent to next_input_ids
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
+ next_attn_mask = ids_tensor((self.batch_size, 3), 2)
+
+ # append to next input_ids and
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
+ next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1)
+
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"]
+ output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[
+ "last_hidden_state"
+ ]
+
+ # select random slice
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
+
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
+
+ # test that outputs are equal for slice
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
+
+ def check_encoder_decoder_model_standalone(self, config, inputs_dict):
+ model = BartModel(config=config).to(torch_device).eval()
+ outputs = model(**inputs_dict)
+
+ encoder_last_hidden_state = outputs.encoder_last_hidden_state
+ last_hidden_state = outputs.last_hidden_state
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ encoder = model.get_encoder()
+ encoder.save_pretrained(tmpdirname)
+ encoder = BartEncoder.from_pretrained(tmpdirname).to(torch_device)
+
+ encoder_last_hidden_state_2 = encoder(inputs_dict["input_ids"], attention_mask=inputs_dict["attention_mask"])[
+ 0
+ ]
+
+ self.parent.assertTrue((encoder_last_hidden_state_2 - encoder_last_hidden_state).abs().max().item() < 1e-3)
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ decoder = model.get_decoder()
+ decoder.save_pretrained(tmpdirname)
+ decoder = BartDecoder.from_pretrained(tmpdirname).to(torch_device)
+
+ last_hidden_state_2 = decoder(
+ input_ids=inputs_dict["decoder_input_ids"],
+ attention_mask=inputs_dict["decoder_attention_mask"],
+ encoder_hidden_states=encoder_last_hidden_state,
+ encoder_attention_mask=inputs_dict["attention_mask"],
+ )[0]
+
+ self.parent.assertTrue((last_hidden_state_2 - last_hidden_state).abs().max().item() < 1e-3)
+
+
+@require_torch
+class BartHeadTests(unittest.TestCase):
+ vocab_size = 99
+
+ def _get_config_and_data(self):
+ input_ids = torch.tensor(
+ [
+ [71, 82, 18, 33, 46, 91, 2],
+ [68, 34, 26, 58, 30, 82, 2],
+ [5, 97, 17, 39, 94, 40, 2],
+ [76, 83, 94, 25, 70, 78, 2],
+ [87, 59, 41, 35, 48, 66, 2],
+ [55, 13, 16, 58, 5, 2, 1], # note padding
+ [64, 27, 31, 51, 12, 75, 2],
+ [52, 64, 86, 17, 83, 39, 2],
+ [48, 61, 9, 24, 71, 82, 2],
+ [26, 1, 60, 48, 22, 13, 2],
+ [21, 5, 62, 28, 14, 76, 2],
+ [45, 98, 37, 86, 59, 48, 2],
+ [70, 70, 50, 9, 28, 0, 2],
+ ],
+ dtype=torch.long,
+ device=torch_device,
+ )
+
+ batch_size = input_ids.shape[0]
+ config = BartConfig(
+ vocab_size=self.vocab_size,
+ d_model=24,
+ encoder_layers=2,
+ decoder_layers=2,
+ encoder_attention_heads=2,
+ decoder_attention_heads=2,
+ encoder_ffn_dim=32,
+ decoder_ffn_dim=32,
+ max_position_embeddings=48,
+ eos_token_id=2,
+ pad_token_id=1,
+ bos_token_id=0,
+ )
+ return config, input_ids, batch_size
+
+ def test_sequence_classification_forward(self):
+ config, input_ids, batch_size = self._get_config_and_data()
+ labels = _long_tensor([2] * batch_size).to(torch_device)
+ model = BartForSequenceClassification(config)
+ model.to(torch_device)
+ outputs = model(input_ids=input_ids, decoder_input_ids=input_ids, labels=labels)
+ expected_shape = torch.Size((batch_size, config.num_labels))
+ self.assertEqual(outputs["logits"].shape, expected_shape)
+ self.assertIsInstance(outputs["loss"].item(), float)
+
+ def test_question_answering_forward(self):
+ config, input_ids, batch_size = self._get_config_and_data()
+ sequence_labels = ids_tensor([batch_size], 2).to(torch_device)
+ model = BartForQuestionAnswering(config)
+ model.to(torch_device)
+ outputs = model(
+ input_ids=input_ids,
+ start_positions=sequence_labels,
+ end_positions=sequence_labels,
+ )
+
+ self.assertEqual(outputs["start_logits"].shape, input_ids.shape)
+ self.assertEqual(outputs["end_logits"].shape, input_ids.shape)
+ self.assertIsInstance(outputs["loss"].item(), float)
+
+ @timeout_decorator.timeout(1)
+ def test_lm_forward(self):
+ config, input_ids, batch_size = self._get_config_and_data()
+ lm_labels = ids_tensor([batch_size, input_ids.shape[1]], self.vocab_size).to(torch_device)
+ lm_model = BartForConditionalGeneration(config)
+ lm_model.to(torch_device)
+ outputs = lm_model(input_ids=input_ids, labels=lm_labels)
+ expected_shape = (batch_size, input_ids.shape[1], config.vocab_size)
+ self.assertEqual(outputs["logits"].shape, expected_shape)
+ self.assertIsInstance(outputs["loss"].item(), float)
+
+ def test_lm_uneven_forward(self):
+ config = BartConfig(
+ vocab_size=self.vocab_size,
+ d_model=14,
+ encoder_layers=2,
+ decoder_layers=2,
+ encoder_attention_heads=2,
+ decoder_attention_heads=2,
+ encoder_ffn_dim=8,
+ decoder_ffn_dim=8,
+ max_position_embeddings=48,
+ )
+ lm_model = BartForConditionalGeneration(config).to(torch_device)
+ context = torch.tensor(
+ [[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]], device=torch_device, dtype=torch.long
+ )
+ summary = torch.tensor([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]], device=torch_device, dtype=torch.long)
+ outputs = lm_model(input_ids=context, decoder_input_ids=summary, labels=summary)
+ expected_shape = (*summary.shape, config.vocab_size)
+ self.assertEqual(outputs["logits"].shape, expected_shape)
+
+ def test_generate_beam_search(self):
+ input_ids = torch.tensor([[71, 82, 2], [68, 34, 2]], device=torch_device, dtype=torch.long)
+ config = BartConfig(
+ vocab_size=self.vocab_size,
+ d_model=24,
+ encoder_layers=2,
+ decoder_layers=2,
+ encoder_attention_heads=2,
+ decoder_attention_heads=2,
+ encoder_ffn_dim=32,
+ decoder_ffn_dim=32,
+ max_position_embeddings=48,
+ eos_token_id=2,
+ pad_token_id=1,
+ bos_token_id=0,
+ )
+ lm_model = BartForConditionalGeneration(config).to(torch_device)
+ lm_model.eval()
+
+ max_length = 5
+ generated_ids = lm_model.generate(
+ input_ids.clone(),
+ do_sample=True,
+ num_return_sequences=1,
+ num_beams=2,
+ no_repeat_ngram_size=3,
+ max_length=max_length,
+ )
+ self.assertEqual(generated_ids.shape, (input_ids.shape[0], max_length))
+
+ def test_shift_tokens_right(self):
+ input_ids = torch.tensor([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]], dtype=torch.long)
+ shifted = shift_tokens_right(input_ids, 1, 2)
+ n_pad_before = input_ids.eq(1).float().sum()
+ n_pad_after = shifted.eq(1).float().sum()
+ self.assertEqual(shifted.shape, input_ids.shape)
+ self.assertEqual(n_pad_after, n_pad_before - 1)
+ self.assertTrue(torch.eq(shifted[:, 0], 2).all())
+
+ @slow
+ def test_tokenization(self):
+ tokenizer = BartTokenizer.from_pretrained("facebook/bart-large")
+ examples = [" Hello world", " DomDramg"] # need leading spaces for equality
+ fairseq_results = [
+ torch.tensor([0, 20920, 232, 2]),
+ torch.tensor([0, 11349, 495, 4040, 571, 2]),
+ ]
+ for ex, desired_result in zip(examples, fairseq_results):
+ bart_toks = tokenizer.encode(ex, return_tensors="pt").squeeze()
+ assert_tensors_close(desired_result.long(), bart_toks, prefix=ex)
+
+ @require_torch_fp16
+ def test_generate_fp16(self):
+ config, input_ids, batch_size = self._get_config_and_data()
+ attention_mask = input_ids.ne(1).to(torch_device)
+ model = BartForConditionalGeneration(config).eval().to(torch_device)
+ model.half()
+ model.generate(input_ids, attention_mask=attention_mask)
+ model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)
+
+ def test_dummy_inputs(self):
+ config, *_ = self._get_config_and_data()
+ model = BartForConditionalGeneration(config).eval().to(torch_device)
+ model(**model.dummy_inputs)
+
+ def test_resize_tokens_embeddings_more(self):
+ config, input_ids, _ = self._get_config_and_data()
+
+ def _get_embs(m):
+ return (m.get_input_embeddings().weight.data.clone(), m.get_output_embeddings().weight.data.clone())
+
+ model = BartForConditionalGeneration(config).eval().to(torch_device)
+ input, output = _get_embs(model)
+ self.assertTrue(torch.eq(input, output).all())
+ new_vocab_size = 45
+ model.resize_token_embeddings(new_vocab_size)
+ input_new, output_new = _get_embs(model)
+ self.assertEqual(input_new.shape, (new_vocab_size, config.d_model))
+ self.assertEqual(output_new.shape, (new_vocab_size, config.d_model))
+ self.assertTrue(torch.eq(input_new, output_new).all())
+
+
+@require_torch
+class BartModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
+ all_model_classes = (
+ (BartModel, BartForConditionalGeneration, BartForSequenceClassification, BartForQuestionAnswering)
+ if is_torch_available()
+ else ()
+ )
+ pipeline_model_mapping = (
+ {
+ "feature-extraction": BartModel,
+ "fill-mask": BartForConditionalGeneration,
+ "question-answering": BartForQuestionAnswering,
+ "summarization": BartForConditionalGeneration,
+ "text-classification": BartForSequenceClassification,
+ "text-generation": BartForCausalLM,
+ "text2text-generation": BartForConditionalGeneration,
+ "translation": BartForConditionalGeneration,
+ "zero-shot": BartForSequenceClassification,
+ }
+ if is_torch_available()
+ else {}
+ )
+ is_encoder_decoder = True
+ fx_compatible = False # Fix me Michael
+ test_pruning = False
+
+ def setUp(self):
+ self.model_tester = BartModelTester(self)
+ self.config_tester = ConfigTester(self, config_class=BartConfig)
+
+ def test_config(self):
+ self.config_tester.run_common_tests()
+
+ def test_save_load_strict(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
+ for model_class in self.all_model_classes:
+ model = model_class(config)
+
+ with tempfile.TemporaryDirectory() as tmpdirname:
+ model.save_pretrained(tmpdirname)
+ model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
+ self.assertEqual(info["missing_keys"], [])
+
+ def test_decoder_model_past_with_large_inputs(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
+ self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
+
+ def test_encoder_decoder_model_standalone(self):
+ config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
+ self.model_tester.check_encoder_decoder_model_standalone(*config_and_inputs)
+
+ # BartForSequenceClassification does not support inputs_embeds
+ def test_inputs_embeds(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
+
+ for model_class in (BartModel, BartForConditionalGeneration, BartForQuestionAnswering):
+ model = model_class(config)
+ model.to(torch_device)
+ model.eval()
+
+ inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class))
+
+ if not self.is_encoder_decoder:
+ input_ids = inputs["input_ids"]
+ del inputs["input_ids"]
+ else:
+ encoder_input_ids = inputs["input_ids"]
+ decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids)
+ del inputs["input_ids"]
+ inputs.pop("decoder_input_ids", None)
+
+ wte = model.get_input_embeddings()
+ if not self.is_encoder_decoder:
+ inputs["inputs_embeds"] = wte(input_ids)
+ else:
+ inputs["inputs_embeds"] = wte(encoder_input_ids)
+ inputs["decoder_inputs_embeds"] = wte(decoder_input_ids)
+
+ with torch.no_grad():
+ model(**inputs)[0]
+
+ @require_torch_fp16
+ def test_generate_fp16(self):
+ config, input_dict = self.model_tester.prepare_config_and_inputs()
+ input_ids = input_dict["input_ids"]
+ attention_mask = input_ids.ne(1).to(torch_device)
+ model = BartForConditionalGeneration(config).eval().to(torch_device)
+ model.half()
+ model.generate(input_ids, attention_mask=attention_mask)
+ model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)
+
+ @unittest.skip(
+ reason="This architecture has tied weights by default and there is no way to remove it, check: https://github.com/huggingface/transformers/pull/31771#issuecomment-2210915245"
+ )
+ def test_load_save_without_tied_weights(self):
+ pass
+
+ def test_resize_embeddings_persists_embeddings_type(self):
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
+
+ config.scale_embedding = True
+ model = BartForConditionalGeneration(config)
+ old_type = type(model.model.decoder.embed_tokens)
+
+ model.resize_token_embeddings(new_num_tokens=config.vocab_size)
+
+ new_type = type(model.model.decoder.embed_tokens)
+ self.assertIs(old_type, new_type)
+
+
+def assert_tensors_close(a, b, atol=1e-12, prefix=""):
+ """If tensors have different shapes, different values or a and b are not both tensors, raise a nice Assertion error."""
+ if a is None and b is None:
+ return True
+ try:
+ if torch.allclose(a, b, atol=atol):
+ return True
+ raise
+ except Exception:
+ pct_different = (torch.gt((a - b).abs(), atol)).float().mean().item()
+ if a.numel() > 100:
+ msg = f"tensor values are {pct_different:.1%} percent different."
+ else:
+ msg = f"{a} != {b}"
+ if prefix:
+ msg = prefix + ": " + msg
+ raise AssertionError(msg)
+
+
+def _long_tensor(tok_lst):
+ return torch.tensor(tok_lst, dtype=torch.long, device=torch_device)
+
+
+@require_torch
+@slow
+class FastIntegrationTests(unittest.TestCase):
+ """These tests are useful for debugging since they operate on a model with 1 encoder layer and 1 decoder layer."""
+
+ @cached_property
+ def tok(self):
+ return BartTokenizer.from_pretrained("facebook/bart-large")
+
+ @cached_property
+ def xsum_1_1_model(self):
+ return BartForConditionalGeneration.from_pretrained("sshleifer/distilbart-xsum-1-1")
+
+ def test_xsum_1_1_generation(self):
+ hf = self.xsum_1_1_model
+ tok = self.tok
+ ARTICLE = (
+ "The Palestinian Authority officially became the 123rd member of the International Criminal Court on"
+ " Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories. The"
+ " formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is based."
+ " The Palestinians signed the ICC's founding Rome Statute in January, when they also accepted its"
+ ' jurisdiction over alleged crimes committed "in the occupied Palestinian territory, including East'
+ ' Jerusalem, since June 13, 2014." Later that month, the ICC opened a preliminary examination into the'
+ " situation in Palestinian territories, paving the way for possible war crimes investigations against"
+ " Israelis. As members of the court, Palestinians may be subject to counter-charges as well. Israel and"
+ " the United States, neither of which is an ICC member, opposed the Palestinians' efforts to join the"
+ " body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday's ceremony, said it was a"
+ ' move toward greater justice. "As Palestine formally becomes a State Party to the Rome Statute today, the'
+ ' world is also a step closer to ending a long era of impunity and injustice," he said, according to an'
+ ' ICC news release. "Indeed, today brings us closer to our shared goals of justice and peace." Judge'
+ " Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was just the first step for the"
+ ' Palestinians. "As the Rome Statute today enters into force for the State of Palestine, Palestine'
+ " acquires all the rights as well as responsibilities that come with being a State Party to the Statute."
+ ' These are substantive commitments, which cannot be taken lightly," she said. Rights group Human Rights'
+ ' Watch welcomed the development. "Governments seeking to penalize Palestine for joining the ICC should'
+ " immediately end their pressure, and countries that support universal acceptance of the court's treaty"
+ ' should speak out to welcome its membership," said Balkees Jarrah, international justice counsel for the'
+ " group. \"What's objectionable is the attempts to undermine international justice, not Palestine's"
+ ' decision to join a treaty to which over 100 countries around the world are members." In January, when'
+ " the preliminary ICC examination was opened, Israeli Prime Minister Benjamin Netanyahu described it as an"
+ ' outrage, saying the court was overstepping its boundaries. The United States also said it "strongly"'
+ " disagreed with the court's decision. \"As we have said repeatedly, we do not believe that Palestine is a"
+ ' state and therefore we do not believe that it is eligible to join the ICC," the State Department said in'
+ ' a statement. It urged the warring sides to resolve their differences through direct negotiations. "We'
+ ' will continue to oppose actions against Israel at the ICC as counterproductive to the cause of peace,"'
+ " it said. But the ICC begs to differ with the definition of a state for its purposes and refers to the"
+ ' territories as "Palestine." While a preliminary examination is not a formal investigation, it allows the'
+ " court to review evidence and determine whether to investigate suspects on both sides. Prosecutor Fatou"
+ ' Bensouda said her office would "conduct its analysis in full independence and impartiality." The war'
+ " between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The inquiry"
+ " will include alleged war crimes committed since June. The International Criminal Court was set up in"
+ " 2002 to prosecute genocide, crimes against humanity and war crimes."
+ )
+ EXPECTED = (
+ " The International Criminal Court (ICC) has announced that it has been announced by the International"
+ " Criminal court."
+ )
+
+ dct = tok(ARTICLE, return_tensors="pt")
+ generated_ids = hf.generate(**dct, num_beams=4)
+ result = tok.batch_decode(generated_ids, skip_special_tokens=True)[0]
+ assert EXPECTED == result
+
+ def test_xsum_1_1_batch_generation(self):
+ # test batch
+
+ batch = self.tok(
+ [
+ "The Palestinian Authority officially became the 123rd member of the International Criminal Court on"
+ " Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories."
+ " The formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is"
+ " based. The Palestinians signed the ICC's founding Rome Statute in January, when they also accepted"
+ ' its jurisdiction over alleged crimes committed "in the occupied Palestinian territory, including'
+ ' East Jerusalem, since June 13, 2014." Later that month, the ICC opened a preliminary examination'
+ " into the situation in Palestinian territories, paving the way for possible war crimes investigations"
+ " against Israelis. As members of the court, Palestinians may be subject to counter-charges as well."
+ " Israel and the United States, neither of which is an ICC member, opposed the Palestinians' efforts"
+ " to join the body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday's ceremony,"
+ ' said it was a move toward greater justice. "As Palestine formally becomes a State Party to the Rome'
+ ' Statute today, the world is also a step closer to ending a long era of impunity and injustice," he'
+ ' said, according to an ICC news release. "Indeed, today brings us closer to our shared goals of'
+ ' justice and peace." Judge Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was'
+ ' just the first step for the Palestinians. "As the Rome Statute today enters into force for the State'
+ " of Palestine, Palestine acquires all the rights as well as responsibilities that come with being a"
+ ' State Party to the Statute. These are substantive commitments, which cannot be taken lightly," she'
+ ' said. Rights group Human Rights Watch welcomed the development. "Governments seeking to penalize'
+ " Palestine for joining the ICC should immediately end their pressure, and countries that support"
+ " universal acceptance of the court's treaty should speak out to welcome its membership,\" said"
+ " Balkees Jarrah, international justice counsel for the group. \"What's objectionable is the attempts"
+ " to undermine international justice, not Palestine's decision to join a treaty to which over 100"
+ ' countries around the world are members." In January, when the preliminary ICC examination was'
+ " opened, Israeli Prime Minister Benjamin Netanyahu described it as an outrage, saying the court was"
+ ' overstepping its boundaries. The United States also said it "strongly" disagreed with the court\'s'
+ ' decision. "As we have said repeatedly, we do not believe that Palestine is a state and therefore we'
+ ' do not believe that it is eligible to join the ICC," the State Department said in a statement. It'
+ ' urged the warring sides to resolve their differences through direct negotiations. "We will continue'
+ ' to oppose actions against Israel at the ICC as counterproductive to the cause of peace," it said.'
+ " But the ICC begs to differ with the definition of a state for its purposes and refers to the"
+ ' territories as "Palestine." While a preliminary examination is not a formal investigation, it allows'
+ " the court to review evidence and determine whether to investigate suspects on both sides. Prosecutor"
+ ' Fatou Bensouda said her office would "conduct its analysis in full independence and impartiality."'
+ " The war between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The"
+ " inquiry will include alleged war crimes committed since June. The International Criminal Court was"
+ " set up in 2002 to prosecute genocide, crimes against humanity and war crimes.",
+ "The French prosecutor leading an investigation into the crash of Germanwings Flight 9525 insisted"
+ " Wednesday that he was not aware of any video footage from on board the plane. Marseille prosecutor"
+ ' Brice Robin told CNN that "so far no videos were used in the crash investigation." He added, "A'
+ " person who has such a video needs to immediately give it to the investigators.\" Robin's comments"
+ " follow claims by two magazines, German daily Bild and French Paris Match, of a cell phone video"
+ " showing the harrowing final seconds from on board Germanwings Flight 9525 as it crashed into the"
+ " French Alps. All 150 on board were killed. Paris Match and Bild reported that the video was"
+ " recovered from a phone at the wreckage site. The two publications described the supposed video, but"
+ " did not post it on their websites. The publications said that they watched the video, which was"
+ " found by a source close to the investigation. \"One can hear cries of 'My God' in several"
+ ' languages," Paris Match reported. "Metallic banging can also be heard more than three times, perhaps'
+ " of the pilot trying to open the cockpit door with a heavy object. Towards the end, after a heavy"
+ ' shake, stronger than the others, the screaming intensifies. Then nothing." "It is a very disturbing'
+ " scene,\" said Julian Reichelt, editor-in-chief of Bild online. An official with France's accident"
+ " investigation agency, the BEA, said the agency is not aware of any such video. Lt. Col. Jean-Marc"
+ " Menichini, a French Gendarmerie spokesman in charge of communications on rescue efforts around the"
+ ' Germanwings crash site, told CNN that the reports were "completely wrong" and "unwarranted." Cell'
+ ' phones have been collected at the site, he said, but that they "hadn\'t been exploited yet."'
+ " Menichini said he believed the cell phones would need to be sent to the Criminal Research Institute"
+ " in Rosny sous-Bois, near Paris, in order to be analyzed by specialized technicians working"
+ " hand-in-hand with investigators. But none of the cell phones found so far have been sent to the"
+ " institute, Menichini said. Asked whether staff involved in the search could have leaked a memory"
+ ' card to the media, Menichini answered with a categorical "no." Reichelt told "Erin Burnett:'
+ ' Outfront" that he had watched the video and stood by the report, saying Bild and Paris Match are'
+ ' "very confident" that the clip is real. He noted that investigators only revealed they\'d recovered'
+ ' cell phones from the crash site after Bild and Paris Match published their reports. "That is'
+ " something we did not know before. ... Overall we can say many things of the investigation weren't"
+ ' revealed by the investigation at the beginning," he said. What was mental state of Germanwings'
+ " co-pilot? German airline Lufthansa confirmed Tuesday that co-pilot Andreas Lubitz had battled"
+ " depression years before he took the controls of Germanwings Flight 9525, which he's accused of"
+ " deliberately crashing last week in the French Alps. Lubitz told his Lufthansa flight training school"
+ ' in 2009 that he had a "previous episode of severe depression," the airline said Tuesday. Email'
+ " correspondence between Lubitz and the school discovered in an internal investigation, Lufthansa"
+ " said, included medical documents he submitted in connection with resuming his flight training. The"
+ " announcement indicates that Lufthansa, the parent company of Germanwings, knew of Lubitz's battle"
+ " with depression, allowed him to continue training and ultimately put him in the cockpit. Lufthansa,"
+ " whose CEO Carsten Spohr previously said Lubitz was 100% fit to fly, described its statement Tuesday"
+ ' as a "swift and seamless clarification" and said it was sharing the information and documents --'
+ " including training and medical records -- with public prosecutors. Spohr traveled to the crash site"
+ " Wednesday, where recovery teams have been working for the past week to recover human remains and"
+ " plane debris scattered across a steep mountainside. He saw the crisis center set up in"
+ " Seyne-les-Alpes, laid a wreath in the village of Le Vernet, closer to the crash site, where grieving"
+ " families have left flowers at a simple stone memorial. Menichini told CNN late Tuesday that no"
+ " visible human remains were left at the site but recovery teams would keep searching. French"
+ " President Francois Hollande, speaking Tuesday, said that it should be possible to identify all the"
+ " victims using DNA analysis by the end of the week, sooner than authorities had previously suggested."
+ " In the meantime, the recovery of the victims' personal belongings will start Wednesday, Menichini"
+ " said. Among those personal belongings could be more cell phones belonging to the 144 passengers and"
+ " six crew on board. Check out the latest from our correspondents . The details about Lubitz's"
+ " correspondence with the flight school during his training were among several developments as"
+ " investigators continued to delve into what caused the crash and Lubitz's possible motive for"
+ " downing the jet. A Lufthansa spokesperson told CNN on Tuesday that Lubitz had a valid medical"
+ ' certificate, had passed all his examinations and "held all the licenses required." Earlier, a'
+ " spokesman for the prosecutor's office in Dusseldorf, Christoph Kumpa, said medical records reveal"
+ " Lubitz suffered from suicidal tendencies at some point before his aviation career and underwent"
+ " psychotherapy before he got his pilot's license. Kumpa emphasized there's no evidence suggesting"
+ " Lubitz was suicidal or acting aggressively before the crash. Investigators are looking into whether"
+ " Lubitz feared his medical condition would cause him to lose his pilot's license, a European"
+ ' government official briefed on the investigation told CNN on Tuesday. While flying was "a big part'
+ " of his life,\" the source said, it's only one theory being considered. Another source, a law"
+ " enforcement official briefed on the investigation, also told CNN that authorities believe the"
+ " primary motive for Lubitz to bring down the plane was that he feared he would not be allowed to fly"
+ " because of his medical problems. Lubitz's girlfriend told investigators he had seen an eye doctor"
+ " and a neuropsychologist, both of whom deemed him unfit to work recently and concluded he had"
+ " psychological issues, the European government official said. But no matter what details emerge about"
+ " his previous mental health struggles, there's more to the story, said Brian Russell, a forensic"
+ ' psychologist. "Psychology can explain why somebody would turn rage inward on themselves about the'
+ " fact that maybe they weren't going to keep doing their job and they're upset about that and so"
+ ' they\'re suicidal," he said. "But there is no mental illness that explains why somebody then feels'
+ " entitled to also take that rage and turn it outward on 149 other people who had nothing to do with"
+ " the person's problems.\" Germanwings crash compensation: What we know . Who was the captain of"
+ " Germanwings Flight 9525? CNN's Margot Haddad reported from Marseille and Pamela Brown from"
+ " Dusseldorf, while Laura Smith-Spark wrote from London. CNN's Frederik Pleitgen, Pamela Boykoff,"
+ " Antonia Mortensen, Sandrine Amiel and Anna-Maja Rappard contributed to this report.",
+ ],
+ return_tensors="pt",
+ padding="longest",
+ truncation=True,
+ )
+ generated_ids = self.xsum_1_1_model.generate(**batch, num_beams=4)
+ result = self.tok.batch_decode(generated_ids, skip_special_tokens=True)
+ assert (
+ result[0]
+ == " The International Criminal Court (ICC) has announced that it has been announced by the International"
+ " Criminal court."
+ )
+ assert (
+ result[1]
+ == " An investigation into the crash that killed at least 10 people in the French capital has been"
+ " released by the French police investigating the crash."
+ )
+
+ def test_encoder_equiv(self):
+ # test batch
+
+ batch = self.tok(
+ [
+ "The Palestinian Authority officially became the 123rd member of the International Criminal Court on"
+ " Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories."
+ " The formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is"
+ " based. The Palestinians signed the ICC's founding Rome Statute in January, when they also accepted"
+ ' its jurisdiction over alleged crimes committed "in the occupied Palestinian territory, including'
+ ' East Jerusalem, since June 13, 2014." Later that month, the ICC opened a preliminary examination'
+ " into the situation in Palestinian territories, paving the way for possible war crimes investigations"
+ " against Israelis. As members of the court, Palestinians may be subject to counter-charges as well."
+ " Israel and the United States, neither of which is an ICC member, opposed the Palestinians' efforts"
+ " to join the body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday's ceremony,"
+ ' said it was a move toward greater justice. "As Palestine formally becomes a State Party to the Rome'
+ ' Statute today, the world is also a step closer to ending a long era of impunity and injustice," he'
+ ' said, according to an ICC news release. "Indeed, today brings us closer to our shared goals of'
+ ' justice and peace." Judge Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was'
+ ' just the first step for the Palestinians. "As the Rome Statute today enters into force for the State'
+ " of Palestine, Palestine acquires all the rights as well as responsibilities that come with being a"
+ ' State Party to the Statute. These are substantive commitments, which cannot be taken lightly," she'
+ ' said. Rights group Human Rights Watch welcomed the development. "Governments seeking to penalize'
+ " Palestine for joining the ICC should immediately end their pressure, and countries that support"
+ " universal acceptance of the court's treaty should speak out to welcome its membership,\" said"
+ " Balkees Jarrah, international justice counsel for the group. \"What's objectionable is the attempts"
+ " to undermine international justice, not Palestine's decision to join a treaty to which over 100"
+ ' countries around the world are members." In January, when the preliminary ICC examination was'
+ " opened, Israeli Prime Minister Benjamin Netanyahu described it as an outrage, saying the court was"
+ ' overstepping its boundaries. The United States also said it "strongly" disagreed with the court\'s'
+ ' decision. "As we have said repeatedly, we do not believe that Palestine is a state and therefore we'
+ ' do not believe that it is eligible to join the ICC," the State Department said in a statement. It'
+ ' urged the warring sides to resolve their differences through direct negotiations. "We will continue'
+ ' to oppose actions against Israel at the ICC as counterproductive to the cause of peace," it said.'
+ " But the ICC begs to differ with the definition of a state for its purposes and refers to the"
+ ' territories as "Palestine." While a preliminary examination is not a formal investigation, it allows'
+ " the court to review evidence and determine whether to investigate suspects on both sides. Prosecutor"
+ ' Fatou Bensouda said her office would "conduct its analysis in full independence and impartiality."'
+ " The war between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The"
+ " inquiry will include alleged war crimes committed since June. The International Criminal Court was"
+ " set up in 2002 to prosecute genocide, crimes against humanity and war crimes.",
+ "The French prosecutor leading an investigation into the crash of Germanwings Flight 9525 insisted"
+ " Wednesday that he was not aware of any video footage from on board the plane. Marseille prosecutor"
+ ' Brice Robin told CNN that "so far no videos were used in the crash investigation." He added, "A'
+ " person who has such a video needs to immediately give it to the investigators.\" Robin's comments"
+ " follow claims by two magazines, German daily Bild and French Paris Match, of a cell phone video"
+ " showing the harrowing final seconds from on board Germanwings Flight 9525 as it crashed into the"
+ " French Alps. All 150 on board were killed. Paris Match and Bild reported that the video was"
+ " recovered from a phone at the wreckage site. The two publications described the supposed video, but"
+ " did not post it on their websites. The publications said that they watched the video, which was"
+ " found by a source close to the investigation. \"One can hear cries of 'My God' in several"
+ ' languages," Paris Match reported. "Metallic banging can also be heard more than three times, perhaps'
+ " of the pilot trying to open the cockpit door with a heavy object. Towards the end, after a heavy"
+ ' shake, stronger than the others, the screaming intensifies. Then nothing." "It is a very disturbing'
+ " scene,\" said Julian Reichelt, editor-in-chief of Bild online. An official with France's accident"
+ " investigation agency, the BEA, said the agency is not aware of any such video. Lt. Col. Jean-Marc"
+ " Menichini, a French Gendarmerie spokesman in charge of communications on rescue efforts around the"
+ ' Germanwings crash site, told CNN that the reports were "completely wrong" and "unwarranted." Cell'
+ ' phones have been collected at the site, he said, but that they "hadn\'t been exploited yet."'
+ " Menichini said he believed the cell phones would need to be sent to the Criminal Research Institute"
+ " in Rosny sous-Bois, near Paris, in order to be analyzed by specialized technicians working"
+ " hand-in-hand with investigators. But none of the cell phones found so far have been sent to the"
+ " institute, Menichini said. Asked whether staff involved in the search could have leaked a memory"
+ ' card to the media, Menichini answered with a categorical "no." Reichelt told "Erin Burnett:'
+ ' Outfront" that he had watched the video and stood by the report, saying Bild and Paris Match are'
+ ' "very confident" that the clip is real. He noted that investigators only revealed they\'d recovered'
+ ' cell phones from the crash site after Bild and Paris Match published their reports. "That is'
+ " something we did not know before. ... Overall we can say many things of the investigation weren't"
+ ' revealed by the investigation at the beginning," he said. What was mental state of Germanwings'
+ " co-pilot? German airline Lufthansa confirmed Tuesday that co-pilot Andreas Lubitz had battled"
+ " depression years before he took the controls of Germanwings Flight 9525, which he's accused of"
+ " deliberately crashing last week in the French Alps. Lubitz told his Lufthansa flight training school"
+ ' in 2009 that he had a "previous episode of severe depression," the airline said Tuesday. Email'
+ " correspondence between Lubitz and the school discovered in an internal investigation, Lufthansa"
+ " said, included medical documents he submitted in connection with resuming his flight training. The"
+ " announcement indicates that Lufthansa, the parent company of Germanwings, knew of Lubitz's battle"
+ " with depression, allowed him to continue training and ultimately put him in the cockpit. Lufthansa,"
+ " whose CEO Carsten Spohr previously said Lubitz was 100% fit to fly, described its statement Tuesday"
+ ' as a "swift and seamless clarification" and said it was sharing the information and documents --'
+ " including training and medical records -- with public prosecutors. Spohr traveled to the crash site"
+ " Wednesday, where recovery teams have been working for the past week to recover human remains and"
+ " plane debris scattered across a steep mountainside. He saw the crisis center set up in"
+ " Seyne-les-Alpes, laid a wreath in the village of Le Vernet, closer to the crash site, where grieving"
+ " families have left flowers at a simple stone memorial. Menichini told CNN late Tuesday that no"
+ " visible human remains were left at the site but recovery teams would keep searching. French"
+ " President Francois Hollande, speaking Tuesday, said that it should be possible to identify all the"
+ " victims using DNA analysis by the end of the week, sooner than authorities had previously suggested."
+ " In the meantime, the recovery of the victims' personal belongings will start Wednesday, Menichini"
+ " said. Among those personal belongings could be more cell phones belonging to the 144 passengers and"
+ " six crew on board. Check out the latest from our correspondents . The details about Lubitz's"
+ " correspondence with the flight school during his training were among several developments as"
+ " investigators continued to delve into what caused the crash and Lubitz's possible motive for"
+ " downing the jet. A Lufthansa spokesperson told CNN on Tuesday that Lubitz had a valid medical"
+ ' certificate, had passed all his examinations and "held all the licenses required." Earlier, a'
+ " spokesman for the prosecutor's office in Dusseldorf, Christoph Kumpa, said medical records reveal"
+ " Lubitz suffered from suicidal tendencies at some point before his aviation career and underwent"
+ " psychotherapy before he got his pilot's license. Kumpa emphasized there's no evidence suggesting"
+ " Lubitz was suicidal or acting aggressively before the crash. Investigators are looking into whether"
+ " Lubitz feared his medical condition would cause him to lose his pilot's license, a European"
+ ' government official briefed on the investigation told CNN on Tuesday. While flying was "a big part'
+ " of his life,\" the source said, it's only one theory being considered. Another source, a law"
+ " enforcement official briefed on the investigation, also told CNN that authorities believe the"
+ " primary motive for Lubitz to bring down the plane was that he feared he would not be allowed to fly"
+ " because of his medical problems. Lubitz's girlfriend told investigators he had seen an eye doctor"
+ " and a neuropsychologist, both of whom deemed him unfit to work recently and concluded he had"
+ " psychological issues, the European government official said. But no matter what details emerge about"
+ " his previous mental health struggles, there's more to the story, said Brian Russell, a forensic"
+ ' psychologist. "Psychology can explain why somebody would turn rage inward on themselves about the'
+ " fact that maybe they weren't going to keep doing their job and they're upset about that and so"
+ ' they\'re suicidal," he said. "But there is no mental illness that explains why somebody then feels'
+ " entitled to also take that rage and turn it outward on 149 other people who had nothing to do with"
+ " the person's problems.\" Germanwings crash compensation: What we know . Who was the captain of"
+ " Germanwings Flight 9525? CNN's Margot Haddad reported from Marseille and Pamela Brown from"
+ " Dusseldorf, while Laura Smith-Spark wrote from London. CNN's Frederik Pleitgen, Pamela Boykoff,"
+ " Antonia Mortensen, Sandrine Amiel and Anna-Maja Rappard contributed to this report.",
+ ],
+ return_tensors="pt",
+ padding="longest",
+ truncation=True,
+ )
+ features = self.xsum_1_1_model.get_encoder()(**batch).last_hidden_state
+ expected = [[-0.0828, -0.0251, -0.0674], [0.1277, 0.3311, -0.0255], [0.2613, -0.0840, -0.2763]]
+ assert_tensors_close(features[0, :3, :3], torch.tensor(expected), atol=1e-3)
+
+
+@require_torch
+@require_sentencepiece
+@require_tokenizers
+class BartModelIntegrationTests(unittest.TestCase):
+ @cached_property
+ def default_tokenizer(self):
+ return BartTokenizer.from_pretrained("facebook/bart-large")
+
+ @slow
+ def test_inference_no_head(self):
+ model = BartModel.from_pretrained("facebook/bart-large").to(torch_device)
+ input_ids = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
+ attention_mask = input_ids.ne(model.config.pad_token_id)
+ with torch.no_grad():
+ output = model(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state
+ expected_shape = torch.Size((1, 11, 1024))
+ self.assertEqual(output.shape, expected_shape)
+ expected_slice = torch.tensor(
+ [[[0.7144, 0.8143, -1.2813], [0.7144, 0.8143, -1.2813], [-0.0467, 2.5911, -2.1845]]], device=torch_device
+ )
+ torch.testing.assert_close(output[:, :3, :3], expected_slice, rtol=1e-3, atol=1e-3)
+
+ @slow
+ def test_base_mask_filling(self):
+ pbase = pipeline(task="fill-mask", model="facebook/bart-base")
+ src_text = [" I went to the ."]
+ results = [x["token_str"] for x in pbase(src_text)]
+ assert " bathroom" in results
+
+ @slow
+ def test_large_mask_filling(self):
+ plarge = pipeline(task="fill-mask", model="facebook/bart-large")
+ src_text = [" I went to the ."]
+ results = [x["token_str"] for x in plarge(src_text)]
+ expected_results = [" bathroom", " gym", " wrong", " movies", " hospital"]
+ self.assertListEqual(results, expected_results)
+
+ @slow
+ def test_mnli_inference(self):
+ example_b = [0, 31414, 232, 328, 740, 1140, 69, 46078, 1588, 2, 1]
+ input_ids = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2], example_b])
+
+ model = AutoModelForSequenceClassification.from_pretrained("facebook/bart-large-mnli").to(
+ torch_device
+ ) # eval called in from_pre
+ attention_mask = input_ids.ne(model.config.pad_token_id)
+ # Test that model hasn't changed
+ with torch.no_grad():
+ outputs = model(input_ids=input_ids, attention_mask=attention_mask)
+
+ batched_logits = outputs.logits
+ expected_shape = torch.Size((2, 3))
+ self.assertEqual(batched_logits.shape, expected_shape)
+ expected_slice = torch.tensor([[0.1907, 1.4342, -1.0289]], device=torch_device)
+ logits_arr = batched_logits[0].detach()
+
+ # Test that padding does not change results
+ input_ids_no_pad = _long_tensor([example_b[:-1]])
+ attention_mask_no_pad = input_ids_no_pad.ne(model.config.pad_token_id)
+
+ with torch.no_grad():
+ logits2 = model(input_ids=input_ids_no_pad, attention_mask=attention_mask_no_pad).logits.squeeze()
+ assert_tensors_close(batched_logits[1], logits2, atol=1e-3)
+ assert_tensors_close(expected_slice, logits_arr, atol=1e-3)
+
+ @slow
+ def test_xsum_summarization_same_as_fairseq(self):
+ model = BartForConditionalGeneration.from_pretrained("facebook/bart-large-xsum").to(torch_device)
+ tok = self.default_tokenizer
+
+ PGE_ARTICLE = """ 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."""
+
+ EXPECTED_SUMMARY = (
+ "California's largest power company has begun shutting off electricity to thousands of customers in the"
+ " state."
+ )
+ dct = tok.batch_encode_plus(
+ [PGE_ARTICLE],
+ max_length=1024,
+ padding="max_length",
+ truncation=True,
+ return_tensors="pt",
+ ).to(torch_device)
+
+ hypotheses_batch = model.generate(
+ input_ids=dct["input_ids"],
+ attention_mask=dct["attention_mask"],
+ num_beams=2,
+ max_length=62,
+ min_length=11,
+ length_penalty=1.0,
+ no_repeat_ngram_size=3,
+ early_stopping=True,
+ decoder_start_token_id=model.config.eos_token_id,
+ )
+
+ decoded = tok.batch_decode(
+ hypotheses_batch,
+ skip_special_tokens=True,
+ )
+ self.assertEqual(EXPECTED_SUMMARY, decoded[0])
+
+ def test_xsum_config_generation_params(self):
+ config = BartConfig.from_pretrained("facebook/bart-large-xsum")
+ expected_params = {"num_beams": 6, "do_sample": False, "early_stopping": True, "length_penalty": 1.0}
+ config_params = {k: getattr(config, k, "MISSING") for k, v in expected_params.items()}
+ self.assertDictEqual(expected_params, config_params)
+
+ @slow
+ def test_cnn_summarization_same_as_fairseq(self):
+ hf = BartForConditionalGeneration.from_pretrained("facebook/bart-large-cnn").to(torch_device)
+ tok = BartTokenizer.from_pretrained("facebook/bart-large")
+
+ FRANCE_ARTICLE = ( # @noq
+ " Marseille, France (CNN)The French prosecutor leading an investigation into the crash of Germanwings"
+ " Flight 9525 insisted Wednesday that he was not aware of any video footage from on board the plane."
+ ' Marseille prosecutor Brice Robin told CNN that "so far no videos were used in the crash investigation."'
+ ' He added, "A person who has such a video needs to immediately give it to the investigators." Robin\'s'
+ " comments follow claims by two magazines, German daily Bild and French Paris Match, of a cell phone video"
+ " showing the harrowing final seconds from on board Germanwings Flight 9525 as it crashed into the French"
+ " Alps. All 150 on board were killed. Paris Match and Bild reported that the video was recovered from a"
+ " phone at the wreckage site. The two publications described the supposed video, but did not post it on"
+ " their websites. The publications said that they watched the video, which was found by a source close to"
+ " the investigation. \"One can hear cries of 'My God' in several languages,\" Paris Match reported."
+ ' "Metallic banging can also be heard more than three times, perhaps of the pilot trying to open the'
+ " cockpit door with a heavy object. Towards the end, after a heavy shake, stronger than the others, the"
+ ' screaming intensifies. Then nothing." "It is a very disturbing scene," said Julian Reichelt,'
+ " editor-in-chief of Bild online. An official with France's accident investigation agency, the BEA, said"
+ " the agency is not aware of any such video. Lt. Col. Jean-Marc Menichini, a French Gendarmerie spokesman"
+ " in charge of communications on rescue efforts around the Germanwings crash site, told CNN that the"
+ ' reports were "completely wrong" and "unwarranted." Cell phones have been collected at the site, he said,'
+ ' but that they "hadn\'t been exploited yet." Menichini said he believed the cell phones would need to be'
+ " sent to the Criminal Research Institute in Rosny sous-Bois, near Paris, in order to be analyzed by"
+ " specialized technicians working hand-in-hand with investigators. But none of the cell phones found so"
+ " far have been sent to the institute, Menichini said. Asked whether staff involved in the search could"
+ ' have leaked a memory card to the media, Menichini answered with a categorical "no." Reichelt told "Erin'
+ ' Burnett: Outfront" that he had watched the video and stood by the report, saying Bild and Paris Match'
+ ' are "very confident" that the clip is real. He noted that investigators only revealed they\'d recovered'
+ ' cell phones from the crash site after Bild and Paris Match published their reports. "That is something'
+ " we did not know before. ... Overall we can say many things of the investigation weren't revealed by the"
+ ' investigation at the beginning," he said. What was mental state of Germanwings co-pilot? German airline'
+ " Lufthansa confirmed Tuesday that co-pilot Andreas Lubitz had battled depression years before he took the"
+ " controls of Germanwings Flight 9525, which he's accused of deliberately crashing last week in the"
+ ' French Alps. Lubitz told his Lufthansa flight training school in 2009 that he had a "previous episode of'
+ ' severe depression," the airline said Tuesday. Email correspondence between Lubitz and the school'
+ " discovered in an internal investigation, Lufthansa said, included medical documents he submitted in"
+ " connection with resuming his flight training. The announcement indicates that Lufthansa, the parent"
+ " company of Germanwings, knew of Lubitz's battle with depression, allowed him to continue training and"
+ " ultimately put him in the cockpit. Lufthansa, whose CEO Carsten Spohr previously said Lubitz was 100%"
+ ' fit to fly, described its statement Tuesday as a "swift and seamless clarification" and said it was'
+ " sharing the information and documents -- including training and medical records -- with public"
+ " prosecutors. Spohr traveled to the crash site Wednesday, where recovery teams have been working for the"
+ " past week to recover human remains and plane debris scattered across a steep mountainside. He saw the"
+ " crisis center set up in Seyne-les-Alpes, laid a wreath in the village of Le Vernet, closer to the crash"
+ " site, where grieving families have left flowers at a simple stone memorial. Menichini told CNN late"
+ " Tuesday that no visible human remains were left at the site but recovery teams would keep searching."
+ " French President Francois Hollande, speaking Tuesday, said that it should be possible to identify all"
+ " the victims using DNA analysis by the end of the week, sooner than authorities had previously suggested."
+ " In the meantime, the recovery of the victims' personal belongings will start Wednesday, Menichini said."
+ " Among those personal belongings could be more cell phones belonging to the 144 passengers and six crew"
+ " on board. Check out the latest from our correspondents . The details about Lubitz's correspondence with"
+ " the flight school during his training were among several developments as investigators continued to"
+ " delve into what caused the crash and Lubitz's possible motive for downing the jet. A Lufthansa"
+ " spokesperson told CNN on Tuesday that Lubitz had a valid medical certificate, had passed all his"
+ ' examinations and "held all the licenses required." Earlier, a spokesman for the prosecutor\'s office in'
+ " Dusseldorf, Christoph Kumpa, said medical records reveal Lubitz suffered from suicidal tendencies at"
+ " some point before his aviation career and underwent psychotherapy before he got his pilot's license."
+ " Kumpa emphasized there's no evidence suggesting Lubitz was suicidal or acting aggressively before the"
+ " crash. Investigators are looking into whether Lubitz feared his medical condition would cause him to"
+ " lose his pilot's license, a European government official briefed on the investigation told CNN on"
+ ' Tuesday. While flying was "a big part of his life," the source said, it\'s only one theory being'
+ " considered. Another source, a law enforcement official briefed on the investigation, also told CNN that"
+ " authorities believe the primary motive for Lubitz to bring down the plane was that he feared he would"
+ " not be allowed to fly because of his medical problems. Lubitz's girlfriend told investigators he had"
+ " seen an eye doctor and a neuropsychologist, both of whom deemed him unfit to work recently and concluded"
+ " he had psychological issues, the European government official said. But no matter what details emerge"
+ " about his previous mental health struggles, there's more to the story, said Brian Russell, a forensic"
+ ' psychologist. "Psychology can explain why somebody would turn rage inward on themselves about the fact'
+ " that maybe they weren't going to keep doing their job and they're upset about that and so they're"
+ ' suicidal," he said. "But there is no mental illness that explains why somebody then feels entitled to'
+ " also take that rage and turn it outward on 149 other people who had nothing to do with the person's"
+ ' problems." Germanwings crash compensation: What we know . Who was the captain of Germanwings Flight'
+ " 9525? CNN's Margot Haddad reported from Marseille and Pamela Brown from Dusseldorf, while Laura"
+ " Smith-Spark wrote from London. CNN's Frederik Pleitgen, Pamela Boykoff, Antonia Mortensen, Sandrine"
+ " Amiel and Anna-Maja Rappard contributed to this report."
+ )
+
+ SHORTER_ARTICLE = (
+ " (CNN)The Palestinian Authority officially became the 123rd member of the International Criminal Court on"
+ " Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories. The"
+ " formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is based."
+ " The Palestinians signed the ICC's founding Rome Statute in January, when they also accepted its"
+ ' jurisdiction over alleged crimes committed "in the occupied Palestinian territory, including East'
+ ' Jerusalem, since June 13, 2014." Later that month, the ICC opened a preliminary examination into the'
+ " situation in Palestinian territories, paving the way for possible war crimes investigations against"
+ " Israelis. As members of the court, Palestinians may be subject to counter-charges as well. Israel and"
+ " the United States, neither of which is an ICC member, opposed the Palestinians' efforts to join the"
+ " body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday's ceremony, said it was a"
+ ' move toward greater justice. "As Palestine formally becomes a State Party to the Rome Statute today, the'
+ ' world is also a step closer to ending a long era of impunity and injustice," he said, according to an'
+ ' ICC news release. "Indeed, today brings us closer to our shared goals of justice and peace." Judge'
+ " Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was just the first step for the"
+ ' Palestinians. "As the Rome Statute today enters into force for the State of Palestine, Palestine'
+ " acquires all the rights as well as responsibilities that come with being a State Party to the Statute."
+ ' These are substantive commitments, which cannot be taken lightly," she said. Rights group Human Rights'
+ ' Watch welcomed the development. "Governments seeking to penalize Palestine for joining the ICC should'
+ " immediately end their pressure, and countries that support universal acceptance of the court's treaty"
+ ' should speak out to welcome its membership," said Balkees Jarrah, international justice counsel for the'
+ " group. \"What's objectionable is the attempts to undermine international justice, not Palestine's"
+ ' decision to join a treaty to which over 100 countries around the world are members." In January, when'
+ " the preliminary ICC examination was opened, Israeli Prime Minister Benjamin Netanyahu described it as an"
+ ' outrage, saying the court was overstepping its boundaries. The United States also said it "strongly"'
+ " disagreed with the court's decision. \"As we have said repeatedly, we do not believe that Palestine is a"
+ ' state and therefore we do not believe that it is eligible to join the ICC," the State Department said in'
+ ' a statement. It urged the warring sides to resolve their differences through direct negotiations. "We'
+ ' will continue to oppose actions against Israel at the ICC as counterproductive to the cause of peace,"'
+ " it said. But the ICC begs to differ with the definition of a state for its purposes and refers to the"
+ ' territories as "Palestine." While a preliminary examination is not a formal investigation, it allows the'
+ " court to review evidence and determine whether to investigate suspects on both sides. Prosecutor Fatou"
+ ' Bensouda said her office would "conduct its analysis in full independence and impartiality." The war'
+ " between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The inquiry"
+ " will include alleged war crimes committed since June. The International Criminal Court was set up in"
+ " 2002 to prosecute genocide, crimes against humanity and war crimes. CNN's Vasco Cotovio, Kareem Khadder"
+ " and Faith Karimi contributed to this report."
+ )
+
+ # The below article tests that we don't add any hypotheses outside of the top n_beams
+ IRAN_ARTICLE = (
+ " (CNN)The United States and its negotiating partners reached a very strong framework agreement with Iran"
+ " in Lausanne, Switzerland, on Thursday that limits Iran's nuclear program in such a way as to effectively"
+ " block it from building a nuclear weapon. Expect pushback anyway, if the recent past is any harbinger."
+ " Just last month, in an attempt to head off such an agreement, House Speaker John Boehner invited Israeli"
+ " Prime Minister Benjamin Netanyahu to preemptively blast it before Congress, and 47 senators sent a"
+ " letter to the Iranian leadership warning them away from a deal. The debate that has already begun since"
+ " the announcement of the new framework will likely result in more heat than light. It will not be helped"
+ " by the gathering swirl of dubious assumptions and doubtful assertions. Let us address some of these: ."
+ " The most misleading assertion, despite universal rejection by experts, is that the negotiations'"
+ " objective at the outset was the total elimination of any nuclear program in Iran. That is the position"
+ " of Netanyahu and his acolytes in the U.S. Congress. But that is not and never was the objective. If it"
+ " had been, there would have been no Iranian team at the negotiating table. Rather, the objective has"
+ " always been to structure an agreement or series of agreements so that Iran could not covertly develop a"
+ " nuclear arsenal before the United States and its allies could respond. The new framework has exceeded"
+ " expectations in achieving that goal. It would reduce Iran's low-enriched uranium stockpile, cut by"
+ " two-thirds its number of installed centrifuges and implement a rigorous inspection regime. Another"
+ " dubious assumption of opponents is that the Iranian nuclear program is a covert weapons program. Despite"
+ " sharp accusations by some in the United States and its allies, Iran denies having such a program, and"
+ " U.S. intelligence contends that Iran has not yet made the decision to build a nuclear weapon. Iran's"
+ " continued cooperation with International Atomic Energy Agency inspections is further evidence on this"
+ " point, and we'll know even more about Iran's program in the coming months and years because of the deal."
+ " In fact, the inspections provisions that are part of this agreement are designed to protect against any"
+ " covert action by the Iranians. What's more, the rhetoric of some members of Congress has implied that"
+ " the negotiations have been between only the United States and Iran (i.e., the 47 senators' letter"
+ " warning that a deal might be killed by Congress or a future president). This of course is not the case."
+ " The talks were between Iran and the five permanent members of the U.N. Security Council (United States,"
+ " United Kingdom, France, China and Russia) plus Germany, dubbed the P5+1. While the United States has"
+ " played a leading role in the effort, it negotiated the terms alongside its partners. If the agreement"
+ " reached by the P5+1 is rejected by Congress, it could result in an unraveling of the sanctions on Iran"
+ " and threaten NATO cohesion in other areas. Another questionable assertion is that this agreement"
+ " contains a sunset clause, after which Iran will be free to do as it pleases. Again, this is not the"
+ " case. Some of the restrictions on Iran's nuclear activities, such as uranium enrichment, will be eased"
+ " or eliminated over time, as long as 15 years. But most importantly, the framework agreement includes"
+ " Iran's ratification of the Additional Protocol, which allows IAEA inspectors expanded access to nuclear"
+ " sites both declared and nondeclared. This provision will be permanent. It does not sunset. Thus, going"
+ " forward, if Iran decides to enrich uranium to weapons-grade levels, monitors will be able to detect such"
+ " a move in a matter of days and alert the U.N. Security Council. Many in Congress have said that the"
+ ' agreement should be a formal treaty requiring the Senate to "advise and consent." But the issue is not'
+ " suited for a treaty. Treaties impose equivalent obligations on all signatories. For example, the New"
+ " START treaty limits Russia and the United States to 1,550 deployed strategic warheads. But any agreement"
+ " with Iran will not be so balanced. The restrictions and obligations in the final framework agreement"
+ " will be imposed almost exclusively on Iran. The P5+1 are obligated only to ease and eventually remove"
+ " most but not all economic sanctions, which were imposed as leverage to gain this final deal. Finally"
+ " some insist that any agreement must address Iranian missile programs, human rights violations or support"
+ " for Hamas or Hezbollah. As important as these issues are, and they must indeed be addressed, they are"
+ " unrelated to the most important aim of a nuclear deal: preventing a nuclear Iran. To include them in"
+ " the negotiations would be a poison pill. This agreement should be judged on its merits and on how it"
+ " affects the security of our negotiating partners and allies, including Israel. Those judgments should be"
+ " fact-based, not based on questionable assertions or dubious assumptions."
+ )
+
+ ARTICLE_SUBWAY = (
+ " New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York. A"
+ " year later, she got married again in Westchester County, but to a different man and without divorcing"
+ " her first husband. Only 18 days after that marriage, she got hitched yet again. Then, Barrientos"
+ ' declared "I do" five more times, sometimes only within two weeks of each other. In 2010, she married'
+ " once more, this time in the Bronx. In an application for a marriage license, she stated it was her"
+ ' "first and only" marriage. Barrientos, now 39, is facing two criminal counts of "offering a false'
+ ' instrument for filing in the first degree," referring to her false statements on the 2010 marriage'
+ " license application, according to court documents. Prosecutors said the marriages were part of an"
+ " immigration scam. On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to"
+ " her attorney, Christopher Wright, who declined to comment further. After leaving court, Barrientos was"
+ " arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New"
+ " York subway through an emergency exit, said Detective Annette Markowski, a police spokeswoman. In total,"
+ " Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002. All"
+ " occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be"
+ " married to four men, and at one time, she was married to eight men at once, prosecutors say. Prosecutors"
+ " said the immigration scam involved some of her husbands, who filed for permanent residence status"
+ " shortly after the marriages. Any divorces happened only after such filings were approved. It was"
+ " unclear whether any of the men will be prosecuted. The case was referred to the Bronx District"
+ " Attorney's Office by Immigration and Customs Enforcement and the Department of Homeland Security's"
+ ' Investigation Division. Seven of the men are from so-called "red-flagged" countries, including Egypt,'
+ " Turkey, Georgia, Pakistan and Mali. Her eighth husband, Rashid Rajput, was deported in 2006 to his"
+ " native Pakistan after an investigation by the Joint Terrorism Task Force. If convicted, Barrientos faces"
+ " up to four years in prison. Her next court appearance is scheduled for May 18."
+ )
+
+ dct = tok.batch_encode_plus(
+ [FRANCE_ARTICLE, SHORTER_ARTICLE, IRAN_ARTICLE, ARTICLE_SUBWAY],
+ max_length=1024,
+ padding="max_length",
+ truncation_strategy="only_first",
+ truncation=True,
+ return_tensors="pt",
+ )
+
+ self.assertEqual(1024, dct["input_ids"].shape[1])
+ hypotheses_batch = hf.generate(
+ input_ids=dct["input_ids"].to(torch_device),
+ attention_mask=dct["attention_mask"].to(torch_device),
+ num_beams=2,
+ )
+ assert hypotheses_batch[:, 1].eq(0).all().item()
+
+ EXPECTED = [
+ "A French prosecutor says he is not aware of any video footage from on board the plane. Two German "
+ "magazines claim to have found a cell phone video showing the crash. The publications say they watched "
+ "the video, which was found by a source close to the investigation. All 150 on board Germanwings Flight "
+ "9525 were killed.",
+ "Palestinian Authority becomes 123rd member of the International Criminal Court. The move gives the court "
+ "jurisdiction over alleged crimes in Palestinian territories. Israel and the United States opposed the "
+ "Palestinians' efforts to join the body. But Palestinian Foreign Minister Riad al-Malki said it was a "
+ "move toward greater justice.",
+ "U.S. and its negotiating partners reached a strong framework agreement with Iran. Peter Bergen: The "
+ "debate that has already begun will likely result in more heat than light. He says critics have made "
+ "dubious assumptions and doubtful assertions. Bergen says the goal was to block Iran from building a "
+ "nuclear weapon.",
+ "Liana Barrientos, 39, has been married 10 times, sometimes within two weeks of each other. Prosecutors "
+ "say the marriages were part of an immigration scam. She pleaded not guilty at State Supreme Court in the "
+ "Bronx on Friday. If convicted, she faces up to four years in prison.",
+ ]
+
+ generated_summaries = tok.batch_decode(
+ hypotheses_batch.tolist(), clean_up_tokenization_spaces=True, skip_special_tokens=True
+ )
+ assert generated_summaries == EXPECTED
+
+ @slow
+ def test_contrastive_search_bart(self):
+ article = (
+ " New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York. A"
+ " year later, she got married again in Westchester County, but to a different man and without divorcing"
+ " her first husband. Only 18 days after that marriage, she got hitched yet again. Then, Barrientos"
+ ' declared "I do" five more times, sometimes only within two weeks of each other. In 2010, she married'
+ " once more, this time in the Bronx. In an application for a marriage license, she stated it was her"
+ ' "first and only" marriage. Barrientos, now 39, is facing two criminal counts of "offering a false'
+ ' instrument for filing in the first degree," referring to her false statements on the 2010 marriage'
+ " license application, according to court documents. Prosecutors said the marriages were part of an"
+ " immigration scam. On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to"
+ " her attorney, Christopher Wright, who declined to comment further. After leaving court, Barrientos was"
+ " arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New"
+ " York subway through an emergency exit, said Detective Annette Markowski, a police spokeswoman. In total,"
+ " Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002. All"
+ " occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be"
+ " married to four men, and at one time, she was married to eight men at once, prosecutors say. Prosecutors"
+ " said the immigration scam involved some of her husbands, who filed for permanent residence status"
+ " shortly after the marriages. Any divorces happened only after such filings were approved. It was"
+ " unclear whether any of the men will be prosecuted. The case was referred to the Bronx District"
+ " Attorney's Office by Immigration and Customs Enforcement and the Department of Homeland Security's"
+ ' Investigation Division. Seven of the men are from so-called "red-flagged" countries, including Egypt,'
+ " Turkey, Georgia, Pakistan and Mali. Her eighth husband, Rashid Rajput, was deported in 2006 to his"
+ " native Pakistan after an investigation by the Joint Terrorism Task Force. If convicted, Barrientos faces"
+ " up to four years in prison. Her next court appearance is scheduled for May 18."
+ )
+ bart_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")
+ bart_model = BartForConditionalGeneration.from_pretrained("facebook/bart-large-cnn").to(torch_device)
+ input_ids = bart_tokenizer(
+ article, add_special_tokens=False, truncation=True, max_length=512, return_tensors="pt"
+ ).input_ids.to(torch_device)
+
+ outputs = bart_model.generate(input_ids, penalty_alpha=0.5, top_k=5, max_length=64, num_beams=1)
+ generated_text = bart_tokenizer.batch_decode(outputs, skip_special_tokens=True)
+
+ self.assertListEqual(
+ generated_text,
+ [
+ "Liana Barrientos, 39, pleaded not guilty to charges related to false marriage statements. "
+ "Prosecutors say she married at least 10 times, sometimes within two weeks of each other. She is "
+ "accused of being part of an immigration scam to get permanent residency. If convicted, she faces up "
+ "to four years in"
+ ],
+ )
+
+ @slow
+ def test_decoder_attention_mask(self):
+ model = BartForConditionalGeneration.from_pretrained("facebook/bart-large", forced_bos_token_id=0).to(
+ torch_device
+ )
+ tokenizer = self.default_tokenizer
+ sentence = "UN Chief Says There Is No in Syria"
+ input_ids = tokenizer(sentence, return_tensors="pt").input_ids.to(torch_device)
+ padding_size = 3
+ decoder_input_ids = torch.tensor(
+ [
+ [model.config.decoder_start_token_id]
+ + padding_size * [model.config.pad_token_id]
+ + [model.config.bos_token_id]
+ ],
+ dtype=torch.long,
+ device=torch_device,
+ )
+ decoder_attention_mask = torch.where(decoder_input_ids == model.config.pad_token_id, 0, 1).to(torch_device)
+ generated_ids = model.generate(
+ input_ids=input_ids,
+ use_cache=False,
+ max_new_tokens=20,
+ decoder_input_ids=decoder_input_ids,
+ decoder_attention_mask=decoder_attention_mask,
+ )
+ generated_sentence = tokenizer.batch_decode(generated_ids)[0]
+ expected_sentence = "