diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/dependency_versions_check.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/dependency_versions_check.py
new file mode 100644
index 0000000000000000000000000000000000000000..82d07850847ec357f36ff51088ddec36aceff093
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/dependency_versions_check.py
@@ -0,0 +1,63 @@
+# 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 .dependency_versions_table import deps
+from .utils.versions import require_version, require_version_core
+
+
+# define which module versions we always want to check at run time
+# (usually the ones defined in `install_requires` in setup.py)
+#
+# order specific notes:
+# - tqdm must be checked before tokenizers
+
+pkgs_to_check_at_runtime = [
+ "python",
+ "tqdm",
+ "regex",
+ "requests",
+ "packaging",
+ "filelock",
+ "numpy",
+ "tokenizers",
+ "huggingface-hub",
+ "safetensors",
+ "accelerate",
+ "pyyaml",
+]
+
+for pkg in pkgs_to_check_at_runtime:
+ if pkg in deps:
+ if pkg == "tokenizers":
+ # must be loaded here, or else tqdm check may fail
+ from .utils import is_tokenizers_available
+
+ if not is_tokenizers_available():
+ continue # not required, check version only if installed
+ elif pkg == "accelerate":
+ # must be loaded here, or else tqdm check may fail
+ from .utils import is_accelerate_available
+
+ # Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of
+ # Transformers with PyTorch
+ if not is_accelerate_available():
+ continue # not required, check version only if installed
+
+ require_version_core(deps[pkg])
+ else:
+ raise ValueError(f"can't find {pkg} in {deps.keys()}, check dependency_versions_table.py")
+
+
+def dep_version_check(pkg, hint=None):
+ require_version(deps[pkg], hint)
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/dependency_versions_table.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/dependency_versions_table.py
new file mode 100644
index 0000000000000000000000000000000000000000..28ae4463667779b1980e202fa83e45facc597291
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/dependency_versions_table.py
@@ -0,0 +1,104 @@
+# THIS FILE HAS BEEN AUTOGENERATED. To update:
+# 1. modify the `_deps` dict in setup.py
+# 2. run `make deps_table_update``
+deps = {
+ "Pillow": "Pillow>=10.0.1,<=15.0",
+ "accelerate": "accelerate>=0.26.0",
+ "av": "av",
+ "beautifulsoup4": "beautifulsoup4",
+ "blobfile": "blobfile",
+ "codecarbon": "codecarbon>=2.8.1",
+ "cookiecutter": "cookiecutter==1.7.3",
+ "dataclasses": "dataclasses",
+ "datasets": "datasets!=2.5.0",
+ "deepspeed": "deepspeed>=0.9.3",
+ "diffusers": "diffusers",
+ "dill": "dill<0.3.5",
+ "evaluate": "evaluate>=0.2.0",
+ "faiss-cpu": "faiss-cpu",
+ "fastapi": "fastapi",
+ "filelock": "filelock",
+ "flax": "flax>=0.4.1,<=0.7.0",
+ "fsspec": "fsspec<2023.10.0",
+ "ftfy": "ftfy",
+ "fugashi": "fugashi>=1.0",
+ "GitPython": "GitPython<3.1.19",
+ "hf-doc-builder": "hf-doc-builder>=0.3.0",
+ "huggingface-hub": "huggingface-hub>=0.26.0,<1.0",
+ "importlib_metadata": "importlib_metadata",
+ "ipadic": "ipadic>=1.0.0,<2.0",
+ "isort": "isort>=5.5.4",
+ "jax": "jax>=0.4.1,<=0.4.13",
+ "jaxlib": "jaxlib>=0.4.1,<=0.4.13",
+ "jieba": "jieba",
+ "jinja2": "jinja2>=3.1.0",
+ "kenlm": "kenlm",
+ "keras": "keras>2.9,<2.16",
+ "keras-nlp": "keras-nlp>=0.3.1,<0.14.0",
+ "librosa": "librosa",
+ "natten": "natten>=0.14.6,<0.15.0",
+ "nltk": "nltk<=3.8.1",
+ "num2words": "num2words",
+ "numpy": "numpy>=1.17",
+ "onnxconverter-common": "onnxconverter-common",
+ "onnxruntime-tools": "onnxruntime-tools>=1.4.2",
+ "onnxruntime": "onnxruntime>=1.4.0",
+ "opencv-python": "opencv-python",
+ "optimum-benchmark": "optimum-benchmark>=0.3.0",
+ "optuna": "optuna",
+ "optax": "optax>=0.0.8,<=0.1.4",
+ "packaging": "packaging>=20.0",
+ "parameterized": "parameterized",
+ "phonemizer": "phonemizer",
+ "protobuf": "protobuf",
+ "psutil": "psutil",
+ "pyyaml": "pyyaml>=5.1",
+ "pydantic": "pydantic",
+ "pytest": "pytest>=7.2.0,<8.0.0",
+ "pytest-asyncio": "pytest-asyncio",
+ "pytest-timeout": "pytest-timeout",
+ "pytest-xdist": "pytest-xdist",
+ "pytest-order": "pytest-order",
+ "python": "python>=3.9.0",
+ "ray[tune]": "ray[tune]>=2.7.0",
+ "regex": "regex!=2019.12.17",
+ "requests": "requests",
+ "rhoknp": "rhoknp>=1.1.0,<1.3.1",
+ "rjieba": "rjieba",
+ "rouge-score": "rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1",
+ "ruff": "ruff==0.5.1",
+ "sacrebleu": "sacrebleu>=1.4.12,<2.0.0",
+ "sacremoses": "sacremoses",
+ "safetensors": "safetensors>=0.4.1",
+ "sagemaker": "sagemaker>=2.31.0",
+ "schedulefree": "schedulefree>=1.2.6",
+ "scikit-learn": "scikit-learn",
+ "scipy": "scipy<1.13.0",
+ "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92",
+ "sigopt": "sigopt",
+ "starlette": "starlette",
+ "sudachipy": "sudachipy>=0.6.6",
+ "sudachidict_core": "sudachidict_core>=20220729",
+ "tensorboard": "tensorboard",
+ "tensorflow-cpu": "tensorflow-cpu>2.9,<2.16",
+ "tensorflow": "tensorflow>2.9,<2.16",
+ "tensorflow-text": "tensorflow-text<2.16",
+ "tensorflow-probability": "tensorflow-probability<0.24",
+ "tf2onnx": "tf2onnx",
+ "timeout-decorator": "timeout-decorator",
+ "tiktoken": "tiktoken",
+ "timm": "timm<=1.0.11",
+ "tokenizers": "tokenizers>=0.21,<0.22",
+ "torch": "torch>=2.0",
+ "torchaudio": "torchaudio",
+ "torchvision": "torchvision",
+ "pyctcdecode": "pyctcdecode>=0.4.0",
+ "tqdm": "tqdm>=4.27",
+ "unidic": "unidic>=1.0.2",
+ "unidic_lite": "unidic_lite>=1.0.7",
+ "urllib3": "urllib3<2.0.0",
+ "uvicorn": "uvicorn",
+ "pytest-rich": "pytest-rich",
+ "libcst": "libcst",
+ "rich": "rich",
+}
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/dynamic_module_utils.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/dynamic_module_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf44d4b427cf7b7bf76e1c550fa08b3dbc56b673
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/dynamic_module_utils.py
@@ -0,0 +1,685 @@
+# 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.
+"""Utilities to dynamically load objects from the Hub."""
+
+import filecmp
+import hashlib
+import importlib
+import importlib.util
+import os
+import re
+import shutil
+import signal
+import sys
+import threading
+import typing
+import warnings
+from pathlib import Path
+from types import ModuleType
+from typing import Any, Dict, List, Optional, Union
+
+from huggingface_hub import try_to_load_from_cache
+
+from .utils import (
+ HF_MODULES_CACHE,
+ TRANSFORMERS_DYNAMIC_MODULE_NAME,
+ cached_file,
+ extract_commit_hash,
+ is_offline_mode,
+ logging,
+)
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+_HF_REMOTE_CODE_LOCK = threading.Lock()
+
+
+def init_hf_modules():
+ """
+ Creates the cache directory for modules with an init, and adds it to the Python path.
+ """
+ # This function has already been executed if HF_MODULES_CACHE already is in the Python path.
+ if HF_MODULES_CACHE in sys.path:
+ return
+
+ sys.path.append(HF_MODULES_CACHE)
+ os.makedirs(HF_MODULES_CACHE, exist_ok=True)
+ init_path = Path(HF_MODULES_CACHE) / "__init__.py"
+ if not init_path.exists():
+ init_path.touch()
+ importlib.invalidate_caches()
+
+
+def create_dynamic_module(name: Union[str, os.PathLike]) -> None:
+ """
+ Creates a dynamic module in the cache directory for modules.
+
+ Args:
+ name (`str` or `os.PathLike`):
+ The name of the dynamic module to create.
+ """
+ init_hf_modules()
+ dynamic_module_path = (Path(HF_MODULES_CACHE) / name).resolve()
+ # If the parent module does not exist yet, recursively create it.
+ if not dynamic_module_path.parent.exists():
+ create_dynamic_module(dynamic_module_path.parent)
+ os.makedirs(dynamic_module_path, exist_ok=True)
+ init_path = dynamic_module_path / "__init__.py"
+ if not init_path.exists():
+ init_path.touch()
+ # It is extremely important to invalidate the cache when we change stuff in those modules, or users end up
+ # with errors about module that do not exist. Same for all other `invalidate_caches` in this file.
+ importlib.invalidate_caches()
+
+
+def get_relative_imports(module_file: Union[str, os.PathLike]) -> List[str]:
+ """
+ Get the list of modules that are relatively imported in a module file.
+
+ Args:
+ module_file (`str` or `os.PathLike`): The module file to inspect.
+
+ Returns:
+ `List[str]`: The list of relative imports in the module.
+ """
+ with open(module_file, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # Imports of the form `import .xxx`
+ relative_imports = re.findall(r"^\s*import\s+\.(\S+)\s*$", content, flags=re.MULTILINE)
+ # Imports of the form `from .xxx import yyy`
+ relative_imports += re.findall(r"^\s*from\s+\.(\S+)\s+import", content, flags=re.MULTILINE)
+ # Unique-ify
+ return list(set(relative_imports))
+
+
+def get_relative_import_files(module_file: Union[str, os.PathLike]) -> List[str]:
+ """
+ Get the list of all files that are needed for a given module. Note that this function recurses through the relative
+ imports (if a imports b and b imports c, it will return module files for b and c).
+
+ Args:
+ module_file (`str` or `os.PathLike`): The module file to inspect.
+
+ Returns:
+ `List[str]`: The list of all relative imports a given module needs (recursively), which will give us the list
+ of module files a given module needs.
+ """
+ no_change = False
+ files_to_check = [module_file]
+ all_relative_imports = []
+
+ # Let's recurse through all relative imports
+ while not no_change:
+ new_imports = []
+ for f in files_to_check:
+ new_imports.extend(get_relative_imports(f))
+
+ module_path = Path(module_file).parent
+ new_import_files = [str(module_path / m) for m in new_imports]
+ new_import_files = [f for f in new_import_files if f not in all_relative_imports]
+ files_to_check = [f"{f}.py" for f in new_import_files]
+
+ no_change = len(new_import_files) == 0
+ all_relative_imports.extend(files_to_check)
+
+ return all_relative_imports
+
+
+def get_imports(filename: Union[str, os.PathLike]) -> List[str]:
+ """
+ Extracts all the libraries (not relative imports this time) that are imported in a file.
+
+ Args:
+ filename (`str` or `os.PathLike`): The module file to inspect.
+
+ Returns:
+ `List[str]`: The list of all packages required to use the input module.
+ """
+ with open(filename, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ # filter out try/except block so in custom code we can have try/except imports
+ content = re.sub(r"\s*try\s*:.*?except.*?:", "", content, flags=re.DOTALL)
+
+ # filter out imports under is_flash_attn_2_available block for avoid import issues in cpu only environment
+ content = re.sub(
+ r"if is_flash_attn[a-zA-Z0-9_]+available\(\):\s*(from flash_attn\s*.*\s*)+", "", content, flags=re.MULTILINE
+ )
+
+ # Imports of the form `import xxx`
+ imports = re.findall(r"^\s*import\s+(\S+)\s*$", content, flags=re.MULTILINE)
+ # Imports of the form `from xxx import yyy`
+ imports += re.findall(r"^\s*from\s+(\S+)\s+import", content, flags=re.MULTILINE)
+ # Only keep the top-level module
+ imports = [imp.split(".")[0] for imp in imports if not imp.startswith(".")]
+ return list(set(imports))
+
+
+def check_imports(filename: Union[str, os.PathLike]) -> List[str]:
+ """
+ Check if the current Python environment contains all the libraries that are imported in a file. Will raise if a
+ library is missing.
+
+ Args:
+ filename (`str` or `os.PathLike`): The module file to check.
+
+ Returns:
+ `List[str]`: The list of relative imports in the file.
+ """
+ imports = get_imports(filename)
+ missing_packages = []
+ for imp in imports:
+ try:
+ importlib.import_module(imp)
+ except ImportError as exception:
+ logger.warning(f"Encountered exception while importing {imp}: {exception}")
+ # Some packages can fail with an ImportError because of a dependency issue.
+ # This check avoids hiding such errors.
+ # See https://github.com/huggingface/transformers/issues/33604
+ if "No module named" in str(exception):
+ missing_packages.append(imp)
+ else:
+ raise
+
+ if len(missing_packages) > 0:
+ raise ImportError(
+ "This modeling file requires the following packages that were not found in your environment: "
+ f"{', '.join(missing_packages)}. Run `pip install {' '.join(missing_packages)}`"
+ )
+
+ return get_relative_imports(filename)
+
+
+def get_class_in_module(
+ class_name: str,
+ module_path: Union[str, os.PathLike],
+ *,
+ force_reload: bool = False,
+) -> typing.Type:
+ """
+ Import a module on the cache directory for modules and extract a class from it.
+
+ Args:
+ class_name (`str`): The name of the class to import.
+ module_path (`str` or `os.PathLike`): The path to the module to import.
+ force_reload (`bool`, *optional*, defaults to `False`):
+ Whether to reload the dynamic module from file if it already exists in `sys.modules`.
+ Otherwise, the module is only reloaded if the file has changed.
+
+ Returns:
+ `typing.Type`: The class looked for.
+ """
+ name = os.path.normpath(module_path)
+ if name.endswith(".py"):
+ name = name[:-3]
+ name = name.replace(os.path.sep, ".")
+ module_file: Path = Path(HF_MODULES_CACHE) / module_path
+ with _HF_REMOTE_CODE_LOCK:
+ if force_reload:
+ sys.modules.pop(name, None)
+ importlib.invalidate_caches()
+ cached_module: Optional[ModuleType] = sys.modules.get(name)
+ module_spec = importlib.util.spec_from_file_location(name, location=module_file)
+
+ # Hash the module file and all its relative imports to check if we need to reload it
+ module_files: List[Path] = [module_file] + sorted(map(Path, get_relative_import_files(module_file)))
+ module_hash: str = hashlib.sha256(b"".join(bytes(f) + f.read_bytes() for f in module_files)).hexdigest()
+
+ module: ModuleType
+ if cached_module is None:
+ module = importlib.util.module_from_spec(module_spec)
+ # insert it into sys.modules before any loading begins
+ sys.modules[name] = module
+ else:
+ module = cached_module
+ # reload in both cases, unless the module is already imported and the hash hits
+ if getattr(module, "__transformers_module_hash__", "") != module_hash:
+ module_spec.loader.exec_module(module)
+ module.__transformers_module_hash__ = module_hash
+ return getattr(module, class_name)
+
+
+def get_cached_module_file(
+ pretrained_model_name_or_path: Union[str, os.PathLike],
+ module_file: 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,
+ repo_type: Optional[str] = None,
+ _commit_hash: Optional[str] = None,
+ **deprecated_kwargs,
+) -> str:
+ """
+ Prepares Downloads a module from a local folder or a distant repo and returns its path inside the cached
+ Transformers module.
+
+ Args:
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
+ This can be either:
+
+ - a string, the *model id* of a pretrained model configuration hosted inside a model repo on
+ huggingface.co.
+ - a path to a *directory* containing a configuration file saved using the
+ [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
+
+ module_file (`str`):
+ The name of the module file containing the class to look for.
+ cache_dir (`str` or `os.PathLike`, *optional*):
+ Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
+ cache should not be used.
+ force_download (`bool`, *optional*, defaults to `False`):
+ Whether or not to force to (re-)download the configuration files and override the cached versions if they
+ exist.
+ resume_download:
+ Deprecated and ignored. All downloads are now resumed by default when possible.
+ Will be removed in v5 of Transformers.
+ proxies (`Dict[str, str]`, *optional*):
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
+ 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
+ token (`str` or *bool*, *optional*):
+ The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
+ when running `huggingface-cli login` (stored in `~/.huggingface`).
+ revision (`str`, *optional*, defaults to `"main"`):
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
+ identifier allowed by git.
+ local_files_only (`bool`, *optional*, defaults to `False`):
+ If `True`, will only try to load the tokenizer configuration from local files.
+ repo_type (`str`, *optional*):
+ Specify the repo type (useful when downloading from a space for instance).
+
+
+
+ Passing `token=True` is required when you want to use a private model.
+
+
+
+ Returns:
+ `str`: The path to the module inside the cache.
+ """
+ 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 is_offline_mode() and not local_files_only:
+ logger.info("Offline mode: forcing local_files_only=True")
+ local_files_only = True
+
+ # Download and cache module_file from the repo `pretrained_model_name_or_path` of grab it if it's a local file.
+ pretrained_model_name_or_path = str(pretrained_model_name_or_path)
+ is_local = os.path.isdir(pretrained_model_name_or_path)
+ if is_local:
+ submodule = os.path.basename(pretrained_model_name_or_path)
+ else:
+ submodule = pretrained_model_name_or_path.replace("/", os.path.sep)
+ cached_module = try_to_load_from_cache(
+ pretrained_model_name_or_path, module_file, cache_dir=cache_dir, revision=_commit_hash, repo_type=repo_type
+ )
+
+ new_files = []
+ try:
+ # Load from URL or cache if already cached
+ resolved_module_file = cached_file(
+ pretrained_model_name_or_path,
+ module_file,
+ cache_dir=cache_dir,
+ force_download=force_download,
+ proxies=proxies,
+ resume_download=resume_download,
+ local_files_only=local_files_only,
+ token=token,
+ revision=revision,
+ repo_type=repo_type,
+ _commit_hash=_commit_hash,
+ )
+ if not is_local and cached_module != resolved_module_file:
+ new_files.append(module_file)
+
+ except EnvironmentError:
+ logger.error(f"Could not locate the {module_file} inside {pretrained_model_name_or_path}.")
+ raise
+
+ # Check we have all the requirements in our environment
+ modules_needed = check_imports(resolved_module_file)
+
+ # Now we move the module inside our cached dynamic modules.
+ full_submodule = TRANSFORMERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
+ create_dynamic_module(full_submodule)
+ submodule_path = Path(HF_MODULES_CACHE) / full_submodule
+ if submodule == os.path.basename(pretrained_model_name_or_path):
+ # We copy local files to avoid putting too many folders in sys.path. This copy is done when the file is new or
+ # has changed since last copy.
+ if not (submodule_path / module_file).exists() or not filecmp.cmp(
+ resolved_module_file, str(submodule_path / module_file)
+ ):
+ shutil.copy(resolved_module_file, submodule_path / module_file)
+ importlib.invalidate_caches()
+ for module_needed in modules_needed:
+ module_needed = f"{module_needed}.py"
+ module_needed_file = os.path.join(pretrained_model_name_or_path, module_needed)
+ if not (submodule_path / module_needed).exists() or not filecmp.cmp(
+ module_needed_file, str(submodule_path / module_needed)
+ ):
+ shutil.copy(module_needed_file, submodule_path / module_needed)
+ importlib.invalidate_caches()
+ else:
+ # Get the commit hash
+ commit_hash = extract_commit_hash(resolved_module_file, _commit_hash)
+
+ # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the
+ # benefit of versioning.
+ submodule_path = submodule_path / commit_hash
+ full_submodule = full_submodule + os.path.sep + commit_hash
+ create_dynamic_module(full_submodule)
+
+ if not (submodule_path / module_file).exists():
+ shutil.copy(resolved_module_file, submodule_path / module_file)
+ importlib.invalidate_caches()
+ # Make sure we also have every file with relative
+ for module_needed in modules_needed:
+ if not (submodule_path / f"{module_needed}.py").exists():
+ get_cached_module_file(
+ pretrained_model_name_or_path,
+ f"{module_needed}.py",
+ cache_dir=cache_dir,
+ force_download=force_download,
+ resume_download=resume_download,
+ proxies=proxies,
+ token=token,
+ revision=revision,
+ local_files_only=local_files_only,
+ _commit_hash=commit_hash,
+ )
+ new_files.append(f"{module_needed}.py")
+
+ if len(new_files) > 0 and revision is None:
+ new_files = "\n".join([f"- {f}" for f in new_files])
+ repo_type_str = "" if repo_type is None else f"{repo_type}s/"
+ url = f"https://huggingface.co/{repo_type_str}{pretrained_model_name_or_path}"
+ logger.warning(
+ f"A new version of the following files was downloaded from {url}:\n{new_files}"
+ "\n. Make sure to double-check they do not contain any added malicious code. To avoid downloading new "
+ "versions of the code file, you can pin a revision."
+ )
+
+ return os.path.join(full_submodule, module_file)
+
+
+def get_class_from_dynamic_module(
+ class_reference: str,
+ pretrained_model_name_or_path: Union[str, os.PathLike],
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
+ force_download: bool = False,
+ resume_download: Optional[bool] = None,
+ proxies: Optional[Dict[str, str]] = None,
+ token: Optional[Union[bool, str]] = None,
+ revision: Optional[str] = None,
+ local_files_only: bool = False,
+ repo_type: Optional[str] = None,
+ code_revision: Optional[str] = None,
+ **kwargs,
+) -> typing.Type:
+ """
+ Extracts a class from a module file, present in the local folder or repository of a model.
+
+
+
+ Calling this function will execute the code in the module file found locally or downloaded from the Hub. It should
+ therefore only be called on trusted repos.
+
+
+
+
+
+ Args:
+ class_reference (`str`):
+ The full name of the class to load, including its module and optionally its repo.
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
+ This can be either:
+
+ - a string, the *model id* of a pretrained model configuration hosted inside a model repo on
+ huggingface.co.
+ - a path to a *directory* containing a configuration file saved using the
+ [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
+
+ This is used when `class_reference` does not specify another repo.
+ module_file (`str`):
+ The name of the module file containing the class to look for.
+ class_name (`str`):
+ The name of the class to import in the module.
+ cache_dir (`str` or `os.PathLike`, *optional*):
+ Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
+ cache should not be used.
+ force_download (`bool`, *optional*, defaults to `False`):
+ Whether or not to force to (re-)download the configuration files and override the cached versions if they
+ exist.
+ resume_download:
+ Deprecated and ignored. All downloads are now resumed by default when possible.
+ Will be removed in v5 of Transformers.
+ proxies (`Dict[str, str]`, *optional*):
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
+ 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
+ token (`str` or `bool`, *optional*):
+ The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
+ when running `huggingface-cli login` (stored in `~/.huggingface`).
+ revision (`str`, *optional*, defaults to `"main"`):
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
+ identifier allowed by git.
+ local_files_only (`bool`, *optional*, defaults to `False`):
+ If `True`, will only try to load the tokenizer configuration from local files.
+ repo_type (`str`, *optional*):
+ Specify the repo type (useful when downloading from a space for instance).
+ code_revision (`str`, *optional*, defaults to `"main"`):
+ The specific revision to use for the code on the Hub, if the code leaves in a different repository than the
+ rest of the model. 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.
+
+
+
+ Passing `token=True` is required when you want to use a private model.
+
+
+
+ Returns:
+ `typing.Type`: The class, dynamically imported from the module.
+
+ Examples:
+
+ ```python
+ # Download module `modeling.py` from huggingface.co and cache then extract the class `MyBertModel` from this
+ # module.
+ cls = get_class_from_dynamic_module("modeling.MyBertModel", "sgugger/my-bert-model")
+
+ # Download module `modeling.py` from a given repo and cache then extract the class `MyBertModel` from this
+ # module.
+ cls = get_class_from_dynamic_module("sgugger/my-bert-model--modeling.MyBertModel", "sgugger/another-bert-model")
+ ```"""
+ use_auth_token = kwargs.pop("use_auth_token", None)
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
+ FutureWarning,
+ )
+ if token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ token = use_auth_token
+
+ # Catch the name of the repo if it's specified in `class_reference`
+ if "--" in class_reference:
+ repo_id, class_reference = class_reference.split("--")
+ else:
+ repo_id = pretrained_model_name_or_path
+ module_file, class_name = class_reference.split(".")
+
+ if code_revision is None and pretrained_model_name_or_path == repo_id:
+ code_revision = revision
+ # And lastly we get the class inside our newly created module
+ final_module = get_cached_module_file(
+ repo_id,
+ module_file + ".py",
+ cache_dir=cache_dir,
+ force_download=force_download,
+ resume_download=resume_download,
+ proxies=proxies,
+ token=token,
+ revision=code_revision,
+ local_files_only=local_files_only,
+ repo_type=repo_type,
+ )
+ return get_class_in_module(class_name, final_module, force_reload=force_download)
+
+
+def custom_object_save(obj: Any, folder: Union[str, os.PathLike], config: Optional[Dict] = None) -> List[str]:
+ """
+ Save the modeling files corresponding to a custom model/configuration/tokenizer etc. in a given folder. Optionally
+ adds the proper fields in a config.
+
+ Args:
+ obj (`Any`): The object for which to save the module files.
+ folder (`str` or `os.PathLike`): The folder where to save.
+ config (`PretrainedConfig` or dictionary, `optional`):
+ A config in which to register the auto_map corresponding to this custom object.
+
+ Returns:
+ `List[str]`: The list of files saved.
+ """
+ if obj.__module__ == "__main__":
+ logger.warning(
+ f"We can't save the code defining {obj} in {folder} as it's been defined in __main__. You should put "
+ "this code in a separate module so we can include it in the saved folder and make it easier to share via "
+ "the Hub."
+ )
+ return
+
+ def _set_auto_map_in_config(_config):
+ module_name = obj.__class__.__module__
+ last_module = module_name.split(".")[-1]
+ full_name = f"{last_module}.{obj.__class__.__name__}"
+ # Special handling for tokenizers
+ if "Tokenizer" in full_name:
+ slow_tokenizer_class = None
+ fast_tokenizer_class = None
+ if obj.__class__.__name__.endswith("Fast"):
+ # Fast tokenizer: we have the fast tokenizer class and we may have the slow one has an attribute.
+ fast_tokenizer_class = f"{last_module}.{obj.__class__.__name__}"
+ if getattr(obj, "slow_tokenizer_class", None) is not None:
+ slow_tokenizer = getattr(obj, "slow_tokenizer_class")
+ slow_tok_module_name = slow_tokenizer.__module__
+ last_slow_tok_module = slow_tok_module_name.split(".")[-1]
+ slow_tokenizer_class = f"{last_slow_tok_module}.{slow_tokenizer.__name__}"
+ else:
+ # Slow tokenizer: no way to have the fast class
+ slow_tokenizer_class = f"{last_module}.{obj.__class__.__name__}"
+
+ full_name = (slow_tokenizer_class, fast_tokenizer_class)
+
+ if isinstance(_config, dict):
+ auto_map = _config.get("auto_map", {})
+ auto_map[obj._auto_class] = full_name
+ _config["auto_map"] = auto_map
+ elif getattr(_config, "auto_map", None) is not None:
+ _config.auto_map[obj._auto_class] = full_name
+ else:
+ _config.auto_map = {obj._auto_class: full_name}
+
+ # Add object class to the config auto_map
+ if isinstance(config, (list, tuple)):
+ for cfg in config:
+ _set_auto_map_in_config(cfg)
+ elif config is not None:
+ _set_auto_map_in_config(config)
+
+ result = []
+ # Copy module file to the output folder.
+ object_file = sys.modules[obj.__module__].__file__
+ dest_file = Path(folder) / (Path(object_file).name)
+ shutil.copy(object_file, dest_file)
+ result.append(dest_file)
+
+ # Gather all relative imports recursively and make sure they are copied as well.
+ for needed_file in get_relative_import_files(object_file):
+ dest_file = Path(folder) / (Path(needed_file).name)
+ shutil.copy(needed_file, dest_file)
+ result.append(dest_file)
+
+ return result
+
+
+def _raise_timeout_error(signum, frame):
+ raise ValueError(
+ "Loading this model requires you to execute custom code contained in the model repository on your local "
+ "machine. Please set the option `trust_remote_code=True` to permit loading of this model."
+ )
+
+
+TIME_OUT_REMOTE_CODE = 15
+
+
+def resolve_trust_remote_code(trust_remote_code, model_name, has_local_code, has_remote_code):
+ if trust_remote_code is None:
+ if has_local_code:
+ trust_remote_code = False
+ elif has_remote_code and TIME_OUT_REMOTE_CODE > 0:
+ prev_sig_handler = None
+ try:
+ prev_sig_handler = signal.signal(signal.SIGALRM, _raise_timeout_error)
+ signal.alarm(TIME_OUT_REMOTE_CODE)
+ while trust_remote_code is None:
+ answer = input(
+ f"The repository for {model_name} contains custom code which must be executed to correctly "
+ f"load the model. You can inspect the repository content at https://hf.co/{model_name}.\n"
+ f"You can avoid this prompt in future by passing the argument `trust_remote_code=True`.\n\n"
+ f"Do you wish to run the custom code? [y/N] "
+ )
+ if answer.lower() in ["yes", "y", "1"]:
+ trust_remote_code = True
+ elif answer.lower() in ["no", "n", "0", ""]:
+ trust_remote_code = False
+ signal.alarm(0)
+ except Exception:
+ # OS which does not support signal.SIGALRM
+ raise ValueError(
+ f"The repository for {model_name} contains custom code which must be executed to correctly "
+ f"load the model. You can inspect the repository content at https://hf.co/{model_name}.\n"
+ f"Please pass the argument `trust_remote_code=True` to allow custom code to be run."
+ )
+ finally:
+ if prev_sig_handler is not None:
+ signal.signal(signal.SIGALRM, prev_sig_handler)
+ signal.alarm(0)
+ elif has_remote_code:
+ # For the CI which puts the timeout at 0
+ _raise_timeout_error(None, None)
+
+ if has_remote_code and not has_local_code and not trust_remote_code:
+ raise ValueError(
+ f"Loading {model_name} requires you to execute the configuration file in that"
+ " repo on your local machine. Make sure you have read the code there to avoid malicious use, then"
+ " set the option `trust_remote_code=True` to remove this error."
+ )
+
+ return trust_remote_code
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/feature_extraction_sequence_utils.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/feature_extraction_sequence_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f74a3f0c40e28415644b2b2b4b81ad7ed9320a56
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/feature_extraction_sequence_utils.py
@@ -0,0 +1,372 @@
+# coding=utf-8
+# Copyright 2021 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Sequence feature extraction class for common feature extractors to preprocess sequences.
+"""
+
+from typing import Dict, List, Optional, Union
+
+import numpy as np
+
+from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin
+from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy
+
+
+logger = logging.get_logger(__name__)
+
+
+class SequenceFeatureExtractor(FeatureExtractionMixin):
+ """
+ This is a general feature extraction class for speech recognition.
+
+ Args:
+ feature_size (`int`):
+ The feature dimension of the extracted features.
+ sampling_rate (`int`):
+ The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
+ padding_value (`float`):
+ The value that is used to fill the padding values / vectors.
+ """
+
+ def __init__(self, feature_size: int, sampling_rate: int, padding_value: float, **kwargs):
+ self.feature_size = feature_size
+ self.sampling_rate = sampling_rate
+ self.padding_value = padding_value
+
+ self.padding_side = kwargs.pop("padding_side", "right")
+ self.return_attention_mask = kwargs.pop("return_attention_mask", True)
+
+ super().__init__(**kwargs)
+
+ def pad(
+ self,
+ processed_features: Union[
+ BatchFeature,
+ List[BatchFeature],
+ Dict[str, BatchFeature],
+ Dict[str, List[BatchFeature]],
+ List[Dict[str, BatchFeature]],
+ ],
+ padding: Union[bool, str, PaddingStrategy] = True,
+ max_length: Optional[int] = None,
+ truncation: bool = False,
+ pad_to_multiple_of: Optional[int] = None,
+ return_attention_mask: Optional[bool] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ ) -> BatchFeature:
+ """
+ Pad input values / input vectors or a batch of input values / input vectors up to predefined length or to the
+ max sequence length in the batch.
+
+ Padding side (left/right) padding values are defined at the feature extractor level (with `self.padding_side`,
+ `self.padding_value`)
+
+
+
+ If the `processed_features` passed are dictionary of numpy arrays, PyTorch tensors or TensorFlow tensors, the
+ result will use the same type unless you provide a different tensor type with `return_tensors`. In the case of
+ PyTorch tensors, you will lose the specific device of your tensors however.
+
+
+
+ Args:
+ processed_features ([`BatchFeature`], list of [`BatchFeature`], `Dict[str, List[float]]`, `Dict[str, List[List[float]]` or `List[Dict[str, List[float]]]`):
+ Processed inputs. Can represent one input ([`BatchFeature`] or `Dict[str, List[float]]`) or a batch of
+ input values / vectors (list of [`BatchFeature`], *Dict[str, List[List[float]]]* or *List[Dict[str,
+ List[float]]]*) so you can use this method during preprocessing as well as in a PyTorch Dataloader
+ collate function.
+
+ Instead of `List[float]` you can have tensors (numpy arrays, PyTorch tensors or TensorFlow tensors),
+ see the note above for the return type.
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
+ index) among:
+
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
+ sequence if provided).
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
+ acceptable input length for the model if that argument is not provided.
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
+ lengths).
+ max_length (`int`, *optional*):
+ Maximum length of the returned list and optionally padding length (see above).
+ truncation (`bool`):
+ Activates truncation to cut input sequences longer than `max_length` to `max_length`.
+ pad_to_multiple_of (`int`, *optional*):
+ If set will pad the sequence to a multiple of the provided value.
+
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
+ `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
+ return_attention_mask (`bool`, *optional*):
+ Whether to return the attention mask. If left to the default, will return the attention mask according
+ to the specific feature_extractor's default.
+
+ [What are attention masks?](../glossary#attention-mask)
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
+ If set, will return tensors instead of list of python integers. Acceptable values are:
+
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return Numpy `np.ndarray` objects.
+ """
+ # If we have a list of dicts, let's convert it in a dict of lists
+ # We do this to allow using this method as a collate_fn function in PyTorch Dataloader
+ if isinstance(processed_features, (list, tuple)) and isinstance(processed_features[0], (dict, BatchFeature)):
+ processed_features = {
+ key: [example[key] for example in processed_features] for key in processed_features[0].keys()
+ }
+
+ # The model's main input name, usually `input_values`, has be passed for padding
+ if self.model_input_names[0] not in processed_features:
+ raise ValueError(
+ "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`"
+ f" to this method that includes {self.model_input_names[0]}, but you provided"
+ f" {list(processed_features.keys())}"
+ )
+
+ required_input = processed_features[self.model_input_names[0]]
+ return_attention_mask = (
+ return_attention_mask if return_attention_mask is not None else self.return_attention_mask
+ )
+
+ if len(required_input) == 0:
+ if return_attention_mask:
+ processed_features["attention_mask"] = []
+ return processed_features
+
+ # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays
+ # and rebuild them afterwards if no return_tensors is specified
+ # Note that we lose the specific device the tensor may be on for PyTorch
+
+ first_element = required_input[0]
+ if isinstance(first_element, (list, tuple)):
+ # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
+ index = 0
+ while len(required_input[index]) == 0:
+ index += 1
+ if index < len(required_input):
+ first_element = required_input[index][0]
+
+ if return_tensors is None:
+ if is_tf_tensor(first_element):
+ return_tensors = "tf"
+ elif is_torch_tensor(first_element):
+ return_tensors = "pt"
+ elif isinstance(first_element, (int, float, list, tuple, np.ndarray)):
+ return_tensors = "np"
+ else:
+ raise ValueError(
+ f"type of {first_element} unknown: {type(first_element)}. "
+ "Should be one of a python, numpy, pytorch or tensorflow object."
+ )
+
+ for key, value in processed_features.items():
+ if isinstance(value[0], (int, float)):
+ processed_features[key] = to_numpy(value)
+ else:
+ processed_features[key] = [to_numpy(v) for v in value]
+
+ # Convert padding_strategy in PaddingStrategy
+ padding_strategy = self._get_padding_strategies(padding=padding, max_length=max_length)
+
+ required_input = processed_features[self.model_input_names[0]]
+
+ batch_size = len(required_input)
+ if not all(len(v) == batch_size for v in processed_features.values()):
+ raise ValueError("Some items in the output dictionary have a different batch size than others.")
+
+ truncated_inputs = []
+ for i in range(batch_size):
+ inputs = {k: v[i] for k, v in processed_features.items()}
+ # truncation
+ inputs_slice = self._truncate(
+ inputs,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ truncation=truncation,
+ )
+ truncated_inputs.append(inputs_slice)
+
+ if padding_strategy == PaddingStrategy.LONGEST:
+ # make sure that `max_length` cannot be longer than the longest truncated length
+ max_length = max(len(input_slice[self.model_input_names[0]]) for input_slice in truncated_inputs)
+ padding_strategy = PaddingStrategy.MAX_LENGTH
+
+ batch_outputs = {}
+ for i in range(batch_size):
+ # padding
+ outputs = self._pad(
+ truncated_inputs[i],
+ max_length=max_length,
+ padding_strategy=padding_strategy,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_attention_mask=return_attention_mask,
+ )
+
+ for key, value in outputs.items():
+ if key not in batch_outputs:
+ batch_outputs[key] = []
+ if value.dtype is np.dtype(np.float64):
+ value = value.astype(np.float32)
+ batch_outputs[key].append(value)
+
+ return BatchFeature(batch_outputs, tensor_type=return_tensors)
+
+ def _pad(
+ self,
+ processed_features: Union[Dict[str, np.ndarray], BatchFeature],
+ max_length: Optional[int] = None,
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
+ pad_to_multiple_of: Optional[int] = None,
+ return_attention_mask: Optional[bool] = None,
+ ) -> dict:
+ """
+ Pad inputs (on left/right and up to predefined length or max length in the batch)
+
+ Args:
+ processed_features (`Union[Dict[str, np.ndarray], BatchFeature]`):
+ Dictionary of input values (`np.ndarray[float]`) / input vectors (`List[np.ndarray[float]]`) or batch
+ of inputs values (`List[np.ndarray[int]]`) / input vectors (`List[np.ndarray[int]]`)
+ max_length (`int`, *optional*):
+ Maximum length of the returned list and optionally padding length (see below)
+ padding_strategy (`PaddingStrategy`, *optional*, default to `PaddingStrategy.DO_NOT_PAD`):
+ PaddingStrategy to use for padding.
+
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
+ The feature_extractor padding sides are defined in self.padding_side:
+
+ - 'left': pads on the left of the sequences
+ - 'right': pads on the right of the sequences
+ pad_to_multiple_of (`int`, *optional*):
+ Integer if set will pad the sequence to a multiple of the provided value. This is especially useful to
+ enable the use of Tensor Core on NVIDIA hardware with compute capability `>= 7.5` (Volta), or on TPUs
+ which benefit from having sequence lengths be a multiple of 128.
+ return_attention_mask (`bool`, *optional*):
+ Set to False to avoid returning attention mask (default: set to model specifics)
+ """
+ required_input = processed_features[self.model_input_names[0]]
+
+ if padding_strategy == PaddingStrategy.LONGEST:
+ max_length = len(required_input)
+
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
+
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) < max_length
+
+ if return_attention_mask and "attention_mask" not in processed_features:
+ processed_features["attention_mask"] = np.ones(len(required_input), dtype=np.int32)
+
+ if needs_to_be_padded:
+ difference = max_length - len(required_input)
+ if self.padding_side == "right":
+ if return_attention_mask:
+ processed_features["attention_mask"] = np.pad(
+ processed_features["attention_mask"], (0, difference)
+ )
+ padding_shape = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference)
+ processed_features[self.model_input_names[0]] = np.pad(
+ required_input, padding_shape, "constant", constant_values=self.padding_value
+ )
+ elif self.padding_side == "left":
+ if return_attention_mask:
+ processed_features["attention_mask"] = np.pad(
+ processed_features["attention_mask"], (difference, 0)
+ )
+ padding_shape = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0)
+ processed_features[self.model_input_names[0]] = np.pad(
+ required_input, padding_shape, "constant", constant_values=self.padding_value
+ )
+ else:
+ raise ValueError("Invalid padding strategy:" + str(self.padding_side))
+
+ return processed_features
+
+ def _truncate(
+ self,
+ processed_features: Union[Dict[str, np.ndarray], BatchFeature],
+ max_length: Optional[int] = None,
+ pad_to_multiple_of: Optional[int] = None,
+ truncation: Optional[bool] = None,
+ ):
+ """
+ Truncate inputs to predefined length or max length in the batch
+
+ Args:
+ processed_features(`Union[Dict[str, np.ndarray], BatchFeature]`):
+ Dictionary of input values (`np.ndarray[float]`) / input vectors (`List[np.ndarray[float]]`) or batch
+ of inputs values (`List[np.ndarray[int]]`) / input vectors (`List[np.ndarray[int]]`)
+ max_length (`int`, *optional*):
+ maximum length of the returned list and optionally padding length (see below)
+ pad_to_multiple_of (`int`, *optional*) :
+ Integer if set will pad the sequence to a multiple of the provided value. This is especially useful to
+ enable the use of Tensor Core on NVIDIA hardware with compute capability `>= 7.5` (Volta), or on TPUs
+ which benefit from having sequence lengths be a multiple of 128.
+ truncation (`bool`, *optional*):
+ Activates truncation to cut input sequences longer than `max_length` to `max_length`.
+ """
+ if not truncation:
+ return processed_features
+ elif truncation and max_length is None:
+ raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined.")
+
+ required_input = processed_features[self.model_input_names[0]]
+
+ # find `max_length` that fits `pad_to_multiple_of`
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
+
+ needs_to_be_truncated = len(required_input) > max_length
+
+ if needs_to_be_truncated:
+ processed_features[self.model_input_names[0]] = processed_features[self.model_input_names[0]][:max_length]
+ if "attention_mask" in processed_features:
+ processed_features["attention_mask"] = processed_features["attention_mask"][:max_length]
+
+ return processed_features
+
+ def _get_padding_strategies(self, padding=False, max_length=None):
+ """
+ Find the correct padding strategy
+ """
+
+ # Get padding strategy
+ if padding is not False:
+ if padding is True:
+ padding_strategy = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch
+ elif not isinstance(padding, PaddingStrategy):
+ padding_strategy = PaddingStrategy(padding)
+ elif isinstance(padding, PaddingStrategy):
+ padding_strategy = padding
+ else:
+ padding_strategy = PaddingStrategy.DO_NOT_PAD
+
+ # Set max length if needed
+ if max_length is None:
+ if padding_strategy == PaddingStrategy.MAX_LENGTH:
+ raise ValueError(
+ f"When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined"
+ )
+
+ # Test if we have a padding value
+ if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None):
+ raise ValueError(
+ "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use"
+ " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`."
+ )
+
+ return padding_strategy
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/feature_extraction_utils.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/feature_extraction_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e8007edbc0b782970887e83a08ba518de0f264a
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/feature_extraction_utils.py
@@ -0,0 +1,702 @@
+# 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.
+"""
+Feature extraction saving/loading class for common feature extractors.
+"""
+
+import copy
+import json
+import os
+import warnings
+from collections import UserDict
+from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
+
+import numpy as np
+
+from .dynamic_module_utils import custom_object_save
+from .utils import (
+ FEATURE_EXTRACTOR_NAME,
+ PushToHubMixin,
+ TensorType,
+ add_model_info_to_auto_map,
+ add_model_info_to_custom_pipelines,
+ cached_file,
+ copy_func,
+ download_url,
+ is_flax_available,
+ is_jax_tensor,
+ is_numpy_array,
+ is_offline_mode,
+ is_remote_url,
+ is_tf_available,
+ is_torch_available,
+ is_torch_device,
+ is_torch_dtype,
+ logging,
+ requires_backends,
+)
+
+
+if TYPE_CHECKING:
+ if is_torch_available():
+ import torch # noqa
+
+
+logger = logging.get_logger(__name__)
+
+PreTrainedFeatureExtractor = Union["SequenceFeatureExtractor"] # noqa: F821
+
+
+class BatchFeature(UserDict):
+ r"""
+ Holds the output of the [`~SequenceFeatureExtractor.pad`] and feature extractor specific `__call__` methods.
+
+ This class is derived from a python dictionary and can be used as a dictionary.
+
+ Args:
+ data (`dict`, *optional*):
+ Dictionary of lists/arrays/tensors returned by the __call__/pad methods ('input_values', 'attention_mask',
+ etc.).
+ tensor_type (`Union[None, str, TensorType]`, *optional*):
+ You can give a tensor_type here to convert the lists of integers in PyTorch/TensorFlow/Numpy Tensors at
+ initialization.
+ """
+
+ def __init__(self, data: Optional[Dict[str, Any]] = None, tensor_type: Union[None, str, TensorType] = None):
+ super().__init__(data)
+ self.convert_to_tensors(tensor_type=tensor_type)
+
+ def __getitem__(self, item: str) -> Union[Any]:
+ """
+ If the key is a string, returns the value of the dict associated to `key` ('input_values', 'attention_mask',
+ etc.).
+ """
+ if isinstance(item, str):
+ return self.data[item]
+ else:
+ raise KeyError("Indexing with integers is not available when using Python based feature extractors")
+
+ def __getattr__(self, item: str):
+ try:
+ return self.data[item]
+ except KeyError:
+ raise AttributeError
+
+ def __getstate__(self):
+ return {"data": self.data}
+
+ def __setstate__(self, state):
+ if "data" in state:
+ self.data = state["data"]
+
+ # Copied from transformers.tokenization_utils_base.BatchEncoding.keys
+ def keys(self):
+ return self.data.keys()
+
+ # Copied from transformers.tokenization_utils_base.BatchEncoding.values
+ def values(self):
+ return self.data.values()
+
+ # Copied from transformers.tokenization_utils_base.BatchEncoding.items
+ def items(self):
+ return self.data.items()
+
+ def _get_is_as_tensor_fns(self, tensor_type: Optional[Union[str, TensorType]] = None):
+ if tensor_type is None:
+ return None, None
+
+ # Convert to TensorType
+ if not isinstance(tensor_type, TensorType):
+ tensor_type = TensorType(tensor_type)
+
+ # Get a function reference for the correct framework
+ if tensor_type == TensorType.TENSORFLOW:
+ if not is_tf_available():
+ raise ImportError(
+ "Unable to convert output to TensorFlow tensors format, TensorFlow is not installed."
+ )
+ import tensorflow as tf
+
+ as_tensor = tf.constant
+ is_tensor = tf.is_tensor
+ elif tensor_type == TensorType.PYTORCH:
+ if not is_torch_available():
+ raise ImportError("Unable to convert output to PyTorch tensors format, PyTorch is not installed.")
+ import torch # noqa
+
+ def as_tensor(value):
+ if isinstance(value, (list, tuple)) and len(value) > 0:
+ if isinstance(value[0], np.ndarray):
+ value = np.array(value)
+ elif (
+ isinstance(value[0], (list, tuple))
+ and len(value[0]) > 0
+ and isinstance(value[0][0], np.ndarray)
+ ):
+ value = np.array(value)
+ if isinstance(value, np.ndarray):
+ return torch.from_numpy(value)
+ else:
+ return torch.tensor(value)
+
+ is_tensor = torch.is_tensor
+ elif tensor_type == TensorType.JAX:
+ if not is_flax_available():
+ raise ImportError("Unable to convert output to JAX tensors format, JAX is not installed.")
+ import jax.numpy as jnp # noqa: F811
+
+ as_tensor = jnp.array
+ is_tensor = is_jax_tensor
+ else:
+
+ def as_tensor(value, dtype=None):
+ if isinstance(value, (list, tuple)) and isinstance(value[0], (list, tuple, np.ndarray)):
+ value_lens = [len(val) for val in value]
+ if len(set(value_lens)) > 1 and dtype is None:
+ # we have a ragged list so handle explicitly
+ value = as_tensor([np.asarray(val) for val in value], dtype=object)
+ return np.asarray(value, dtype=dtype)
+
+ is_tensor = is_numpy_array
+ return is_tensor, as_tensor
+
+ def convert_to_tensors(self, tensor_type: Optional[Union[str, TensorType]] = None):
+ """
+ Convert the inner content to tensors.
+
+ Args:
+ tensor_type (`str` or [`~utils.TensorType`], *optional*):
+ The type of tensors to use. If `str`, should be one of the values of the enum [`~utils.TensorType`]. If
+ `None`, no modification is done.
+ """
+ if tensor_type is None:
+ return self
+
+ is_tensor, as_tensor = self._get_is_as_tensor_fns(tensor_type)
+
+ # Do the tensor conversion in batch
+ for key, value in self.items():
+ try:
+ if not is_tensor(value):
+ tensor = as_tensor(value)
+
+ self[key] = tensor
+ except: # noqa E722
+ if key == "overflowing_values":
+ raise ValueError("Unable to create tensor returning overflowing values of different lengths. ")
+ raise ValueError(
+ "Unable to create tensor, you should probably activate padding "
+ "with 'padding=True' to have batched tensors with the same length."
+ )
+
+ return self
+
+ def to(self, *args, **kwargs) -> "BatchFeature":
+ """
+ Send all values to device by calling `v.to(*args, **kwargs)` (PyTorch only). This should support casting in
+ different `dtypes` and sending the `BatchFeature` to a different `device`.
+
+ Args:
+ args (`Tuple`):
+ Will be passed to the `to(...)` function of the tensors.
+ kwargs (`Dict`, *optional*):
+ Will be passed to the `to(...)` function of the tensors.
+ To enable asynchronous data transfer, set the `non_blocking` flag in `kwargs` (defaults to `False`).
+
+ Returns:
+ [`BatchFeature`]: The same instance after modification.
+ """
+ requires_backends(self, ["torch"])
+ import torch # noqa
+
+ new_data = {}
+ device = kwargs.get("device")
+ non_blocking = kwargs.get("non_blocking", False)
+ # Check if the args are a device or a dtype
+ if device is None and len(args) > 0:
+ # device should be always the first argument
+ arg = args[0]
+ if is_torch_dtype(arg):
+ # The first argument is a dtype
+ pass
+ elif isinstance(arg, str) or is_torch_device(arg) or isinstance(arg, int):
+ device = arg
+ else:
+ # it's something else
+ raise ValueError(f"Attempting to cast a BatchFeature to type {str(arg)}. This is not supported.")
+ # We cast only floating point tensors to avoid issues with tokenizers casting `LongTensor` to `FloatTensor`
+ for k, v in self.items():
+ # check if v is a floating point
+ if isinstance(v, torch.Tensor) and torch.is_floating_point(v):
+ # cast and send to device
+ new_data[k] = v.to(*args, **kwargs)
+ elif isinstance(v, torch.Tensor) and device is not None:
+ new_data[k] = v.to(device=device, non_blocking=non_blocking)
+ else:
+ new_data[k] = v
+ self.data = new_data
+ return self
+
+
+class FeatureExtractionMixin(PushToHubMixin):
+ """
+ This is a feature extraction mixin used to provide saving/loading functionality for sequential and image feature
+ extractors.
+ """
+
+ _auto_class = None
+
+ def __init__(self, **kwargs):
+ """Set elements of `kwargs` as attributes."""
+ # Pop "processor_class" as it should be saved as private attribute
+ self._processor_class = kwargs.pop("processor_class", None)
+ # Additional attributes without default values
+ for key, value in kwargs.items():
+ try:
+ setattr(self, key, value)
+ except AttributeError as err:
+ logger.error(f"Can't set {key} with value {value} for {self}")
+ raise err
+
+ def _set_processor_class(self, processor_class: str):
+ """Sets processor class as an attribute."""
+ self._processor_class = processor_class
+
+ @classmethod
+ def from_pretrained(
+ cls,
+ pretrained_model_name_or_path: Union[str, os.PathLike],
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
+ force_download: bool = False,
+ local_files_only: bool = False,
+ token: Optional[Union[str, bool]] = None,
+ revision: str = "main",
+ **kwargs,
+ ):
+ r"""
+ Instantiate a type of [`~feature_extraction_utils.FeatureExtractionMixin`] from a feature extractor, *e.g.* a
+ derived class of [`SequenceFeatureExtractor`].
+
+ Args:
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
+ This can be either:
+
+ - a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on
+ huggingface.co.
+ - a path to a *directory* containing a feature extractor file saved using the
+ [`~feature_extraction_utils.FeatureExtractionMixin.save_pretrained`] method, e.g.,
+ `./my_model_directory/`.
+ - a path or url to a saved feature extractor JSON *file*, e.g.,
+ `./my_model_directory/preprocessor_config.json`.
+ cache_dir (`str` or `os.PathLike`, *optional*):
+ Path to a directory in which a downloaded pretrained model feature extractor should be cached if the
+ standard cache should not be used.
+ force_download (`bool`, *optional*, defaults to `False`):
+ Whether or not to force to (re-)download the feature extractor files and override the cached versions
+ if they exist.
+ resume_download:
+ Deprecated and ignored. All downloads are now resumed by default when possible.
+ Will be removed in v5 of Transformers.
+ proxies (`Dict[str, str]`, *optional*):
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
+ 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
+ token (`str` or `bool`, *optional*):
+ The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, 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/"`.
+
+
+
+ return_unused_kwargs (`bool`, *optional*, defaults to `False`):
+ If `False`, then this function returns just the final feature extractor object. If `True`, then this
+ functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary
+ consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part of
+ `kwargs` which has not been used to update `feature_extractor` and is otherwise ignored.
+ kwargs (`Dict[str, Any]`, *optional*):
+ The values in kwargs of any keys which are feature extractor attributes will be used to override the
+ loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is
+ controlled by the `return_unused_kwargs` keyword parameter.
+
+ Returns:
+ A feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`].
+
+ Examples:
+
+ ```python
+ # We can't instantiate directly the base class *FeatureExtractionMixin* nor *SequenceFeatureExtractor* so let's show the examples on a
+ # derived class: *Wav2Vec2FeatureExtractor*
+ feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
+ "facebook/wav2vec2-base-960h"
+ ) # Download feature_extraction_config from huggingface.co and cache.
+ feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
+ "./test/saved_model/"
+ ) # E.g. feature_extractor (or model) was saved using *save_pretrained('./test/saved_model/')*
+ feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("./test/saved_model/preprocessor_config.json")
+ feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
+ "facebook/wav2vec2-base-960h", return_attention_mask=False, foo=False
+ )
+ assert feature_extractor.return_attention_mask is False
+ feature_extractor, unused_kwargs = Wav2Vec2FeatureExtractor.from_pretrained(
+ "facebook/wav2vec2-base-960h", return_attention_mask=False, foo=False, return_unused_kwargs=True
+ )
+ assert feature_extractor.return_attention_mask is False
+ assert unused_kwargs == {"foo": False}
+ ```"""
+ kwargs["cache_dir"] = cache_dir
+ kwargs["force_download"] = force_download
+ kwargs["local_files_only"] = local_files_only
+ kwargs["revision"] = revision
+
+ use_auth_token = kwargs.pop("use_auth_token", None)
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
+ FutureWarning,
+ )
+ if token is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ token = use_auth_token
+
+ if token is not None:
+ kwargs["token"] = token
+
+ feature_extractor_dict, kwargs = cls.get_feature_extractor_dict(pretrained_model_name_or_path, **kwargs)
+
+ return cls.from_dict(feature_extractor_dict, **kwargs)
+
+ def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
+ """
+ Save a feature_extractor object to the directory `save_directory`, so that it can be re-loaded using the
+ [`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`] class method.
+
+ Args:
+ save_directory (`str` or `os.PathLike`):
+ Directory where the feature extractor JSON file will be saved (will be created if it does not exist).
+ push_to_hub (`bool`, *optional*, defaults to `False`):
+ Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
+ repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
+ namespace).
+ kwargs (`Dict[str, Any]`, *optional*):
+ Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
+ """
+ use_auth_token = kwargs.pop("use_auth_token", None)
+
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
+ FutureWarning,
+ )
+ if kwargs.get("token", None) is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ kwargs["token"] = use_auth_token
+
+ if os.path.isfile(save_directory):
+ raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
+
+ os.makedirs(save_directory, exist_ok=True)
+
+ if push_to_hub:
+ commit_message = kwargs.pop("commit_message", None)
+ repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
+ repo_id = self._create_repo(repo_id, **kwargs)
+ files_timestamps = self._get_files_timestamps(save_directory)
+
+ # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
+ # loaded from the Hub.
+ if self._auto_class is not None:
+ custom_object_save(self, save_directory, config=self)
+
+ # If we save using the predefined names, we can load using `from_pretrained`
+ output_feature_extractor_file = os.path.join(save_directory, FEATURE_EXTRACTOR_NAME)
+
+ self.to_json_file(output_feature_extractor_file)
+ logger.info(f"Feature extractor saved in {output_feature_extractor_file}")
+
+ if push_to_hub:
+ self._upload_modified_files(
+ save_directory,
+ repo_id,
+ files_timestamps,
+ commit_message=commit_message,
+ token=kwargs.get("token"),
+ )
+
+ return [output_feature_extractor_file]
+
+ @classmethod
+ def get_feature_extractor_dict(
+ cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
+ ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
+ """
+ From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a
+ feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`] using `from_dict`.
+
+ Parameters:
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
+ The identifier of the pre-trained checkpoint from which we want the dictionary of parameters.
+
+ Returns:
+ `Tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the feature extractor object.
+ """
+ cache_dir = kwargs.pop("cache_dir", None)
+ force_download = kwargs.pop("force_download", False)
+ resume_download = kwargs.pop("resume_download", None)
+ proxies = kwargs.pop("proxies", None)
+ subfolder = kwargs.pop("subfolder", None)
+ token = kwargs.pop("token", None)
+ use_auth_token = kwargs.pop("use_auth_token", None)
+ local_files_only = kwargs.pop("local_files_only", False)
+ revision = kwargs.pop("revision", 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
+
+ from_pipeline = kwargs.pop("_from_pipeline", None)
+ from_auto_class = kwargs.pop("_from_auto", False)
+
+ user_agent = {"file_type": "feature extractor", "from_auto_class": from_auto_class}
+ if from_pipeline is not None:
+ user_agent["using_pipeline"] = from_pipeline
+
+ if is_offline_mode() and not local_files_only:
+ logger.info("Offline mode: forcing local_files_only=True")
+ local_files_only = True
+
+ pretrained_model_name_or_path = str(pretrained_model_name_or_path)
+ is_local = os.path.isdir(pretrained_model_name_or_path)
+ if os.path.isdir(pretrained_model_name_or_path):
+ feature_extractor_file = os.path.join(pretrained_model_name_or_path, FEATURE_EXTRACTOR_NAME)
+ if os.path.isfile(pretrained_model_name_or_path):
+ resolved_feature_extractor_file = pretrained_model_name_or_path
+ is_local = True
+ elif is_remote_url(pretrained_model_name_or_path):
+ feature_extractor_file = pretrained_model_name_or_path
+ resolved_feature_extractor_file = download_url(pretrained_model_name_or_path)
+ else:
+ feature_extractor_file = FEATURE_EXTRACTOR_NAME
+ try:
+ # Load from local folder or from cache or download from model Hub and cache
+ resolved_feature_extractor_file = cached_file(
+ pretrained_model_name_or_path,
+ feature_extractor_file,
+ cache_dir=cache_dir,
+ force_download=force_download,
+ proxies=proxies,
+ resume_download=resume_download,
+ local_files_only=local_files_only,
+ subfolder=subfolder,
+ token=token,
+ user_agent=user_agent,
+ revision=revision,
+ )
+ except EnvironmentError:
+ # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to
+ # the original exception.
+ raise
+ except Exception:
+ # For any other exception, we throw a generic error.
+ raise EnvironmentError(
+ f"Can't load feature extractor for '{pretrained_model_name_or_path}'. If you were trying to load"
+ " it from 'https://huggingface.co/models', make sure you don't have a local directory with the"
+ f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a"
+ f" directory containing a {FEATURE_EXTRACTOR_NAME} file"
+ )
+
+ try:
+ # Load feature_extractor dict
+ with open(resolved_feature_extractor_file, "r", encoding="utf-8") as reader:
+ text = reader.read()
+ feature_extractor_dict = json.loads(text)
+
+ except json.JSONDecodeError:
+ raise EnvironmentError(
+ f"It looks like the config file at '{resolved_feature_extractor_file}' is not a valid JSON file."
+ )
+
+ if is_local:
+ logger.info(f"loading configuration file {resolved_feature_extractor_file}")
+ else:
+ logger.info(
+ f"loading configuration file {feature_extractor_file} from cache at {resolved_feature_extractor_file}"
+ )
+
+ if not is_local:
+ if "auto_map" in feature_extractor_dict:
+ feature_extractor_dict["auto_map"] = add_model_info_to_auto_map(
+ feature_extractor_dict["auto_map"], pretrained_model_name_or_path
+ )
+ if "custom_pipelines" in feature_extractor_dict:
+ feature_extractor_dict["custom_pipelines"] = add_model_info_to_custom_pipelines(
+ feature_extractor_dict["custom_pipelines"], pretrained_model_name_or_path
+ )
+
+ return feature_extractor_dict, kwargs
+
+ @classmethod
+ def from_dict(cls, feature_extractor_dict: Dict[str, Any], **kwargs) -> PreTrainedFeatureExtractor:
+ """
+ Instantiates a type of [`~feature_extraction_utils.FeatureExtractionMixin`] from a Python dictionary of
+ parameters.
+
+ Args:
+ feature_extractor_dict (`Dict[str, Any]`):
+ Dictionary that will be used to instantiate the feature extractor object. Such a dictionary can be
+ retrieved from a pretrained checkpoint by leveraging the
+ [`~feature_extraction_utils.FeatureExtractionMixin.to_dict`] method.
+ kwargs (`Dict[str, Any]`):
+ Additional parameters from which to initialize the feature extractor object.
+
+ Returns:
+ [`~feature_extraction_utils.FeatureExtractionMixin`]: The feature extractor object instantiated from those
+ parameters.
+ """
+ return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
+
+ # Update feature_extractor with kwargs if needed
+ to_remove = []
+ for key, value in kwargs.items():
+ if key in feature_extractor_dict:
+ feature_extractor_dict[key] = value
+ to_remove.append(key)
+ for key in to_remove:
+ kwargs.pop(key, None)
+
+ feature_extractor = cls(**feature_extractor_dict)
+
+ logger.info(f"Feature extractor {feature_extractor}")
+ if return_unused_kwargs:
+ return feature_extractor, kwargs
+ else:
+ return feature_extractor
+
+ 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["feature_extractor_type"] = self.__class__.__name__
+ if "mel_filters" in output:
+ del output["mel_filters"]
+ if "window" in output:
+ del output["window"]
+ return output
+
+ @classmethod
+ def from_json_file(cls, json_file: Union[str, os.PathLike]) -> PreTrainedFeatureExtractor:
+ """
+ Instantiates a feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`] from the path to
+ a JSON file of parameters.
+
+ Args:
+ json_file (`str` or `os.PathLike`):
+ Path to the JSON file containing the parameters.
+
+ Returns:
+ A feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`]: The feature_extractor
+ object instantiated from that JSON file.
+ """
+ with open(json_file, "r", encoding="utf-8") as reader:
+ text = reader.read()
+ feature_extractor_dict = json.loads(text)
+ return cls(**feature_extractor_dict)
+
+ def to_json_string(self) -> str:
+ """
+ Serializes this instance to a JSON string.
+
+ Returns:
+ `str`: String containing all the attributes that make up this feature_extractor instance in JSON format.
+ """
+ dictionary = self.to_dict()
+
+ for key, value in dictionary.items():
+ if isinstance(value, np.ndarray):
+ dictionary[key] = value.tolist()
+
+ # make sure private name "_processor_class" is correctly
+ # saved as "processor_class"
+ _processor_class = dictionary.pop("_processor_class", None)
+ if _processor_class is not None:
+ dictionary["processor_class"] = _processor_class
+
+ return json.dumps(dictionary, indent=2, sort_keys=True) + "\n"
+
+ 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 feature_extractor instance's parameters will be saved.
+ """
+ with open(json_file_path, "w", encoding="utf-8") as writer:
+ writer.write(self.to_json_string())
+
+ def __repr__(self):
+ return f"{self.__class__.__name__} {self.to_json_string()}"
+
+ @classmethod
+ def register_for_auto_class(cls, auto_class="AutoFeatureExtractor"):
+ """
+ Register this class with a given auto class. This should only be used for custom feature extractors as the ones
+ in the library are already mapped with `AutoFeatureExtractor`.
+
+
+
+ This API is experimental and may have some slight breaking changes in the next releases.
+
+
+
+ Args:
+ auto_class (`str` or `type`, *optional*, defaults to `"AutoFeatureExtractor"`):
+ The auto class to register this new feature extractor with.
+ """
+ if not isinstance(auto_class, str):
+ auto_class = auto_class.__name__
+
+ import transformers.models.auto as auto_module
+
+ if not hasattr(auto_module, auto_class):
+ raise ValueError(f"{auto_class} is not a valid auto class.")
+
+ cls._auto_class = auto_class
+
+
+FeatureExtractionMixin.push_to_hub = copy_func(FeatureExtractionMixin.push_to_hub)
+if FeatureExtractionMixin.push_to_hub.__doc__ is not None:
+ FeatureExtractionMixin.push_to_hub.__doc__ = FeatureExtractionMixin.push_to_hub.__doc__.format(
+ object="feature extractor", object_class="AutoFeatureExtractor", object_files="feature extractor file"
+ )
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/file_utils.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/file_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac6b36d2dbcf7fef3621a3b35f083ae89a39b1b4
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/file_utils.py
@@ -0,0 +1,131 @@
+# 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.
+"""
+File utilities: utilities related to download and cache models
+
+This module should not be update anymore and is only left for backward compatibility.
+"""
+
+from huggingface_hub import get_full_repo_name # for backward compatibility
+from huggingface_hub.constants import HF_HUB_DISABLE_TELEMETRY as DISABLE_TELEMETRY # for backward compatibility
+
+from . import __version__
+
+# Backward compatibility imports, to make sure all those objects can be found in file_utils
+from .utils import (
+ CLOUDFRONT_DISTRIB_PREFIX,
+ CONFIG_NAME,
+ DUMMY_INPUTS,
+ DUMMY_MASK,
+ ENV_VARS_TRUE_AND_AUTO_VALUES,
+ ENV_VARS_TRUE_VALUES,
+ FEATURE_EXTRACTOR_NAME,
+ FLAX_WEIGHTS_NAME,
+ HF_MODULES_CACHE,
+ HUGGINGFACE_CO_PREFIX,
+ HUGGINGFACE_CO_RESOLVE_ENDPOINT,
+ MODEL_CARD_NAME,
+ MULTIPLE_CHOICE_DUMMY_INPUTS,
+ PYTORCH_PRETRAINED_BERT_CACHE,
+ PYTORCH_TRANSFORMERS_CACHE,
+ S3_BUCKET_PREFIX,
+ SENTENCEPIECE_UNDERLINE,
+ SPIECE_UNDERLINE,
+ TF2_WEIGHTS_NAME,
+ TF_WEIGHTS_NAME,
+ TORCH_FX_REQUIRED_VERSION,
+ TRANSFORMERS_CACHE,
+ TRANSFORMERS_DYNAMIC_MODULE_NAME,
+ USE_JAX,
+ USE_TF,
+ USE_TORCH,
+ WEIGHTS_INDEX_NAME,
+ WEIGHTS_NAME,
+ ContextManagers,
+ DummyObject,
+ EntryNotFoundError,
+ ExplicitEnum,
+ ModelOutput,
+ PaddingStrategy,
+ PushToHubMixin,
+ RepositoryNotFoundError,
+ RevisionNotFoundError,
+ TensorType,
+ _LazyModule,
+ add_code_sample_docstrings,
+ add_end_docstrings,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ cached_property,
+ copy_func,
+ default_cache_path,
+ define_sagemaker_information,
+ get_torch_version,
+ has_file,
+ http_user_agent,
+ is_apex_available,
+ is_bs4_available,
+ is_coloredlogs_available,
+ is_datasets_available,
+ is_detectron2_available,
+ is_faiss_available,
+ is_flax_available,
+ is_ftfy_available,
+ is_g2p_en_available,
+ is_in_notebook,
+ is_ipex_available,
+ is_librosa_available,
+ is_offline_mode,
+ is_onnx_available,
+ is_pandas_available,
+ is_phonemizer_available,
+ is_protobuf_available,
+ is_psutil_available,
+ is_py3nvml_available,
+ is_pyctcdecode_available,
+ is_pytesseract_available,
+ is_pytorch_quantization_available,
+ is_rjieba_available,
+ is_sagemaker_dp_enabled,
+ is_sagemaker_mp_enabled,
+ is_scipy_available,
+ is_sentencepiece_available,
+ is_seqio_available,
+ is_sklearn_available,
+ is_soundfile_available,
+ is_spacy_available,
+ is_speech_available,
+ is_tensor,
+ is_tensorflow_probability_available,
+ is_tf2onnx_available,
+ is_tf_available,
+ is_timm_available,
+ is_tokenizers_available,
+ is_torch_available,
+ is_torch_bf16_available,
+ is_torch_cuda_available,
+ is_torch_fx_available,
+ is_torch_fx_proxy,
+ is_torch_mps_available,
+ is_torch_tf32_available,
+ is_torch_xla_available,
+ is_torchaudio_available,
+ is_training_run_on_sagemaker,
+ is_vision_available,
+ replace_return_docstrings,
+ requires_backends,
+ to_numpy,
+ to_py_obj,
+ torch_only_method,
+)
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/__init__.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf1fa3661e0c89b805b2a690df75e0f924cd27cd
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/__init__.py
@@ -0,0 +1,348 @@
+# 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 typing import TYPE_CHECKING
+
+from ..utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available
+
+
+_import_structure = {
+ "configuration_utils": [
+ "BaseWatermarkingConfig",
+ "CompileConfig",
+ "GenerationConfig",
+ "GenerationMode",
+ "SynthIDTextWatermarkingConfig",
+ "WatermarkingConfig",
+ ],
+ "streamers": ["AsyncTextIteratorStreamer", "BaseStreamer", "TextIteratorStreamer", "TextStreamer"],
+}
+
+try:
+ if not is_torch_available():
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ pass
+else:
+ _import_structure["beam_constraints"] = [
+ "Constraint",
+ "ConstraintListState",
+ "DisjunctiveConstraint",
+ "PhrasalConstraint",
+ ]
+ _import_structure["beam_search"] = [
+ "BeamHypotheses",
+ "BeamScorer",
+ "BeamSearchScorer",
+ "ConstrainedBeamSearchScorer",
+ ]
+ _import_structure["candidate_generator"] = [
+ "AssistedCandidateGenerator",
+ "CandidateGenerator",
+ "EarlyExitCandidateGenerator",
+ "PromptLookupCandidateGenerator",
+ ]
+ _import_structure["logits_process"] = [
+ "AlternatingCodebooksLogitsProcessor",
+ "ClassifierFreeGuidanceLogitsProcessor",
+ "EncoderNoRepeatNGramLogitsProcessor",
+ "EncoderRepetitionPenaltyLogitsProcessor",
+ "EpsilonLogitsWarper",
+ "EtaLogitsWarper",
+ "ExponentialDecayLengthPenalty",
+ "ForcedBOSTokenLogitsProcessor",
+ "ForcedEOSTokenLogitsProcessor",
+ "HammingDiversityLogitsProcessor",
+ "InfNanRemoveLogitsProcessor",
+ "LogitNormalization",
+ "LogitsProcessor",
+ "LogitsProcessorList",
+ "MinLengthLogitsProcessor",
+ "MinNewTokensLengthLogitsProcessor",
+ "MinPLogitsWarper",
+ "NoBadWordsLogitsProcessor",
+ "NoRepeatNGramLogitsProcessor",
+ "PrefixConstrainedLogitsProcessor",
+ "RepetitionPenaltyLogitsProcessor",
+ "SequenceBiasLogitsProcessor",
+ "SuppressTokensLogitsProcessor",
+ "SuppressTokensAtBeginLogitsProcessor",
+ "SynthIDTextWatermarkLogitsProcessor",
+ "TemperatureLogitsWarper",
+ "TopKLogitsWarper",
+ "TopPLogitsWarper",
+ "TypicalLogitsWarper",
+ "UnbatchedClassifierFreeGuidanceLogitsProcessor",
+ "WhisperTimeStampLogitsProcessor",
+ "WatermarkLogitsProcessor",
+ ]
+ _import_structure["stopping_criteria"] = [
+ "MaxLengthCriteria",
+ "MaxTimeCriteria",
+ "ConfidenceCriteria",
+ "EosTokenCriteria",
+ "StoppingCriteria",
+ "StoppingCriteriaList",
+ "validate_stopping_criteria",
+ "StopStringCriteria",
+ ]
+ _import_structure["utils"] = [
+ "GenerationMixin",
+ "GreedySearchEncoderDecoderOutput",
+ "GreedySearchDecoderOnlyOutput",
+ "SampleEncoderDecoderOutput",
+ "SampleDecoderOnlyOutput",
+ "BeamSearchEncoderDecoderOutput",
+ "BeamSearchDecoderOnlyOutput",
+ "BeamSampleEncoderDecoderOutput",
+ "BeamSampleDecoderOnlyOutput",
+ "ContrastiveSearchEncoderDecoderOutput",
+ "ContrastiveSearchDecoderOnlyOutput",
+ "GenerateBeamDecoderOnlyOutput",
+ "GenerateBeamEncoderDecoderOutput",
+ "GenerateDecoderOnlyOutput",
+ "GenerateEncoderDecoderOutput",
+ ]
+ _import_structure["watermarking"] = [
+ "WatermarkDetector",
+ "WatermarkDetectorOutput",
+ "BayesianDetectorModel",
+ "BayesianDetectorConfig",
+ "SynthIDTextWatermarkDetector",
+ ]
+
+try:
+ if not is_tf_available():
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ pass
+else:
+ _import_structure["tf_logits_process"] = [
+ "TFForcedBOSTokenLogitsProcessor",
+ "TFForcedEOSTokenLogitsProcessor",
+ "TFForceTokensLogitsProcessor",
+ "TFLogitsProcessor",
+ "TFLogitsProcessorList",
+ "TFLogitsWarper",
+ "TFMinLengthLogitsProcessor",
+ "TFNoBadWordsLogitsProcessor",
+ "TFNoRepeatNGramLogitsProcessor",
+ "TFRepetitionPenaltyLogitsProcessor",
+ "TFSuppressTokensAtBeginLogitsProcessor",
+ "TFSuppressTokensLogitsProcessor",
+ "TFTemperatureLogitsWarper",
+ "TFTopKLogitsWarper",
+ "TFTopPLogitsWarper",
+ ]
+ _import_structure["tf_utils"] = [
+ "TFGenerationMixin",
+ "TFGreedySearchDecoderOnlyOutput",
+ "TFGreedySearchEncoderDecoderOutput",
+ "TFSampleEncoderDecoderOutput",
+ "TFSampleDecoderOnlyOutput",
+ "TFBeamSearchEncoderDecoderOutput",
+ "TFBeamSearchDecoderOnlyOutput",
+ "TFBeamSampleEncoderDecoderOutput",
+ "TFBeamSampleDecoderOnlyOutput",
+ "TFContrastiveSearchEncoderDecoderOutput",
+ "TFContrastiveSearchDecoderOnlyOutput",
+ ]
+
+try:
+ if not is_flax_available():
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ pass
+else:
+ _import_structure["flax_logits_process"] = [
+ "FlaxForcedBOSTokenLogitsProcessor",
+ "FlaxForcedEOSTokenLogitsProcessor",
+ "FlaxForceTokensLogitsProcessor",
+ "FlaxLogitsProcessor",
+ "FlaxLogitsProcessorList",
+ "FlaxLogitsWarper",
+ "FlaxMinLengthLogitsProcessor",
+ "FlaxSuppressTokensAtBeginLogitsProcessor",
+ "FlaxSuppressTokensLogitsProcessor",
+ "FlaxTemperatureLogitsWarper",
+ "FlaxTopKLogitsWarper",
+ "FlaxTopPLogitsWarper",
+ "FlaxWhisperTimeStampLogitsProcessor",
+ "FlaxNoRepeatNGramLogitsProcessor",
+ ]
+ _import_structure["flax_utils"] = [
+ "FlaxGenerationMixin",
+ "FlaxGreedySearchOutput",
+ "FlaxSampleOutput",
+ "FlaxBeamSearchOutput",
+ ]
+
+if TYPE_CHECKING:
+ from .configuration_utils import (
+ BaseWatermarkingConfig,
+ CompileConfig,
+ GenerationConfig,
+ GenerationMode,
+ SynthIDTextWatermarkingConfig,
+ WatermarkingConfig,
+ )
+ from .streamers import AsyncTextIteratorStreamer, BaseStreamer, TextIteratorStreamer, TextStreamer
+
+ try:
+ if not is_torch_available():
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ pass
+ else:
+ from .beam_constraints import Constraint, ConstraintListState, DisjunctiveConstraint, PhrasalConstraint
+ from .beam_search import BeamHypotheses, BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer
+ from .candidate_generator import (
+ AssistedCandidateGenerator,
+ CandidateGenerator,
+ EarlyExitCandidateGenerator,
+ PromptLookupCandidateGenerator,
+ )
+ from .logits_process import (
+ AlternatingCodebooksLogitsProcessor,
+ ClassifierFreeGuidanceLogitsProcessor,
+ EncoderNoRepeatNGramLogitsProcessor,
+ EncoderRepetitionPenaltyLogitsProcessor,
+ EpsilonLogitsWarper,
+ EtaLogitsWarper,
+ ExponentialDecayLengthPenalty,
+ ForcedBOSTokenLogitsProcessor,
+ ForcedEOSTokenLogitsProcessor,
+ HammingDiversityLogitsProcessor,
+ InfNanRemoveLogitsProcessor,
+ LogitNormalization,
+ LogitsProcessor,
+ LogitsProcessorList,
+ MinLengthLogitsProcessor,
+ MinNewTokensLengthLogitsProcessor,
+ MinPLogitsWarper,
+ NoBadWordsLogitsProcessor,
+ NoRepeatNGramLogitsProcessor,
+ PrefixConstrainedLogitsProcessor,
+ RepetitionPenaltyLogitsProcessor,
+ SequenceBiasLogitsProcessor,
+ SuppressTokensAtBeginLogitsProcessor,
+ SuppressTokensLogitsProcessor,
+ SynthIDTextWatermarkLogitsProcessor,
+ TemperatureLogitsWarper,
+ TopKLogitsWarper,
+ TopPLogitsWarper,
+ TypicalLogitsWarper,
+ UnbatchedClassifierFreeGuidanceLogitsProcessor,
+ WatermarkLogitsProcessor,
+ WhisperTimeStampLogitsProcessor,
+ )
+ from .stopping_criteria import (
+ ConfidenceCriteria,
+ EosTokenCriteria,
+ MaxLengthCriteria,
+ MaxTimeCriteria,
+ StoppingCriteria,
+ StoppingCriteriaList,
+ StopStringCriteria,
+ validate_stopping_criteria,
+ )
+ from .utils import (
+ BeamSampleDecoderOnlyOutput,
+ BeamSampleEncoderDecoderOutput,
+ BeamSearchDecoderOnlyOutput,
+ BeamSearchEncoderDecoderOutput,
+ ContrastiveSearchDecoderOnlyOutput,
+ ContrastiveSearchEncoderDecoderOutput,
+ GenerateBeamDecoderOnlyOutput,
+ GenerateBeamEncoderDecoderOutput,
+ GenerateDecoderOnlyOutput,
+ GenerateEncoderDecoderOutput,
+ GenerationMixin,
+ GreedySearchDecoderOnlyOutput,
+ GreedySearchEncoderDecoderOutput,
+ SampleDecoderOnlyOutput,
+ SampleEncoderDecoderOutput,
+ )
+ from .watermarking import (
+ BayesianDetectorConfig,
+ BayesianDetectorModel,
+ SynthIDTextWatermarkDetector,
+ WatermarkDetector,
+ WatermarkDetectorOutput,
+ )
+
+ try:
+ if not is_tf_available():
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ pass
+ else:
+ from .tf_logits_process import (
+ TFForcedBOSTokenLogitsProcessor,
+ TFForcedEOSTokenLogitsProcessor,
+ TFForceTokensLogitsProcessor,
+ TFLogitsProcessor,
+ TFLogitsProcessorList,
+ TFLogitsWarper,
+ TFMinLengthLogitsProcessor,
+ TFNoBadWordsLogitsProcessor,
+ TFNoRepeatNGramLogitsProcessor,
+ TFRepetitionPenaltyLogitsProcessor,
+ TFSuppressTokensAtBeginLogitsProcessor,
+ TFSuppressTokensLogitsProcessor,
+ TFTemperatureLogitsWarper,
+ TFTopKLogitsWarper,
+ TFTopPLogitsWarper,
+ )
+ from .tf_utils import (
+ TFBeamSampleDecoderOnlyOutput,
+ TFBeamSampleEncoderDecoderOutput,
+ TFBeamSearchDecoderOnlyOutput,
+ TFBeamSearchEncoderDecoderOutput,
+ TFContrastiveSearchDecoderOnlyOutput,
+ TFContrastiveSearchEncoderDecoderOutput,
+ TFGenerationMixin,
+ TFGreedySearchDecoderOnlyOutput,
+ TFGreedySearchEncoderDecoderOutput,
+ TFSampleDecoderOnlyOutput,
+ TFSampleEncoderDecoderOutput,
+ )
+
+ try:
+ if not is_flax_available():
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ pass
+ else:
+ from .flax_logits_process import (
+ FlaxForcedBOSTokenLogitsProcessor,
+ FlaxForcedEOSTokenLogitsProcessor,
+ FlaxForceTokensLogitsProcessor,
+ FlaxLogitsProcessor,
+ FlaxLogitsProcessorList,
+ FlaxLogitsWarper,
+ FlaxMinLengthLogitsProcessor,
+ FlaxNoRepeatNGramLogitsProcessor,
+ FlaxSuppressTokensAtBeginLogitsProcessor,
+ FlaxSuppressTokensLogitsProcessor,
+ FlaxTemperatureLogitsWarper,
+ FlaxTopKLogitsWarper,
+ FlaxTopPLogitsWarper,
+ FlaxWhisperTimeStampLogitsProcessor,
+ )
+ from .flax_utils import FlaxBeamSearchOutput, FlaxGenerationMixin, FlaxGreedySearchOutput, FlaxSampleOutput
+else:
+ import sys
+
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/beam_constraints.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/beam_constraints.py
new file mode 100644
index 0000000000000000000000000000000000000000..daf64209b796772ac5c8da0dc139d944c2e82430
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/beam_constraints.py
@@ -0,0 +1,524 @@
+from abc import ABC, abstractmethod
+from typing import List, Optional
+
+
+class Constraint(ABC):
+ r"""Abstract base class for all constraints that can be applied during generation.
+ It must define how the constraint can be satisfied.
+
+ All classes that inherit Constraint must follow the requirement that
+
+ ```py
+ completed = False
+ while not completed:
+ _, completed = constraint.update(constraint.advance())
+ ```
+
+ will always terminate (halt).
+ """
+
+ def __init__(self):
+ # test for the above condition
+ self.test()
+
+ def test(self):
+ """
+ Tests whether this constraint has been properly defined.
+ """
+ counter = 0
+ completed = False
+ while not completed:
+ if counter == 1:
+ self.reset()
+ advance = self.advance()
+ if not self.does_advance(advance):
+ raise Exception(
+ "Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true."
+ )
+
+ stepped, completed, reset = self.update(advance)
+ counter += 1
+
+ if counter > 10000:
+ raise Exception("update() does not fulfill the constraint.")
+
+ if self.remaining() != 0:
+ raise Exception("Custom Constraint is not defined correctly.")
+
+ @abstractmethod
+ def advance(self):
+ """
+ When called, returns the token(s) that would take this constraint one step closer to being fulfilled.
+
+ Return:
+ token_ids (Union[int, List[int], None]):
+ - A single token ID (int) that advances the constraint, or
+ - A list of token IDs that could advance the constraint
+ - None if the constraint is completed or cannot be advanced
+ """
+ raise NotImplementedError(
+ f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
+ )
+
+ @abstractmethod
+ def does_advance(self, token_id: int):
+ """
+ Reads in a token and returns whether it creates progress.
+ """
+ raise NotImplementedError(
+ f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
+ )
+
+ @abstractmethod
+ def update(self, token_id: int):
+ """
+ Reads in a token and returns booleans that indicate the progress made by it. This function will update the
+ state of this object unlikes `does_advance(self, token_id: int)`.
+
+ This isn't to test whether a certain token will advance the progress; it's to update its state as if it has
+ been generated. This becomes important if token_id != desired token (refer to else statement in
+ PhrasalConstraint)
+
+ Args:
+ token_id(`int`):
+ The id of a newly generated token in the beam search.
+ Return:
+ stepped(`bool`):
+ Whether this constraint has become one step closer to being fulfuilled.
+ completed(`bool`):
+ Whether this constraint has been completely fulfilled by this token being generated.
+ reset (`bool`):
+ Whether this constraint has reset its progress by this token being generated.
+ """
+ raise NotImplementedError(
+ f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
+ )
+
+ @abstractmethod
+ def reset(self):
+ """
+ Resets the state of this constraint to its initialization. We would call this in cases where the fulfillment of
+ a constraint is abrupted by an unwanted token.
+ """
+ raise NotImplementedError(
+ f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
+ )
+
+ @abstractmethod
+ def remaining(self):
+ """
+ Returns the number of remaining steps of `advance()` in order to complete this constraint.
+ """
+ raise NotImplementedError(
+ f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
+ )
+
+ @abstractmethod
+ def copy(self, stateful=False):
+ """
+ Creates a new instance of this constraint.
+
+ Args:
+ stateful(`bool`): Whether to not only copy the constraint for new instance, but also its state.
+
+ Return:
+ constraint(`Constraint`): The same constraint as the one being called from.
+ """
+ raise NotImplementedError(
+ f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
+ )
+
+
+class PhrasalConstraint(Constraint):
+ r"""
+ [`Constraint`] enforcing that an ordered sequence of tokens is included in the output.
+
+ Args:
+ token_ids (`List[int]`):
+ The id of the token that must be generated by the output.
+ """
+
+ def __init__(self, token_ids: List[int]):
+ super(Constraint, self).__init__()
+
+ if not isinstance(token_ids, list) or len(token_ids) == 0:
+ raise ValueError(f"`token_ids` has to be a non-empty list, but is {token_ids}.")
+ if any((not isinstance(token_id, int) or token_id < 0) for token_id in token_ids):
+ raise ValueError(f"Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.")
+
+ self.token_ids = token_ids
+
+ self.seqlen = len(self.token_ids)
+ self.fulfilled_idx = -1 # the index of the currently fulfilled step
+ self.completed = False
+
+ def advance(self):
+ if self.completed:
+ return None
+ return self.token_ids[self.fulfilled_idx + 1]
+
+ def does_advance(self, token_id: int):
+ if not isinstance(token_id, int):
+ raise TypeError(f"`token_id` has to be an `int`, but is {token_id} of type {type(token_id)}")
+
+ if self.completed:
+ return False
+
+ return token_id == self.token_ids[self.fulfilled_idx + 1]
+
+ def update(self, token_id: int):
+ if not isinstance(token_id, int):
+ raise TypeError(f"`token_id` has to be an `int`, but is {token_id} of type {type(token_id)}")
+
+ stepped = False
+ completed = False
+ reset = False
+
+ if self.does_advance(token_id):
+ self.fulfilled_idx += 1
+ stepped = True
+ if self.fulfilled_idx == (self.seqlen - 1):
+ completed = True
+ self.completed = completed
+ else:
+ # failed to make progress.
+ reset = True
+ self.reset()
+ return stepped, completed, reset
+
+ def reset(self):
+ self.completed = False
+ self.fulfilled_idx = 0
+
+ def remaining(self):
+ return self.seqlen - (self.fulfilled_idx + 1)
+
+ def copy(self, stateful=False):
+ new_constraint = PhrasalConstraint(self.token_ids)
+
+ if stateful:
+ new_constraint.seq_len = self.seqlen
+ new_constraint.fulfilled_idx = self.fulfilled_idx
+ new_constraint.completed = self.completed
+
+ return new_constraint
+
+
+class DisjunctiveTrie:
+ def __init__(self, nested_token_ids: List[List[int]], no_subsets=True):
+ r"""
+ A helper class that builds a trie with the words represented in `nested_token_ids`.
+ """
+ self.max_height = max([len(one) for one in nested_token_ids])
+
+ root = {}
+ for token_ids in nested_token_ids:
+ level = root
+ for tidx, token_id in enumerate(token_ids):
+ if token_id not in level:
+ level[token_id] = {}
+
+ level = level[token_id]
+
+ if no_subsets and self.has_subsets(root, nested_token_ids):
+ raise ValueError(
+ "Each list in `nested_token_ids` can't be a complete subset of another list, but is"
+ f" {nested_token_ids}."
+ )
+
+ self.trie = root
+
+ def next_tokens(self, current_seq):
+ """
+ The next possible tokens that will progress the trie, given the current sequence of tokens in `current_seq`.
+ """
+ start = self.trie
+
+ for current_token in current_seq:
+ start = start[current_token]
+
+ next_tokens = list(start.keys())
+
+ return next_tokens
+
+ def reached_leaf(self, current_seq):
+ next_tokens = self.next_tokens(current_seq)
+
+ return len(next_tokens) == 0
+
+ def count_leaves(self, root):
+ next_nodes = list(root.values())
+ if len(next_nodes) == 0:
+ return 1
+ else:
+ return sum([self.count_leaves(nn) for nn in next_nodes])
+
+ def has_subsets(self, trie, nested_token_ids):
+ """
+ Returns whether # of leaves == # of words. Otherwise some word is a subset of another.
+ """
+ leaf_count = self.count_leaves(trie)
+ return len(nested_token_ids) != leaf_count
+
+
+class DisjunctiveConstraint(Constraint):
+ r"""
+ A special [`Constraint`] that is fulfilled by fulfilling just one of several constraints.
+
+ Args:
+ nested_token_ids (`List[List[int]]`):
+ A list of words, where each word is a list of ids. This constraint is fulfilled by generating just one from
+ the list of words.
+ """
+
+ def __init__(self, nested_token_ids: List[List[int]]):
+ super(Constraint, self).__init__()
+
+ if not isinstance(nested_token_ids, list) or len(nested_token_ids) == 0:
+ raise ValueError(f"`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.")
+ if any(not isinstance(token_ids, list) for token_ids in nested_token_ids):
+ raise ValueError(f"`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.")
+ if any(
+ any((not isinstance(token_id, int) or token_id < 0) for token_id in token_ids)
+ for token_ids in nested_token_ids
+ ):
+ raise ValueError(
+ f"Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}."
+ )
+
+ self.trie = DisjunctiveTrie(nested_token_ids)
+ self.token_ids = nested_token_ids
+
+ self.seqlen = self.trie.max_height
+ self.current_seq = []
+ self.completed = False
+
+ def advance(self):
+ token_list = self.trie.next_tokens(self.current_seq)
+
+ if len(token_list) == 0:
+ return None
+ else:
+ return token_list
+
+ def does_advance(self, token_id: int):
+ if not isinstance(token_id, int):
+ raise TypeError(f"`token_id` is supposed to be type `int`, but is {token_id} of type {type(token_id)}")
+
+ next_tokens = self.trie.next_tokens(self.current_seq)
+
+ return token_id in next_tokens
+
+ def update(self, token_id: int):
+ if not isinstance(token_id, int):
+ raise TypeError(f"`token_id` is supposed to be type `int`, but is {token_id} of type {type(token_id)}")
+
+ stepped = False
+ completed = False
+ reset = False
+
+ if self.does_advance(token_id):
+ self.current_seq.append(token_id)
+ stepped = True
+ else:
+ reset = True
+ self.reset()
+
+ completed = self.trie.reached_leaf(self.current_seq)
+ self.completed = completed
+
+ return stepped, completed, reset
+
+ def reset(self):
+ self.completed = False
+ self.current_seq = []
+
+ def remaining(self):
+ if self.completed:
+ # since this can be completed without reaching max height
+ return 0
+ else:
+ return self.seqlen - len(self.current_seq)
+
+ def copy(self, stateful=False):
+ new_constraint = DisjunctiveConstraint(self.token_ids)
+
+ if stateful:
+ new_constraint.seq_len = self.seqlen
+ new_constraint.current_seq = self.current_seq
+ new_constraint.completed = self.completed
+
+ return new_constraint
+
+
+class ConstraintListState:
+ r"""
+ A class for beam scorers to track its progress through a list of constraints.
+
+ Args:
+ constraints (`List[Constraint]`):
+ A list of [`Constraint`] objects that must be fulfilled by the beam scorer.
+ """
+
+ def __init__(self, constraints: List[Constraint]):
+ self.constraints = constraints
+
+ # max # of steps required to fulfill a given constraint
+ self.max_seqlen = max([c.seqlen for c in constraints])
+ self.n_constraints = len(constraints)
+ self.completed = False
+
+ self.init_state()
+
+ def init_state(self):
+ self.complete_constraints = []
+ self.inprogress_constraint = None
+ self.pending_constraints = [constraint.copy(stateful=False) for constraint in self.constraints]
+
+ def get_bank(self):
+ add = 0
+ if self.inprogress_constraint:
+ # extra points for having a constraint mid-fulfilled
+ add += self.max_seqlen - self.inprogress_constraint.remaining()
+
+ return (len(self.complete_constraints) * self.max_seqlen) + add
+
+ def advance(self):
+ """The list of tokens to generate such that we can make progress.
+ By "list" we don't mean the list of token that will fully fulfill a constraint.
+
+ Given constraints `c_i = {t_ij | j == # of tokens}`, If we're not in the middle of progressing through a
+ specific constraint `c_i`, we return:
+
+ `[t_k1 for k in indices of unfulfilled constraints]`
+
+ If we are in the middle of a constraint, then we return:
+ `[t_ij]`, where `i` is the index of the inprogress constraint, `j` is the next step for the constraint.
+
+ Though we don't care which constraint is fulfilled first, if we are in the progress of fulfilling a constraint,
+ that's the only one we'll return.
+ """
+ token_list = []
+ if self.inprogress_constraint is None:
+ for constraint in self.pending_constraints: # "pending" == "unfulfilled yet"
+ advance = constraint.advance()
+ if isinstance(advance, int):
+ token_list.append(advance)
+ elif isinstance(advance, list):
+ token_list.extend(advance)
+ else:
+ advance = self.inprogress_constraint.advance()
+ if isinstance(advance, int):
+ token_list.append(advance)
+ elif isinstance(advance, list):
+ token_list.extend(advance)
+
+ if len(token_list) == 0:
+ return None
+ else:
+ return token_list
+
+ def reset(self, token_ids: Optional[List[int]]):
+ """
+ token_ids: the tokens generated thus far to reset the state of the progress through constraints.
+ """
+ self.init_state()
+
+ if token_ids is not None:
+ for token in token_ids:
+ # completes or steps **one** constraint
+ complete, stepped = self.add(token)
+
+ # the entire list of constraints are fulfilled
+ if self.completed:
+ break
+
+ def add(self, token_id: int):
+ if not isinstance(token_id, int):
+ raise TypeError(f"`token_id` should be an `int`, but is `{token_id}`.")
+
+ complete, stepped = False, False
+
+ if self.completed:
+ complete = True
+ stepped = False
+ return complete, stepped
+
+ if self.inprogress_constraint is not None:
+ # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
+ # job, simply update the state
+
+ stepped, complete, reset = self.inprogress_constraint.update(token_id)
+ if reset:
+ # 1. If the next token breaks the progress, then we must restart.
+ # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".
+
+ # But that doesn't mean we self.init_state(), since we only reset the state for this particular
+ # constraint, not the full list of constraints.
+
+ self.pending_constraints.append(self.inprogress_constraint.copy(stateful=False))
+ self.inprogress_constraint = None
+
+ if complete:
+ # 2. If the next token completes the constraint, move it to completed list, set
+ # inprogress to None. If there are no pending constraints either, then this full list of constraints
+ # is complete.
+
+ self.complete_constraints.append(self.inprogress_constraint)
+ self.inprogress_constraint = None
+
+ if len(self.pending_constraints) == 0:
+ # we're done!
+ self.completed = True
+
+ else:
+ # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
+ # of constraints?
+
+ for cidx, pending_constraint in enumerate(self.pending_constraints):
+ if pending_constraint.does_advance(token_id):
+ stepped, complete, reset = pending_constraint.update(token_id)
+
+ if not stepped:
+ raise Exception(
+ "`constraint.update(token_id)` is not yielding incremental progress, "
+ "even though `constraint.does_advance(token_id)` is true."
+ )
+
+ if complete:
+ self.complete_constraints.append(pending_constraint)
+ self.inprogress_constraint = None
+
+ if not complete and stepped:
+ self.inprogress_constraint = pending_constraint
+
+ if complete or stepped:
+ # If we made any progress at all, then it's at least not a "pending constraint".
+
+ self.pending_constraints = (
+ self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
+ )
+
+ if len(self.pending_constraints) == 0 and self.inprogress_constraint is None:
+ # If there's no longer any pending after this and no inprogress either, then we must be
+ # complete.
+
+ self.completed = True
+
+ break # prevent accidentally stepping through multiple constraints with just one token.
+
+ return complete, stepped
+
+ def copy(self, stateful=True):
+ new_state = ConstraintListState(self.constraints) # we actually never though self.constraints objects
+ # throughout this process. So it's at initialization state.
+
+ if stateful:
+ new_state.complete_constraints = [
+ constraint.copy(stateful=True) for constraint in self.complete_constraints
+ ]
+ if self.inprogress_constraint is not None:
+ new_state.inprogress_constraint = self.inprogress_constraint.copy(stateful=True)
+ new_state.pending_constraints = [constraint.copy() for constraint in self.pending_constraints]
+
+ return new_state
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/beam_search.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/beam_search.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e4f13ad1e15c64718f153c740b827ee5f2b6a65
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/beam_search.py
@@ -0,0 +1,1013 @@
+# coding=utf-8
+# Copyright 2020 The HuggingFace Inc. team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from abc import ABC, abstractmethod
+from collections import UserDict
+from typing import Dict, List, Optional, Tuple, Union
+
+import numpy as np
+import torch
+
+from ..utils import add_start_docstrings
+from .beam_constraints import Constraint, ConstraintListState
+
+
+PROCESS_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size * num_beams, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using any class inheriting from [`PreTrainedTokenizer`]. See
+ [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ next_scores (`torch.FloatTensor` of shape `(batch_size, 2 * num_beams)`):
+ Current scores of the top `2 * num_beams` non-finished beam hypotheses.
+ next_tokens (`torch.LongTensor` of shape `(batch_size, 2 * num_beams)`):
+ `input_ids` of the tokens corresponding to the top `2 * num_beams` non-finished beam hypotheses.
+ next_indices (`torch.LongTensor` of shape `(batch_size, 2 * num_beams)`):
+ Beam indices indicating to which beam hypothesis the `next_tokens` correspond.
+ pad_token_id (`int`, *optional*):
+ The id of the *padding* token.
+ eos_token_id (`Union[int, List[int]]`, *optional*):
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
+ beam_indices (`torch.LongTensor`, *optional*):
+ Beam indices indicating to which beam hypothesis each token correspond.
+ group_index (`int`, *optional*):
+ The index of the group of beams. Used with [`~PreTrainedModel.group_beam_search`].
+
+ Return:
+ `UserDict`: A dictionary composed of the fields as defined above:
+
+ - **next_beam_scores** (`torch.FloatTensor` of shape `(batch_size * num_beams)`) -- Updated scores of all
+ non-finished beams.
+ - **next_beam_tokens** (`torch.FloatTensor` of shape `(batch_size * num_beams)`) -- Next tokens to be added
+ to the non-finished beam_hypotheses.
+ - **next_beam_indices** (`torch.FloatTensor` of shape `(batch_size * num_beams)`) -- Beam indices
+ indicating to which beam the next tokens shall be added.
+
+"""
+
+FINALIZE_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size * num_beams, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using any class inheriting from [`PreTrainedTokenizer`]. See
+ [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ final_beam_scores (`torch.FloatTensor` of shape `(batch_size * num_beams)`):
+ The final scores of all non-finished beams.
+ final_beam_tokens (`torch.FloatTensor` of shape `(batch_size * num_beams)`):
+ The last tokens to be added to the non-finished beam_hypotheses.
+ final_beam_indices (`torch.FloatTensor` of shape `(batch_size * num_beams)`):
+ The beam indices indicating to which beam the `final_beam_tokens` shall be added.
+ pad_token_id (`int`, *optional*):
+ The id of the *padding* token.
+ eos_token_id (`Union[int, List[int]]`, *optional*):
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
+
+ Return:
+ `torch.LongTensor` of shape `(batch_size * num_return_sequences, sequence_length)`: The generated sequences.
+ The second dimension (sequence_length) is either equal to `max_length` or shorter if all batches finished early
+ due to the `eos_token_id`.
+
+"""
+
+
+class BeamScorer(ABC):
+ """
+ Abstract base class for all beam scorers that are used for [`~PreTrainedModel.beam_search`] and
+ [`~PreTrainedModel.beam_sample`].
+ """
+
+ @abstractmethod
+ @add_start_docstrings(PROCESS_INPUTS_DOCSTRING)
+ def process(
+ self,
+ input_ids: torch.LongTensor,
+ next_scores: torch.FloatTensor,
+ next_tokens: torch.LongTensor,
+ next_indices: torch.LongTensor,
+ **kwargs,
+ ) -> Tuple[torch.Tensor]:
+ raise NotImplementedError("This is an abstract method.")
+
+ @abstractmethod
+ @add_start_docstrings(FINALIZE_INPUTS_DOCSTRING)
+ def finalize(
+ self,
+ input_ids: torch.LongTensor,
+ next_scores: torch.FloatTensor,
+ next_tokens: torch.LongTensor,
+ next_indices: torch.LongTensor,
+ max_length: int,
+ **kwargs,
+ ) -> torch.LongTensor:
+ raise NotImplementedError("This is an abstract method.")
+
+
+class BeamSearchScorer(BeamScorer):
+ r"""
+ [`BeamScorer`] implementing standard beam search decoding.
+
+ Adapted in part from [Facebook's XLM beam search
+ code](https://github.com/facebookresearch/XLM/blob/9e6f6814d17be4fe5b15f2e6c43eb2b2d76daeb4/src/model/transformer.py#L529).
+
+ Reference for the diverse beam search algorithm and implementation [Ashwin Kalyan's DBS
+ implementation](https://github.com/ashwinkalyan/dbs/blob/master/dbs/beam_utils.lua)
+
+ Args:
+ batch_size (`int`):
+ Batch Size of `input_ids` for which standard beam search decoding is run in parallel.
+ num_beams (`int`):
+ Number of beams for beam search.
+ device (`torch.device`):
+ Defines the device type (*e.g.*, `"cpu"` or `"cuda"`) on which this instance of `BeamSearchScorer` will be
+ allocated.
+ length_penalty (`float`, *optional*, defaults to 1.0):
+ Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to
+ the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log
+ likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while
+ `length_penalty` < 0.0 encourages shorter sequences.
+ do_early_stopping (`bool` or `str`, *optional*, defaults to `False`):
+ Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:
+ `True`, where the generation stops as soon as there are `num_beams` complete candidates; `False`, where an
+ heuristic is applied and the generation stops when is it very unlikely to find better candidates;
+ `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical
+ beam search algorithm).
+ num_beam_hyps_to_keep (`int`, *optional*, defaults to 1):
+ The number of beam hypotheses that shall be returned upon calling
+ [`~transformers.BeamSearchScorer.finalize`].
+ num_beam_groups (`int`, *optional*, defaults to 1):
+ Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams.
+ See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
+ max_length (`int`, *optional*):
+ The maximum length of the sequence to be generated.
+ """
+
+ def __init__(
+ self,
+ batch_size: int,
+ num_beams: int,
+ device: torch.device,
+ length_penalty: Optional[float] = 1.0,
+ do_early_stopping: Optional[Union[bool, str]] = False,
+ num_beam_hyps_to_keep: Optional[int] = 1,
+ num_beam_groups: Optional[int] = 1,
+ max_length: Optional[int] = None,
+ ):
+ self.num_beams = num_beams
+ self.device = device
+ self.length_penalty = length_penalty
+ self.do_early_stopping = do_early_stopping
+ self.num_beam_hyps_to_keep = num_beam_hyps_to_keep
+ self.num_beam_groups = num_beam_groups
+ self.group_size = self.num_beams // self.num_beam_groups
+
+ self._is_init = False
+ # self._beam_hyps[i*self.num_beam_groups+j] is the beam_hyps of the j-th group in the i-th mini-batch.
+ # If group_beam_search is not used, the list consists of `batch_size` beam_hyps.
+ self._beam_hyps = [
+ BeamHypotheses(
+ num_beams=self.group_size,
+ length_penalty=self.length_penalty,
+ early_stopping=self.do_early_stopping,
+ max_length=max_length,
+ )
+ for _ in range(batch_size * self.num_beam_groups)
+ ]
+ # self._done[i*self.num_beam_groups+j] indicates whether the generation of the beam_hyps of the j-th group
+ # in the i-th mini-batch is complete.
+ self._done = torch.tensor(
+ [False for _ in range(batch_size * self.num_beam_groups)], dtype=torch.bool, device=self.device
+ )
+
+ if not isinstance(num_beams, int) or num_beams <= 1:
+ raise ValueError(
+ f"`num_beams` has to be an integer strictly greater than 1, but is {num_beams}. For `num_beams` == 1,"
+ " one should make use of `greedy_search` instead."
+ )
+
+ if not isinstance(num_beam_groups, int) or (num_beam_groups > num_beams) or (num_beams % num_beam_groups != 0):
+ raise ValueError(
+ "`num_beam_groups` has to be an integer smaller or equal than `num_beams` and `num_beams` has to be"
+ f" divisible by `num_beam_groups`, but is {num_beam_groups} with `num_beams` being {num_beams}."
+ )
+
+ @property
+ def is_done(self) -> bool:
+ return self._done.all()
+
+ def process(
+ self,
+ input_ids: torch.LongTensor,
+ next_scores: torch.FloatTensor,
+ next_tokens: torch.LongTensor,
+ next_indices: torch.LongTensor,
+ pad_token_id: Optional[Union[int, torch.Tensor]] = None,
+ eos_token_id: Optional[Union[int, List[int], torch.Tensor]] = None,
+ beam_indices: Optional[torch.LongTensor] = None,
+ group_index: Optional[int] = 0,
+ decoder_prompt_len: Optional[int] = 0,
+ ) -> Dict[str, torch.Tensor]:
+ # add up to the length which the next_scores is calculated on (including decoder prompt)
+ cur_len = input_ids.shape[-1] + 1
+ batch_size = len(self._beam_hyps) // self.num_beam_groups
+
+ if not (batch_size == (input_ids.shape[0] // self.group_size)):
+ if self.num_beam_groups > 1:
+ raise ValueError(
+ f"A group beam size of {input_ids.shape[0]} is used as the input, but a group beam "
+ f"size of {self.group_size} is expected by the beam scorer."
+ )
+ else:
+ raise ValueError(
+ f"A beam size of {input_ids.shape[0]} is used as the input, but a beam size of "
+ f"{self.group_size} is expected by the beam scorer."
+ )
+
+ device = input_ids.device
+ next_beam_scores = torch.zeros((batch_size, self.group_size), dtype=next_scores.dtype, device=device)
+ next_beam_tokens = torch.zeros((batch_size, self.group_size), dtype=next_tokens.dtype, device=device)
+ next_beam_indices = torch.zeros((batch_size, self.group_size), dtype=next_indices.dtype, device=device)
+
+ if eos_token_id is not None and not isinstance(eos_token_id, torch.Tensor):
+ if isinstance(eos_token_id, int):
+ eos_token_id = [eos_token_id]
+ eos_token_id = torch.tensor(eos_token_id)
+
+ for batch_idx in range(batch_size):
+ batch_group_idx = batch_idx * self.num_beam_groups + group_index
+ if self._done[batch_group_idx]:
+ if self.num_beams < len(self._beam_hyps[batch_group_idx]):
+ raise ValueError(f"Batch can only be done if at least {self.num_beams} beams have been generated")
+ if eos_token_id is None or pad_token_id is None:
+ raise ValueError("Generated beams >= num_beams -> eos_token_id and pad_token have to be defined")
+ # pad the batch
+ next_beam_scores[batch_idx, :] = 0
+ next_beam_tokens[batch_idx, :] = pad_token_id
+ next_beam_indices[batch_idx, :] = 0
+ continue
+
+ # next tokens for this sentence
+ beam_idx = 0
+ for beam_token_rank, (next_token, next_score, next_index) in enumerate(
+ zip(next_tokens[batch_idx], next_scores[batch_idx], next_indices[batch_idx])
+ ):
+ batch_beam_idx = batch_idx * self.group_size + next_index
+ # add to generated hypotheses if end of sentence
+ if (eos_token_id is not None) and (next_token.item() in eos_token_id):
+ # if beam_token does not belong to top num_beams tokens, it should not be added
+ is_beam_token_worse_than_top_num_beams = beam_token_rank >= self.group_size
+ if is_beam_token_worse_than_top_num_beams:
+ continue
+ if beam_indices is not None:
+ beam_index = beam_indices[batch_beam_idx]
+ beam_index = beam_index + (batch_beam_idx,)
+ else:
+ beam_index = None
+
+ self._beam_hyps[batch_group_idx].add(
+ input_ids[batch_beam_idx].clone(),
+ next_score.item(),
+ beam_indices=beam_index,
+ generated_len=cur_len - decoder_prompt_len,
+ )
+ else:
+ # add next predicted token since it is not eos_token
+ next_beam_scores[batch_idx, beam_idx] = next_score
+ next_beam_tokens[batch_idx, beam_idx] = next_token
+ next_beam_indices[batch_idx, beam_idx] = batch_beam_idx
+ beam_idx += 1
+
+ # once the beam for next step is full, don't add more tokens to it.
+ if beam_idx == self.group_size:
+ break
+
+ if beam_idx < self.group_size:
+ raise ValueError(
+ f"At most {self.group_size} tokens in {next_tokens[batch_idx]} can be equal to `eos_token_id:"
+ f" {eos_token_id}`. Make sure {next_tokens[batch_idx]} are corrected."
+ )
+
+ # Check if we are done so that we can save a pad step if all(done)
+ self._done[batch_group_idx] = self._done[batch_group_idx] or self._beam_hyps[batch_group_idx].is_done(
+ next_scores[batch_idx].max().item(), cur_len, decoder_prompt_len
+ )
+
+ return UserDict(
+ {
+ "next_beam_scores": next_beam_scores.view(-1),
+ "next_beam_tokens": next_beam_tokens.view(-1),
+ "next_beam_indices": next_beam_indices.view(-1),
+ }
+ )
+
+ def finalize(
+ self,
+ input_ids: torch.LongTensor,
+ final_beam_scores: torch.FloatTensor,
+ final_beam_tokens: torch.LongTensor,
+ final_beam_indices: torch.LongTensor,
+ max_length: int,
+ pad_token_id: Optional[Union[int, torch.Tensor]] = None,
+ eos_token_id: Optional[Union[int, List[int], torch.Tensor]] = None,
+ beam_indices: Optional[torch.LongTensor] = None,
+ decoder_prompt_len: Optional[int] = 0,
+ ) -> Tuple[torch.LongTensor]:
+ batch_size = len(self._beam_hyps) // self.num_beam_groups
+
+ if eos_token_id is not None and not isinstance(eos_token_id, torch.Tensor):
+ if isinstance(eos_token_id, int):
+ eos_token_id = [eos_token_id]
+ eos_token_id = torch.tensor(eos_token_id)
+
+ # finalize all open beam hypotheses and add to generated hypotheses
+ for batch_group_idx, beam_hyp in enumerate(self._beam_hyps):
+ if self._done[batch_group_idx]:
+ continue
+
+ # all open beam hypotheses are added to the beam hypothesis
+ # beam hypothesis class automatically keeps the best beams
+ for index_per_group in range(self.group_size):
+ batch_beam_idx = batch_group_idx * self.group_size + index_per_group
+ final_score = final_beam_scores[batch_beam_idx].item()
+ final_tokens = input_ids[batch_beam_idx]
+ beam_index = beam_indices[batch_beam_idx] if beam_indices is not None else None
+ generated_len = final_tokens.shape[-1] - decoder_prompt_len
+ beam_hyp.add(final_tokens, final_score, beam_indices=beam_index, generated_len=generated_len)
+
+ # select the best hypotheses
+ sent_lengths = input_ids.new(batch_size * self.num_beam_hyps_to_keep)
+ best = []
+ best_indices = []
+ best_scores = torch.zeros(batch_size * self.num_beam_hyps_to_keep, device=self.device, dtype=torch.float32)
+
+ # retrieve best hypotheses
+ for i in range(batch_size):
+ beam_hyps_in_batch = self._beam_hyps[i * self.num_beam_groups : (i + 1) * self.num_beam_groups]
+ candidate_beams = [beam for beam_hyp in beam_hyps_in_batch for beam in beam_hyp.beams]
+ sorted_hyps = sorted(candidate_beams, key=lambda x: x[0])
+ for j in range(self.num_beam_hyps_to_keep):
+ best_hyp_tuple = sorted_hyps.pop()
+ best_score = best_hyp_tuple[0]
+ best_hyp = best_hyp_tuple[1]
+ best_index = best_hyp_tuple[2]
+ sent_lengths[self.num_beam_hyps_to_keep * i + j] = len(best_hyp)
+
+ # append hyp to lists
+ best.append(best_hyp)
+
+ # append indices to list
+ best_indices.append(best_index)
+
+ best_scores[i * self.num_beam_hyps_to_keep + j] = best_score
+
+ # prepare for adding eos
+ sent_lengths_max = sent_lengths.max().item() + 1
+ sent_max_len = min(sent_lengths_max, max_length) if max_length is not None else sent_lengths_max
+ decoded: torch.LongTensor = input_ids.new(batch_size * self.num_beam_hyps_to_keep, sent_max_len)
+
+ if len(best_indices) > 0 and best_indices[0] is not None:
+ indices: torch.LongTensor = input_ids.new(batch_size * self.num_beam_hyps_to_keep, sent_max_len)
+ else:
+ indices = None
+
+ # shorter batches are padded if needed
+ if sent_lengths.min().item() != sent_lengths.max().item():
+ if pad_token_id is None:
+ raise ValueError("`pad_token_id` has to be defined")
+ decoded.fill_(pad_token_id)
+
+ if indices is not None:
+ indices.fill_(-1)
+
+ # fill with hypotheses and eos_token_id if the latter fits in
+ for i, (hypo, best_idx) in enumerate(zip(best, best_indices)):
+ decoded[i, : sent_lengths[i]] = hypo
+
+ if indices is not None:
+ indices[i, : len(best_idx)] = torch.tensor(best_idx)
+
+ if sent_lengths[i] < sent_max_len:
+ # inserting only the first eos_token_id
+ decoded[i, sent_lengths[i]] = eos_token_id[0]
+
+ return UserDict(
+ {
+ "sequences": decoded,
+ "sequence_scores": best_scores,
+ "beam_indices": indices,
+ }
+ )
+
+
+class ConstrainedBeamSearchScorer(BeamScorer):
+ r"""
+ [`BeamScorer`] implementing constrained beam search decoding.
+
+
+ Args:
+ batch_size (`int`):
+ Batch Size of `input_ids` for which standard beam search decoding is run in parallel.
+ num_beams (`int`):
+ Number of beams for beam search.
+ constraints (`List[Constraint]`):
+ A list of positive constraints represented as `Constraint` objects that must be fulfilled in the generation
+ output. For more information, the documentation of [`Constraint`] should be read.
+ device (`torch.device`):
+ Defines the device type (*e.g.*, `"cpu"` or `"cuda"`) on which this instance of `BeamSearchScorer` will be
+ allocated.
+ length_penalty (`float`, *optional*, defaults to 1.0):
+ Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to
+ the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log
+ likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while
+ `length_penalty` < 0.0 encourages shorter sequences.
+ do_early_stopping (`bool` or `str`, *optional*, defaults to `False`):
+ Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:
+ `True`, where the generation stops as soon as there are `num_beams` complete candidates; `False`, where an
+ heuristic is applied and the generation stops when is it very unlikely to find better candidates;
+ `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical
+ beam search algorithm).
+ num_beam_hyps_to_keep (`int`, *optional*, defaults to 1):
+ The number of beam hypotheses that shall be returned upon calling
+ [`~transformers.BeamSearchScorer.finalize`].
+ num_beam_groups (`int`, *optional*, defaults to 1):
+ Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams.
+ See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
+ max_length (`int`, *optional*):
+ The maximum length of the sequence to be generated.
+ """
+
+ def __init__(
+ self,
+ batch_size: int,
+ num_beams: int,
+ constraints: List[Constraint],
+ device: torch.device,
+ length_penalty: Optional[float] = 1.0,
+ do_early_stopping: Optional[Union[bool, str]] = False,
+ num_beam_hyps_to_keep: Optional[int] = 1,
+ num_beam_groups: Optional[int] = 1,
+ max_length: Optional[int] = None,
+ ):
+ self.num_beams = num_beams
+ self.device = device
+ self.length_penalty = length_penalty
+ self.do_early_stopping = do_early_stopping
+ self.num_beam_hyps_to_keep = num_beam_hyps_to_keep
+ self.num_beam_groups = num_beam_groups
+ self.group_size = self.num_beams // self.num_beam_groups
+ self.constraints = constraints
+
+ self._is_init = False
+ self._beam_hyps = [
+ BeamHypotheses(
+ num_beams=self.num_beams,
+ length_penalty=self.length_penalty,
+ early_stopping=self.do_early_stopping,
+ max_length=max_length,
+ )
+ for _ in range(batch_size)
+ ]
+ self._done = torch.tensor([False for _ in range(batch_size)], dtype=torch.bool, device=self.device)
+
+ if not isinstance(num_beams, int) or num_beams <= 1:
+ raise ValueError(
+ f"`num_beams` has to be an integer strictly greater than 1, but is {num_beams}. For `num_beams` == 1,"
+ " one should make use of `greedy_search` instead."
+ )
+
+ if not isinstance(num_beam_groups, int) or (num_beam_groups > num_beams) or (num_beams % num_beam_groups != 0):
+ raise ValueError(
+ "`num_beam_groups` has to be an integer smaller or equal than `num_beams` and `num_beams` has to be"
+ f" divisible by `num_beam_groups`, but is {num_beam_groups} with `num_beams` being {num_beams}."
+ )
+
+ @property
+ def is_done(self) -> bool:
+ return self._done.all()
+
+ def make_constraint_states(self, n):
+ return [ConstraintListState([constraint.copy() for constraint in self.constraints]) for _ in range(n)]
+
+ def check_completes_constraints(self, sequence):
+ new_state = self.make_constraint_states(1)[0]
+ new_state.reset(sequence)
+ return new_state.completed
+
+ def process(
+ self,
+ input_ids: torch.LongTensor,
+ next_scores: torch.FloatTensor,
+ next_tokens: torch.LongTensor,
+ next_indices: torch.LongTensor,
+ scores_for_all_vocab: torch.FloatTensor,
+ pad_token_id: Optional[Union[int, torch.Tensor]] = None,
+ eos_token_id: Optional[Union[int, List[int], torch.Tensor]] = None,
+ beam_indices: Optional[torch.LongTensor] = None,
+ decoder_prompt_len: Optional[int] = 0,
+ ) -> Tuple[torch.Tensor]:
+ r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size * num_beams, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using any class inheriting from [`PreTrainedTokenizer`]. See
+ [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ next_scores (`torch.FloatTensor` of shape `(batch_size, 2 * num_beams)`):
+ Current scores of the top `2 * num_beams` non-finished beam hypotheses.
+ next_tokens (`torch.LongTensor` of shape `(batch_size, 2 * num_beams)`):
+ `input_ids` of the tokens corresponding to the top `2 * num_beams` non-finished beam hypotheses.
+ next_indices (`torch.LongTensor` of shape `(batch_size, 2 * num_beams)`):
+ Beam indices indicating to which beam hypothesis the `next_tokens` correspond.
+ scores_for_all_vocab (`torch.FloatTensor` of shape `(batch_size * num_beams, sequence_length)`):
+ The scores of all tokens in the vocabulary for each of the beam hypotheses.
+ pad_token_id (`int`, *optional*):
+ The id of the *padding* token.
+ eos_token_id (`Union[int, List[int]]`, *optional*):
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
+ beam_indices (`torch.LongTensor`, *optional*):
+ Beam indices indicating to which beam hypothesis each token correspond.
+ decoder_prompt_len (`int`, *optional*):
+ The length of prompt that is included in the input to decoder.
+ Return:
+ `UserDict`: A dictionary composed of the fields as defined above:
+
+ - **next_beam_scores** (`torch.FloatTensor` of shape `(batch_size * num_beams)`) -- Updated scores of
+ all
+ non-finished beams.
+
+ - **next_beam_tokens** (`torch.FloatTensor` of shape `(batch_size * num_beams)`) -- Next tokens to be
+ added
+ to the non-finished beam_hypotheses.
+ - **next_beam_indices** (`torch.FloatTensor` of shape `(batch_size * num_beams)`) -- Beam indices
+ indicating to which beam the next tokens shall be added.
+ """
+
+ # add up to the length which the next_scores is calculated on (including decoder prompt)
+ cur_len = input_ids.shape[-1] + 1
+ batch_size = len(self._beam_hyps)
+ if not (batch_size == (input_ids.shape[0] // self.group_size)):
+ if self.num_beam_groups > 1:
+ raise ValueError(
+ f"A group beam size of {input_ids.shape[0]} is used as the input, but a group beam "
+ f"size of {self.group_size} is expected by the beam scorer."
+ )
+ else:
+ raise ValueError(
+ f"A beam size of {input_ids.shape[0]} is used as the input, but a beam size of "
+ f"{self.group_size} is expected by the beam scorer."
+ )
+
+ device = input_ids.device
+
+ next_beam_scores = torch.zeros((batch_size, self.group_size), dtype=next_scores.dtype, device=device)
+ next_beam_tokens = torch.zeros((batch_size, self.group_size), dtype=next_tokens.dtype, device=device)
+ next_beam_indices = torch.zeros((batch_size, self.group_size), dtype=next_indices.dtype, device=device)
+
+ if eos_token_id is not None and not isinstance(eos_token_id, torch.Tensor):
+ if isinstance(eos_token_id, int):
+ eos_token_id = [eos_token_id]
+ eos_token_id = torch.tensor(eos_token_id)
+
+ for batch_idx, beam_hyp in enumerate(self._beam_hyps):
+ if self._done[batch_idx]:
+ if self.num_beams < len(beam_hyp):
+ raise ValueError(f"Batch can only be done if at least {self.num_beams} beams have been generated")
+ if eos_token_id is None or pad_token_id is None:
+ raise ValueError("Generated beams >= num_beams -> eos_token_id and pad_token have to be defined")
+ # pad the batch
+ next_beam_scores[batch_idx, :] = 0
+ next_beam_tokens[batch_idx, :] = pad_token_id
+ next_beam_indices[batch_idx, :] = 0
+ continue
+
+ # next tokens for this sentence.
+ beam_idx = 0
+ for beam_token_rank, (next_token, next_score, next_index) in enumerate(
+ zip(next_tokens[batch_idx], next_scores[batch_idx], next_indices[batch_idx])
+ ):
+ batch_beam_idx = batch_idx * self.group_size + next_index
+ # add to generated hypotheses if end of sentence
+ if (eos_token_id is not None) and (next_token.item() in eos_token_id):
+ # if beam_token does not belong to top num_beams tokens, it should not be added
+ is_beam_token_worse_than_top_num_beams = beam_token_rank >= self.group_size
+ if is_beam_token_worse_than_top_num_beams:
+ continue
+
+ completes_constraint = self.check_completes_constraints(input_ids[batch_beam_idx].cpu().tolist())
+ if completes_constraint:
+ if beam_indices is not None:
+ beam_index = beam_indices[batch_beam_idx]
+ beam_index = beam_index + (batch_beam_idx,)
+ else:
+ beam_index = None
+
+ beam_hyp.add(
+ input_ids[batch_beam_idx].clone(),
+ next_score.item(),
+ beam_indices=beam_index,
+ generated_len=cur_len - decoder_prompt_len,
+ )
+ else:
+ # add next predicted token since it is not eos_token
+ next_beam_scores[batch_idx, beam_idx] = next_score
+ next_beam_tokens[batch_idx, beam_idx] = next_token
+ next_beam_indices[batch_idx, beam_idx] = batch_beam_idx
+ beam_idx += 1
+
+ # once the beam for next step is full, don't add more tokens to it.
+ if beam_idx == self.group_size:
+ break
+
+ new_scores, new_tokens, new_indices = self.step_sentence_constraint(
+ batch_idx,
+ input_ids,
+ scores_for_all_vocab,
+ next_beam_scores[batch_idx],
+ next_beam_tokens[batch_idx],
+ next_beam_indices[batch_idx],
+ )
+
+ next_beam_scores[batch_idx] = new_scores
+ next_beam_tokens[batch_idx] = new_tokens
+ next_beam_indices[batch_idx] = new_indices
+
+ if beam_idx < self.group_size:
+ raise ValueError(
+ f"At most {self.group_size} tokens in {next_tokens[batch_idx]} can be equal to `eos_token_id:"
+ f" {eos_token_id}`. Make sure {next_tokens[batch_idx]} are corrected."
+ )
+
+ # Check if we are done so that we can save a pad step if all(done)
+ self._done[batch_idx] = self._done[batch_idx] or beam_hyp.is_done(
+ next_scores[batch_idx].max().item(), cur_len, decoder_prompt_len
+ )
+
+ return UserDict(
+ {
+ "next_beam_scores": next_beam_scores.view(-1),
+ "next_beam_tokens": next_beam_tokens.view(-1),
+ "next_beam_indices": next_beam_indices.view(-1),
+ }
+ )
+
+ def step_sentence_constraint(
+ self,
+ batch_idx: int,
+ input_ids: torch.LongTensor,
+ vocab_scores: torch.FloatTensor,
+ sent_beam_scores: torch.FloatTensor,
+ sent_beam_tokens: torch.LongTensor,
+ sent_beam_indices: torch.LongTensor,
+ push_progress: bool = False,
+ ):
+ # sent_beam_tokens are the next {num_beams} number of tokens that are under consideration for this beam
+ # (candidate next tokens)
+
+ # 1. Adding "advance_tokens"
+ # using ConstraintStateList.advance(), we propose new tokens to be added into this "candidate list" that will
+ # advance us in fulfilling the constraints.
+
+ # 2. Selecting best candidates such that we end up with highest probable candidates
+ # that fulfill our constraints.
+
+ orig_len = sent_beam_indices.size(0)
+ device = sent_beam_indices.device
+
+ # initialize states
+ topk_contraint_states = self.make_constraint_states(orig_len)
+ advance_constraint_states = self.make_constraint_states(orig_len)
+
+ sidx, eidx = batch_idx * orig_len, (batch_idx + 1) * orig_len
+ this_batch_input_ids = input_ids[sidx:eidx]
+ this_batch_token_scores = vocab_scores[sidx:eidx]
+ full_hypotheses = torch.cat((input_ids[sent_beam_indices], sent_beam_tokens.unsqueeze(-1)), dim=-1)
+
+ # need to make new hypothesis that advance the constraints
+ track_new = {
+ "new_seqs": full_hypotheses.tolist(),
+ "new_states": [],
+ "new_indices": [],
+ "new_tokens": [],
+ "new_scores": [],
+ }
+ for seq_idx, pre_seq in enumerate(this_batch_input_ids):
+ # pre_seq = ith sequence generated before this step.
+
+ # input_ids -> (topk) generic beam search best model next tokens
+ # -> (advance) constraints forcing the next token
+ # either way, we need to sort them into "banks" later, so store a "ConstraintListState" for all types of
+ # hypotheses.
+
+ topk_state = topk_contraint_states[seq_idx]
+ topk_state.reset(full_hypotheses[seq_idx].cpu().tolist())
+
+ advance_state = advance_constraint_states[seq_idx]
+ advance_state.reset(pre_seq.cpu().tolist())
+
+ if not advance_state.completed:
+ advance_tokens = torch.LongTensor(advance_state.advance()).to(device)
+ for advance_token in advance_tokens:
+ # since adding each `advance_token` leads to a different hypothesis, create new state instance.
+ new_state = advance_state.copy(stateful=True)
+ new_state.add(advance_token.cpu().tolist())
+
+ advance_seq = torch.cat((pre_seq, advance_token.unsqueeze(0)), -1).cpu().tolist()
+ if advance_seq not in track_new["new_seqs"]:
+ # prevent duplicates, which are basically bound to happen in this process.
+ track_new["new_seqs"].append(advance_seq)
+ track_new["new_indices"].append(sidx + seq_idx) # idx -> global idx across all the batches
+ track_new["new_tokens"].append(advance_token)
+ track_new["new_scores"].append(this_batch_token_scores[seq_idx].take(advance_token))
+ track_new["new_states"].append(new_state)
+ elif push_progress:
+ # Basically, `sent_beam_indices` often chooses very little among `input_ids` the generated sequences that
+ # actually fulfill our constraints. For example, let constraints == ["loves pies"] and
+
+ # pre_seq_1 = "The child loves pies and" pre_seq_2 = "The child plays in the playground and"
+
+ # Without this step, if `sent_beam_indices` is something like [1,1], then
+ # 1. `pre_seq_1` won't be added to the list of (topk) hypothesis since it's not in the indices and
+ # 2. it won't be added to the list of (advance) hypothesis since it's completed already. (this is
+ # the else part of `if constraints_completed[seq_idx]`)
+ # 3. it ends up simply getting removed from consideration.
+
+ # #3 might be fine and actually desired, since it's likely that it's a low-probability output anyways,
+ # especially if it's not in the list of `sent_beam_indices`. But this often leads to lengthened beam
+ # search times, since completed sequences keep getting removed after all this effort for constrained
+ # generation.
+
+ # Here, we basically take `pre_seq_1` and to "push" it into the considered list of hypotheses, by simply
+ # appending the next likely token in the vocabulary and adding it to the list of hypotheses.
+
+ new_score, new_token = torch.max(this_batch_token_scores[seq_idx], 0) # some next probable token
+ advance_seq = torch.cat((pre_seq, new_token.unsqueeze(0)), -1)
+
+ advance_state = advance_constraint_states[seq_idx]
+
+ advance_seq = advance_seq.cpu().tolist()
+
+ advance_state.reset(advance_seq)
+ if advance_seq not in track_new["new_seqs"]:
+ # but still don't want to have duplicates
+ track_new["new_seqs"].append(advance_seq)
+ track_new["new_indices"].append(seq_idx)
+ track_new["new_tokens"].append(new_token)
+ track_new["new_scores"].append(new_score)
+ track_new["new_states"].append(advance_state)
+
+ if len(track_new["new_indices"]) > 0:
+ new_indices = torch.tensor(track_new["new_indices"]).to(device)
+ new_tokens = torch.stack(track_new["new_tokens"]).to(device)
+ new_scores = torch.stack(track_new["new_scores"]).to(device)
+
+ all_states = topk_contraint_states + track_new["new_states"]
+ all_tokens = torch.cat((sent_beam_tokens, new_tokens), -1)
+ all_scores = torch.cat((sent_beam_scores, new_scores), -1)
+ all_banks = torch.tensor([one.get_bank() for one in all_states]).to(device)
+
+ zipped = all_banks * 100 + all_scores
+ indices = zipped.sort(descending=True).indices
+ sorted_banks = all_banks[indices]
+
+ # Then we end up with {sorted among bank C}, {sorted among bank C-1}, ..., {sorted among bank 0}
+
+ counter = -1
+ cur_bank = sorted_banks[0]
+ increments = []
+ for bank in sorted_banks:
+ if bank == cur_bank:
+ counter += 1
+ else:
+ counter = 0
+ cur_bank = bank
+ increments.append(counter)
+ rearrangers = torch.tensor(np.argsort(increments, kind="mergesort"))
+
+ indices = indices[rearrangers][:orig_len]
+
+ sent_beam_scores = all_scores[indices]
+ sent_beam_tokens = all_tokens[indices]
+ sent_beam_indices = torch.cat((sent_beam_indices, new_indices))[indices]
+
+ return sent_beam_scores, sent_beam_tokens, sent_beam_indices
+
+ def finalize(
+ self,
+ input_ids: torch.LongTensor,
+ final_beam_scores: torch.FloatTensor,
+ final_beam_tokens: torch.LongTensor,
+ final_beam_indices: torch.LongTensor,
+ max_length: int,
+ pad_token_id: Optional[Union[int, torch.Tensor]] = None,
+ eos_token_id: Optional[Union[int, List[int], torch.Tensor]] = None,
+ beam_indices: Optional[torch.LongTensor] = None,
+ decoder_prompt_len: Optional[int] = 0,
+ ) -> Tuple[torch.LongTensor]:
+ batch_size = len(self._beam_hyps)
+
+ if eos_token_id is not None and not isinstance(eos_token_id, torch.Tensor):
+ if isinstance(eos_token_id, int):
+ eos_token_id = [eos_token_id]
+ eos_token_id = torch.tensor(eos_token_id)
+
+ # finalize all open beam hypotheses and add to generated hypotheses
+ for batch_idx, beam_hyp in enumerate(self._beam_hyps):
+ if self._done[batch_idx]:
+ continue
+
+ # all open beam hypotheses are added to the beam hypothesis
+ # beam hypothesis class automatically keeps the best beams
+
+ ids_collect = []
+ for beam_id in range(self.num_beams):
+ batch_beam_idx = batch_idx * self.num_beams + beam_id
+ final_score = final_beam_scores[batch_beam_idx].item()
+ final_tokens = input_ids[batch_beam_idx]
+
+ completes_constraint = self.check_completes_constraints(final_tokens.cpu().tolist())
+ if completes_constraint:
+ beam_index = beam_indices[batch_beam_idx] if beam_indices is not None else None
+ generated_len = final_tokens.shape[-1] - decoder_prompt_len
+ beam_hyp.add(final_tokens, final_score, beam_indices=beam_index, generated_len=generated_len)
+ ids_collect.append(beam_id)
+
+ # due to overly complex constraints or other factors, sometimes we can't gaurantee a successful
+ # generation. In these cases we simply return the highest scoring outputs.
+ if len(ids_collect) < self.num_beam_hyps_to_keep:
+ for beam_id in range(self.num_beams):
+ if beam_id not in ids_collect:
+ batch_beam_idx = batch_idx * self.num_beams + beam_id
+ final_score = final_beam_scores[batch_beam_idx].item()
+ final_tokens = input_ids[batch_beam_idx]
+ generated_len = final_tokens.shape[-1] - decoder_prompt_len
+ beam_hyp.add(final_tokens, final_score, generated_len=generated_len)
+ if len(ids_collect) >= self.num_beam_hyps_to_keep:
+ break
+
+ # select the best hypotheses
+ sent_lengths = input_ids.new(batch_size * self.num_beam_hyps_to_keep)
+ best = []
+ best_indices = []
+ best_scores = torch.zeros(batch_size * self.num_beam_hyps_to_keep, device=self.device, dtype=torch.float32)
+
+ # retrieve best hypotheses
+ for i, beam_hyp in enumerate(self._beam_hyps):
+ sorted_hyps = sorted(beam_hyp.beams, key=lambda x: x[0])
+ for j in range(self.num_beam_hyps_to_keep):
+ best_hyp_tuple = sorted_hyps.pop()
+ best_score = best_hyp_tuple[0]
+ best_hyp = best_hyp_tuple[1]
+ best_index = best_hyp_tuple[2]
+ sent_lengths[self.num_beam_hyps_to_keep * i + j] = len(best_hyp)
+
+ # append to lists
+ best.append(best_hyp)
+
+ # append indices to list
+ best_indices.append(best_index)
+
+ best_scores[i * self.num_beam_hyps_to_keep + j] = best_score
+
+ # prepare for adding eos
+ sent_lengths_max = sent_lengths.max().item() + 1
+
+ sent_max_len = min(sent_lengths_max, max_length) if max_length is not None else sent_lengths_max
+ decoded: torch.LongTensor = input_ids.new(batch_size * self.num_beam_hyps_to_keep, sent_max_len)
+
+ if len(best_indices) > 0 and best_indices[0] is not None:
+ indices: torch.LongTensor = input_ids.new(batch_size * self.num_beam_hyps_to_keep, sent_max_len)
+ else:
+ indices = None
+
+ # shorter batches are padded if needed
+ if sent_lengths.min().item() != sent_lengths.max().item():
+ if pad_token_id is None:
+ raise ValueError("`pad_token_id` has to be defined")
+ decoded.fill_(pad_token_id)
+
+ if indices is not None:
+ indices.fill_(-1)
+
+ # fill with hypotheses and eos_token_id if the latter fits in
+ for i, (hypo, best_idx) in enumerate(zip(best, best_indices)):
+ decoded[i, : sent_lengths[i]] = hypo
+
+ if indices is not None:
+ indices[i, : len(best_idx)] = torch.tensor(best_idx)
+
+ if sent_lengths[i] < sent_max_len:
+ # inserting only the first eos_token_id
+ decoded[i, sent_lengths[i]] = eos_token_id[0]
+
+ return UserDict(
+ {
+ "sequences": decoded,
+ "sequence_scores": best_scores,
+ "beam_indices": indices,
+ }
+ )
+
+
+class BeamHypotheses:
+ def __init__(self, num_beams: int, length_penalty: float, early_stopping: bool, max_length: Optional[int] = None):
+ """
+ Initialize n-best list of hypotheses.
+ """
+ self.length_penalty = length_penalty
+ self.early_stopping = early_stopping
+ self.max_length = max_length
+ self.num_beams = num_beams
+ self.beams = []
+ self.worst_score = 1e9
+
+ if not isinstance(self.early_stopping, bool) and self.max_length is None:
+ raise ValueError(
+ "When `do_early_stopping` is set to a string, `max_length` must be defined. Ensure it is passed to the"
+ " BeamScorer class instance at initialization time."
+ )
+
+ def __len__(self):
+ """
+ Number of hypotheses in the list.
+ """
+ return len(self.beams)
+
+ def add(
+ self,
+ hyp: torch.LongTensor,
+ sum_logprobs: float,
+ beam_indices: Optional[torch.LongTensor] = None,
+ generated_len: Optional[int] = None,
+ ):
+ """
+ Add a new hypothesis to the list.
+ """
+ if generated_len is not None:
+ score = sum_logprobs / (generated_len**self.length_penalty)
+ # This 'else' case exists for retrocompatibility
+ else:
+ score = sum_logprobs / (hyp.shape[-1] ** self.length_penalty)
+
+ if len(self) < self.num_beams or score > self.worst_score:
+ self.beams.append((score, hyp, beam_indices))
+ if len(self) > self.num_beams:
+ sorted_next_scores = sorted([(s, idx) for idx, (s, _, _) in enumerate(self.beams)])
+ del self.beams[sorted_next_scores[0][1]]
+ self.worst_score = sorted_next_scores[1][0]
+ else:
+ self.worst_score = min(score, self.worst_score)
+
+ def is_done(self, best_sum_logprobs: float, cur_len: int, decoder_prompt_len: Optional[int] = 0) -> bool:
+ """
+ If there are enough hypotheses and that none of the hypotheses being generated can become better than the worst
+ one in the heap, then we are done with this sentence.
+ """
+
+ if len(self) < self.num_beams:
+ return False
+
+ # `True`: stop as soon as at least `num_beams` hypotheses are finished
+ if self.early_stopping is True:
+ return True
+ # `False`: heuristic -- compute best possible score from `cur_len`, even though it is not entirely accurate
+ # when `length_penalty` is positive. See the discussion below for more details.
+ # https://github.com/huggingface/transformers/pull/20901#issuecomment-1369845565
+ elif self.early_stopping is False:
+ highest_attainable_score = best_sum_logprobs / (cur_len - decoder_prompt_len) ** self.length_penalty
+ ret = self.worst_score >= highest_attainable_score
+ return ret
+ # `"never"`: compute the best possible score, depending on the signal of `length_penalty`
+ else:
+ # `length_penalty` > 0.0 -> max denominator is obtaned from `max_length`, not from `cur_len` -> min
+ # abs(`highest_attainable_score`) is obtained -> `highest_attainable_score` is negative, hence we obtain
+ # its max this way
+ if self.length_penalty > 0.0:
+ if self.max_length <= decoder_prompt_len:
+ raise ValueError("max_length is not larger than decoder prompt length")
+ highest_attainable_score = (
+ best_sum_logprobs / (self.max_length - decoder_prompt_len) ** self.length_penalty
+ )
+ # the opposite logic applies here (max `highest_attainable_score` from `cur_len`)
+ else:
+ highest_attainable_score = best_sum_logprobs / (cur_len - decoder_prompt_len) ** self.length_penalty
+ ret = self.worst_score >= highest_attainable_score
+ return ret
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/candidate_generator.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/candidate_generator.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebb9a18d559f064bbf81641a7a2168c4c045117a
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/candidate_generator.py
@@ -0,0 +1,1158 @@
+# coding=utf-8
+# Copyright 2023 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import copy
+import weakref
+from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple
+
+import numpy as np
+import torch
+
+from ..utils import is_sklearn_available
+
+
+if is_sklearn_available():
+ from sklearn.metrics import roc_curve
+
+from ..cache_utils import DynamicCache
+from ..pytorch_utils import isin_mps_friendly
+from .logits_process import LogitsProcessorList, MinLengthLogitsProcessor, SuppressTokensLogitsProcessor
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..tokenization_utils_base import PreTrainedTokenizerBase
+ from .configuration_utils import GenerationConfig
+
+
+class CandidateGenerator:
+ """Abstract base class for all candidate generators that can be applied during assisted generation."""
+
+ def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
+ """
+ Fetches the candidates to be tried for the current input.
+
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
+
+ Return:
+ `torch.LongTensor` of shape `(batch_size, candidate_length)` containing the candidate sequences to be
+ assessed by the model and, optionally, a `torch.FloatTensor` of shape `(batch_size, candidate_length,
+ vocabulary_size)` containing the logits associated to each candidate.
+ """
+ raise NotImplementedError(
+ f"{self.__class__} is an abstract class. Only classes inheriting this class can call `get_candidates`."
+ )
+
+ def update_candidate_strategy(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, num_matches: int):
+ """
+ Updates the candidate generation strategy based on the outcomes.
+
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
+ scores (`torch.FloatTensor` of shape `(batch_size, candidate_length, config.vocab_size)`):
+ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using
+ beam search or log softmax for each vocabulary token when using beam search
+ num_matches (`int`):
+ The number of matches between the candidate sequences and the model predictions.
+ """
+ raise NotImplementedError(
+ f"{self.__class__} is an abstract class. Only classes inheriting this class can call "
+ "`update_candidate_strategy`."
+ )
+
+
+class AssistedCandidateGenerator(CandidateGenerator):
+ """
+ `CandidateGenerator` class to be used for assisted generation and speculative decoding. This class generates
+ candidates through the use of a smaller model. Read the following blog post for more information:
+ https://huggingface.co/blog/assisted-generation
+
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
+ assistant_model (`PreTrainedModel`):
+ The model to be used for generating candidates. This model should be smaller than the main model.
+ generation_config (`~generation.GenerationConfig`, *optional*):
+ The generation configuration to be used as base parametrization for the generation call.
+ logits_processor (`LogitsProcessorList`):
+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ model_kwargs (`Dict`):
+ The keyword arguments that will be passed to the main model, and are used as base inputs for the assistant
+ model as well.
+ inputs_tensor (`torch.Tensor`, *optional*):
+ The model input tensor. In encoder-decoder models, this is the encoder input.
+ """
+
+ def __init__(
+ self,
+ input_ids: torch.LongTensor,
+ assistant_model: "PreTrainedModel",
+ generation_config: "GenerationConfig",
+ model_kwargs: Dict,
+ inputs_tensor: Optional[torch.Tensor] = None,
+ logits_processor: "LogitsProcessorList" = None,
+ ):
+ # Make sure all data at the same device as assistant model
+ device = assistant_model.device
+ input_ids = input_ids.to(device)
+ if inputs_tensor is not None:
+ inputs_tensor = inputs_tensor.to(device)
+
+ # Prepare the assistant and the starting number of candidate tokens
+ self.assistant_model = assistant_model
+ self.num_assistant_tokens = assistant_model.generation_config.num_assistant_tokens
+ self.assistant_confidence_threshold = assistant_model.generation_config.assistant_confidence_threshold
+
+ # Set eos in assistant same as in target model
+ self.assistant_model.generation_config.eos_token_id = generation_config.eos_token_id
+
+ # Prepare the kwargs for the assistant model
+ assistant_kwargs = {}
+ for key, value in model_kwargs.items(): # deepcopy crashes if we attempt to copy encoder outputs with grads
+ if key not in ("encoder_outputs", "past_key_values"):
+ assistant_kwargs[key] = (
+ value.detach().to(device) if isinstance(value, torch.Tensor) else copy.deepcopy(value)
+ )
+
+ # Remove potential default "logits_to_keep" key
+ if "logits_to_keep" in assistant_kwargs.keys() and not assistant_model._supports_logits_to_keep():
+ del assistant_kwargs["logits_to_keep"]
+
+ # If the assistant is an encoder-decoder model, assume the encoder is different on the assistant.
+ if assistant_model.config.is_encoder_decoder:
+ inputs_tensor, model_input_name, assistant_kwargs = assistant_model._prepare_model_inputs(
+ inputs_tensor, assistant_model.generation_config.bos_token_id, assistant_kwargs
+ )
+ assistant_kwargs = assistant_model._prepare_encoder_decoder_kwargs_for_generation(
+ inputs_tensor, assistant_kwargs, model_input_name, assistant_model.generation_config
+ )
+ elif "encoder_outputs" in model_kwargs:
+ assistant_kwargs["encoder_outputs"] = model_kwargs["encoder_outputs"]
+ self.assistant_kwargs = assistant_kwargs
+
+ # Prepare assistant model's keys of inputs
+ if assistant_model.config.is_encoder_decoder:
+ # both are encoder-decoder
+ self.input_ids_key = "decoder_input_ids"
+ elif "encoder_outputs" in assistant_kwargs:
+ # special case for encoder-decoder with decoder-only assistant (like DistilWhisper)
+ self.input_ids_key = "input_ids"
+ self.assistant_kwargs["attention_mask"] = self.assistant_kwargs.get(
+ "decoder_attention_mask",
+ torch.ones((input_ids.shape[0], 1), device=input_ids.device, dtype=torch.long),
+ )
+ else:
+ # both are decoder-only
+ self.input_ids_key = "input_ids"
+
+ # Prepare generation-related options.
+ self.logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
+ self.generation_config = copy.deepcopy(generation_config)
+
+ self.generation_config.return_dict_in_generate = True
+ self.generation_config.output_scores = True
+ self.generation_config.assistant_confidence_threshold = self.assistant_confidence_threshold
+ # this flag allow us set the confidence stopping criteria for assistant model generation.
+ self.generation_config.is_assistant = True
+
+ # avoid unnecessary warnings that min_length is larger than max_new_tokens
+ # remove the `MinLengthLogitsProcessor` if exists (NOTE: no need to check for `MinNewTokensLogitsProcessor`)
+ self.main_model_min_length = self.generation_config.min_length
+ self.generation_config.min_length = 0
+ self.generation_config.min_new_tokens = None
+ for processor in self.logits_processor:
+ if isinstance(processor, MinLengthLogitsProcessor):
+ raise ValueError(
+ "Passing `MinLengthLogitsProcessor` when using `assisted_generation is disabled. "
+ "Please pass in `min_length` into `.generate()` instead"
+ )
+
+ # We need to roll back the cache in assisted generation, only DynamicCache is supported
+ self.generation_config.cache_implementation = None
+
+ if (
+ is_sklearn_available()
+ and self.assistant_model.generation_config.assistant_confidence_threshold
+ and type(self) is AssistedCandidateGenerator
+ ):
+ self.probs = []
+ self.matches = []
+
+ def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
+ """
+ Fetches the candidates to be tried for the current input.
+
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
+
+ Return:
+ `torch.LongTensor` of shape `(batch_size, candidate_length)` containing the candidate sequences to be
+ assessed by the model and a `torch.FloatTensor` of shape `(batch_size, candidate_length,
+ vocabulary_size)` containing the logits associated to each candidate.
+ """
+ input_ids = input_ids.to(self.assistant_model.device)
+ # Calculate new tokens to generate
+ min_new_tokens, max_new_tokens = self._calculate_new_tokens(input_ids)
+ if max_new_tokens == 0:
+ return input_ids, None
+ # Update past key values and masks
+ self._update_past_and_masks(input_ids)
+ # Generate candidates
+ generation_args = self._prepare_generation_args(input_ids, min_new_tokens, max_new_tokens)
+ candidate_ids, candidate_logits = self._generate_candidates(generation_args)
+ return candidate_ids, candidate_logits
+
+ def update_candidate_strategy(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, num_matches: int):
+ """
+ Updates the candidate generation strategy based on the outcomes.
+
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
+ scores (`torch.FloatTensor` of shape `(batch_size, candidate_length, config.vocab_size)`):
+ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using
+ beam search or log softmax for each vocabulary token when using beam search
+ num_matches (`int`):
+ The number of matches between the candidate sequences and the model predictions.
+ """
+ # Adjust the max number of assistant tokens to use in the next iteration. This is a simple heuristic,
+ # probably can be improved -- we want to balance the benefits of getting assistant tokens correct with the
+ # cost of forecasting incorrect assistant tokens.
+ if self.assistant_model.generation_config.num_assistant_tokens_schedule in {
+ "heuristic",
+ "heuristic_transient",
+ }:
+ # len(scores[0])-1 is the number of candidates according to the target tokenizer.
+ if num_matches == len(scores[0]) - 1:
+ self.num_assistant_tokens += 2.0
+ else:
+ self.num_assistant_tokens = max(1.0, self.num_assistant_tokens - 1.0)
+
+ # The assistant's confidence threshold is adjusted throughout the speculative iterations to reduce the number of unnecessary draft and target forward passes. The costs are estimated based on the ROC curve, which considers the probability of the draft token and its match with the target. A cost of 25% is assigned to false positives and 75% to false negatives.
+ # This adaptation is not compatible with UAG, as it relies on the number of matched tokens based on the draft vocabulary, which is unavailable in UAG.
+ if (
+ is_sklearn_available()
+ and self.assistant_model.generation_config.assistant_confidence_threshold
+ and type(self) is AssistedCandidateGenerator
+ ):
+ # update self.matches
+ self.matches.extend([1] * num_matches)
+ if len(self.probs) > len(self.matches):
+ self.matches.append(0)
+
+ # update self.probs
+ excess_length = len(self.probs) - len(self.matches)
+ if excess_length > 0:
+ del self.probs[-excess_length:]
+
+ if (
+ len(self.probs) > 5 and {0, 1}.issubset(self.matches)
+ ): # require at least 5 samples to calculate the ROC curve and at least one positive and one negative sample
+ fpr, tpr, thresholds = roc_curve(self.matches, self.probs)
+ fnr = 1 - tpr
+
+ # Calculate the cost for each threshold
+ costs = fpr + 3 * fnr
+
+ # Find the threshold that minimizes the cost
+ optimal_threshold_index = np.argmin(costs)
+ best_threshold = thresholds[optimal_threshold_index]
+
+ self.assistant_model.generation_config.assistant_confidence_threshold = best_threshold
+
+ def _calculate_new_tokens(self, input_ids: torch.LongTensor) -> Tuple[int, int]:
+ """Calculate the minimum and maximum number of new tokens to generate."""
+ new_cur_len = input_ids.shape[-1]
+ max_new_tokens = min(int(self.num_assistant_tokens), self.generation_config.max_length - new_cur_len - 1)
+ min_new_tokens = max(min(max_new_tokens, self.main_model_min_length - new_cur_len), 0)
+ return min_new_tokens, max_new_tokens
+
+ def _update_past_and_masks(
+ self, input_ids: torch.LongTensor, remove_from_pkv: int = 0, num_added_tokens: int = 1
+ ) -> bool:
+ """Update past key values and attention masks for subsequent generation rounds."""
+ has_past_key_values = self.assistant_kwargs.get("past_key_values", None) is not None
+ if has_past_key_values:
+ new_cache_size = input_ids.shape[-1] - 1 - remove_from_pkv
+ self.assistant_kwargs["past_key_values"] = _crop_past_key_values(
+ self.assistant_model, self.assistant_kwargs["past_key_values"], new_cache_size - num_added_tokens
+ )
+ self.assistant_kwargs = _prepare_attention_mask(
+ self.assistant_kwargs, input_ids.shape[-1], self.assistant_model.config.is_encoder_decoder
+ )
+ self.assistant_kwargs = _prepare_token_type_ids(self.assistant_kwargs, input_ids.shape[-1])
+
+ return has_past_key_values
+
+ def _prepare_generation_args(self, input_ids: torch.LongTensor, min_new_tokens: int, max_new_tokens: int) -> Dict:
+ """Prepare arguments for the generation call."""
+ return {
+ self.input_ids_key: input_ids,
+ "min_new_tokens": min_new_tokens,
+ "max_new_tokens": max_new_tokens,
+ "generation_config": self.generation_config,
+ "logits_processor": self.logits_processor,
+ }
+
+ def _generate_candidates(self, generation_args: Dict) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
+ """Generate candidate sequences using the assistant model."""
+ assistant_output = self.assistant_model.generate(**generation_args, **self.assistant_kwargs)
+ self.assistant_kwargs["past_key_values"] = assistant_output.past_key_values
+ if (
+ is_sklearn_available()
+ and self.assistant_model.generation_config.assistant_confidence_threshold
+ and type(self) is AssistedCandidateGenerator
+ ):
+ scores_tensor = torch.cat(assistant_output.scores, dim=0)
+ scores_softmax = torch.softmax(scores_tensor, dim=-1)
+ ids = assistant_output.sequences[-1, -len(assistant_output.scores) :]
+ p = scores_softmax[range(len(ids)), ids]
+ self.probs.extend(p.tolist())
+ candidate_logits = torch.stack(assistant_output.scores, dim=1)
+ candidate_ids = assistant_output.sequences
+ return candidate_ids, candidate_logits
+
+
+class AssistedCandidateGeneratorDifferentTokenizers(AssistedCandidateGenerator):
+ """
+ `CandidateGenerator` class to be used for Universal Assisted Generation (UAD): assisted generation with different tokenizers
+ for the assistant and main models. This class generates candidates through the use of a smaller
+ model.
+
+ The main model input tokens are re-encoded into assistant model tokens, then candidate tokens are generated in the assistant encoding, which are
+ in turn re-encoded into main model candidate tokens. Validation then proceeds as explained above.
+ The re-encoding steps involve decoding token ids into text and then encoding the text using a different tokenizer.
+ Since re-encoding the tokens may result in tokenization discrepancies, UAD finds the longest common subsequence between the source and target encodings,
+ to ensure the new tokens include the correct prompt suffix.
+
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
+ assistant_model (`PreTrainedModel`):
+ The model to be used for generating candidates. This model should be smaller than the main model.
+ target_tokenizer (`PreTrainedTokenizerBase`):
+ The tokenizer used for the target model.
+ assistant_tokenizer (`PreTrainedTokenizerBase`):
+ The tokenizer used for the assistant model.
+ generation_config (`~generation.GenerationConfig`, *optional*):
+ The generation configuration to be used as base parametrization for the generation call.
+ logits_processor (`LogitsProcessorList`):
+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ model_kwargs (`Dict`):
+ The keyword arguments that will be passed to the main model, and are used as base inputs for the assistant
+ model as well.
+ inputs_tensor (`torch.Tensor`, *optional*):
+ The model input tensor. In encoder-decoder models, this is the encoder input.
+ """
+
+ def __init__(
+ self,
+ input_ids: torch.LongTensor,
+ assistant_model: "PreTrainedModel",
+ target_tokenizer: "PreTrainedTokenizerBase",
+ assistant_tokenizer: "PreTrainedTokenizerBase",
+ generation_config: "GenerationConfig",
+ model_kwargs: Dict,
+ inputs_tensor: Optional[torch.Tensor] = None,
+ logits_processor: "LogitsProcessorList" = None,
+ ):
+ super().__init__(input_ids, assistant_model, generation_config, model_kwargs, inputs_tensor, logits_processor)
+
+ self.target_tokenizer = target_tokenizer
+ self.assistant_tokenizer = assistant_tokenizer
+ self.prev_target_ids_len: Optional[int] = None
+ self.prev_assistant_ids = None
+ self.target_lookbehind = assistant_model.generation_config.target_lookbehind
+ self.assistant_lookbehind = assistant_model.generation_config.assistant_lookbehind
+
+ @staticmethod
+ def _get_longest_diag_dict(input_matrix, nonzero_idx):
+ """
+ Calculates the length of the longest diagonal sequence in a given matrix.
+ Args:
+ input_matrix (torch.Tensor): The input matrix.
+ nonzero_idx (torch.Tensor): The indices of the non-zero elements in the matrix.
+ Returns:
+ dict: A dictionary where the keys are the indices of the non-zero elements and the values are the lengths of the longest diagonal sequences starting from those indices.
+ """
+
+ visited = set()
+ diags = {}
+ for idx in nonzero_idx:
+ start_idx = torch.clone(idx)
+ tuple_start_idx = tuple(start_idx.tolist())
+
+ if tuple_start_idx in visited:
+ continue
+
+ visited.add(tuple_start_idx)
+ cur_diag_len = 1
+ start_idx += 1
+ while start_idx[0] < input_matrix.shape[0] and start_idx[1] < input_matrix.shape[1]:
+ tuple_start_idx = tuple(start_idx.tolist())
+ visited.add(tuple_start_idx)
+
+ if input_matrix[start_idx[0], start_idx[1]] == 1:
+ cur_diag_len += 1
+ start_idx += 1
+ else:
+ break
+
+ diags[idx] = cur_diag_len
+ return diags
+
+ @staticmethod
+ def _get_longest_diag_index(input_matrix):
+ """
+ Returns the start index and length of the longest diagonal in the given input.
+ Args:
+ input_matrix (numpy.ndarray): The input matrix.
+ Returns:
+ tuple: A tuple containing the start index and length of the longest diagonal.
+ """
+
+ diags = AssistedCandidateGeneratorDifferentTokenizers._get_longest_diag_dict(
+ input_matrix, input_matrix.nonzero()
+ )
+ diags_values = list(diags.values())
+ diags_keys = list(diags.keys())
+ best_diag = np.argmax(diags_values)
+ diag_start_index = diags_keys[best_diag]
+ diag_start_length = diags_values[best_diag]
+ return diag_start_index, diag_start_length
+
+ @staticmethod
+ def _get_tokens_diag(prompt, prompt_plus_new_tokens):
+ """
+ Input:
+ prompt: 2D array of shape (batch_size, prompt_length), represents the original prompt tokens
+ prompt_plus_new_tokens: 2D array of shape (batch_size, prompt_length), represents the suffix of the original prompt, with additional new tokens.
+ Output:
+ discrepancy_length: int, represents the number of tokens that need to be replaced from prompt
+ new_tokens_only: 2D array of shape (batch_size, new_token_length), represents the new tokens that are not in prompt
+ discrepancy_only: 2D array of shape (batch_size, discrepancy_length), represents the new tokens that are in prompt but not in prompt_plus_new_tokens
+ """
+ compare_mat = prompt_plus_new_tokens.T == prompt
+ if not torch.is_tensor(compare_mat):
+ compare_mat = torch.tensor(compare_mat)
+
+ compare_mat_int = compare_mat.to(int)
+
+ if not compare_mat_int.any().item():
+ # empty intersection between prompt and prompt_plus_new_tokens
+ return None, None, None
+
+ longest_location, longest_diag_length = AssistedCandidateGeneratorDifferentTokenizers._get_longest_diag_index(
+ compare_mat_int
+ )
+ new_token_start_index = longest_location[0] + longest_diag_length
+ discrepancy_with_old = longest_location[1] + longest_diag_length
+ discrepancy_length = (prompt.shape[1] - discrepancy_with_old).item()
+ new_tokens_only = prompt_plus_new_tokens[:, new_token_start_index + discrepancy_length :]
+ discrepancy_only = prompt_plus_new_tokens[
+ :, new_token_start_index : new_token_start_index + discrepancy_length
+ ]
+ return discrepancy_length, new_tokens_only, discrepancy_only
+
+ def convert_source_tokens_to_target_tokens(
+ self,
+ input_ids,
+ source_tokenizer,
+ destination_tokenizer,
+ ):
+ """
+ Convert token IDs from one tokenizer to another.
+ Args:
+ input_ids: The input token IDs.
+ source_tokenizer: The source tokenizer.
+ destination_tokenizer: The destination tokenizer.
+ Returns:
+ The converted token IDs.
+ """
+ text = source_tokenizer.batch_decode(input_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)
+ dest_ids = destination_tokenizer(text, add_special_tokens=True, return_tensors="pt")["input_ids"]
+ return dest_ids.to(input_ids.device)
+
+ def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
+ """
+ Fetches the candidates to be tried for the current input.
+
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
+
+ Return:
+ `torch.LongTensor` of shape `(batch_size, candidate_length)` containing the candidate sequences to be
+ assessed by the model and a `torch.FloatTensor` of shape `(batch_size, candidate_length,
+ vocabulary_size)` containing the logits associated to each candidate.
+ """
+ max_new_tokens = int(self.num_assistant_tokens)
+ if max_new_tokens == 0:
+ return input_ids, None
+
+ input_ids = input_ids.to(self.assistant_model.device)
+ remove_from_pkv = 0
+
+ assistant_input_ids, remove_from_pkv = self._prepare_assistant_input_ids(input_ids)
+ self.prev_assistant_ids = assistant_input_ids
+
+ min_new_tokens = max(min(max_new_tokens, self.main_model_min_length - assistant_input_ids.shape[-1]), 0)
+
+ self._update_past_and_masks(assistant_input_ids, remove_from_pkv)
+ generation_args = self._prepare_generation_args(assistant_input_ids, min_new_tokens, max_new_tokens)
+ self.assistant_kwargs.pop("attention_mask", None)
+
+ assistant_output = self.assistant_model.generate(**generation_args, **self.assistant_kwargs)
+ new_target_ids = self._process_assistant_outputs(input_ids, assistant_output.sequences, assistant_input_ids)
+
+ # Update state
+ self.prev_target_ids_len = input_ids.shape[1]
+ self.assistant_kwargs["past_key_values"] = assistant_output.past_key_values
+ self.prev_assistant_ids = assistant_output.sequences
+
+ if self.prev_target_ids_len >= new_target_ids.shape[1]:
+ return input_ids, None
+
+ return new_target_ids, None
+
+ def _prepare_assistant_input_ids(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, int]:
+ """Converts target input IDs to assistant input IDs, handling discrepancies."""
+ convert_kwargs = {
+ "source_tokenizer": self.target_tokenizer,
+ "destination_tokenizer": self.assistant_tokenizer,
+ }
+ remove_from_pkv = 0
+
+ if self.prev_assistant_ids is not None and self.prev_target_ids_len > self.target_lookbehind:
+ # input_ids contains all target prompt input ids and some new target input ids
+ start_index_in_target_window = self.prev_target_ids_len - self.target_lookbehind
+
+ new_assistant_ids = self.convert_source_tokens_to_target_tokens(
+ input_ids[:, start_index_in_target_window:], **convert_kwargs
+ )
+ prompt_use_length = new_assistant_ids.shape[1]
+ prompt_use = self.prev_assistant_ids[:, -prompt_use_length:]
+
+ discrepancy_length, new_tokens_only, discrepancy_only = self._get_tokens_diag(
+ prompt_use, new_assistant_ids
+ )
+ assistant_input_ids = self.prev_assistant_ids
+
+ if new_tokens_only is not None:
+ if discrepancy_length > 0 and discrepancy_only.shape[1] > 0:
+ if discrepancy_length == discrepancy_only.shape[1]:
+ assistant_input_ids[:, -discrepancy_length:] = discrepancy_only
+
+ elif discrepancy_length > discrepancy_only.shape[1]:
+ discrepancy_length_diff = discrepancy_length - discrepancy_only.shape[1]
+ assistant_input_ids = assistant_input_ids[:, :-discrepancy_length_diff]
+ assistant_input_ids[:, -discrepancy_only.shape[1] :] = discrepancy_only
+
+ remove_from_pkv = discrepancy_length
+
+ if new_tokens_only.shape[1] > 0:
+ assistant_input_ids = torch.cat([assistant_input_ids, new_tokens_only], dim=-1)
+ else:
+ # edge case: in case of no intersection between prompt and new_assistant_ids
+ assistant_input_ids = torch.cat([assistant_input_ids, new_assistant_ids], dim=-1)
+ else:
+ assistant_input_ids = self.convert_source_tokens_to_target_tokens(input_ids, **convert_kwargs)
+ self.prev_target_ids_len = input_ids.shape[1]
+
+ return assistant_input_ids, remove_from_pkv
+
+ def _process_assistant_outputs(
+ self, input_ids: torch.LongTensor, assistant_sequences: torch.LongTensor, assistant_input_ids: torch.LongTensor
+ ) -> torch.LongTensor:
+ """Processes assistant outputs to obtain target input IDs."""
+ num_prev_assistant = self.prev_assistant_ids.shape[1]
+ start_assistant_look_index = num_prev_assistant - self.assistant_lookbehind
+
+ new_target_ids_from_window = self.convert_source_tokens_to_target_tokens(
+ assistant_sequences[:, start_assistant_look_index:],
+ source_tokenizer=self.assistant_tokenizer,
+ destination_tokenizer=self.target_tokenizer,
+ )
+ target_prompt_use_length = new_target_ids_from_window.shape[1]
+
+ target_prompt_use = input_ids[:, -target_prompt_use_length:]
+
+ _, target_new_tokens_only, _ = self._get_tokens_diag(target_prompt_use, new_target_ids_from_window)
+
+ new_target_ids = input_ids
+
+ if target_new_tokens_only is not None:
+ if target_new_tokens_only.shape[1] > 0:
+ new_target_ids = torch.cat([new_target_ids, target_new_tokens_only], dim=-1)
+ else:
+ # edge case: in case of no intersection between prompt and new_target_ids
+ new_target_ids = torch.cat([new_target_ids, new_target_ids_from_window], dim=-1)
+
+ if hasattr(self.generation_config, "max_length"):
+ new_target_ids = new_target_ids[:, : self.generation_config.max_length]
+
+ return new_target_ids
+
+
+class AssistantToTargetTranslator:
+ """
+ Translates token ids and logits between assistant and target model vocabularies. This class is used to handle
+ vocabulary mismatches when using different tokenizers for the assistant and target models in speculative decoding,
+ as introduced in the paper "Lossless Speculative Decoding Algorithms for Heterogeneous Vocabularies"
+ (https://www.arxiv.org/abs/2502.05202).
+ It maintains mappings between the two vocabularies and handles token/logit conversion.
+
+ Args:
+ target_tokenizer (`PreTrainedTokenizerBase`):
+ The tokenizer used by the target (main) model.
+ assistant_tokenizer (`PreTrainedTokenizerBase`):
+ The tokenizer used by the assistant model.
+ assistant_model_device (`str`, defaults to "cpu"):
+ The device where the assistant model is located. Used for placing tensors.
+ target_vocab_size (`int`, *optional*):
+ The size of the target model's vocabulary. If not provided, will be inferred from the target tokenizer.
+ """
+
+ FILTER_VALUE: float = -float("Inf") # The value used to filter out unmapped tokens in the logits.
+ SUPPRESS_TOKEN_ID: int = -1 # The ID used to mark suppressed tokens in the mapping.
+
+ def __init__(
+ self,
+ target_tokenizer: "PreTrainedTokenizerBase",
+ assistant_tokenizer: "PreTrainedTokenizerBase",
+ target_vocab_size: int, # required since target_vocab_size can be different from the length of target_tokenizer.get_vocab()
+ assistant_model_device: str = "cpu",
+ ):
+ self._target_tokenizer: "PreTrainedTokenizerBase" = target_tokenizer
+ self._assistant_tokenizer: "PreTrainedTokenizerBase" = assistant_tokenizer
+ self._assistant_model_device: str = assistant_model_device
+ self.target_vocab_size: int = target_vocab_size
+ self._assistant_to_target_input_ids, self.target_to_assistant_input_ids = (
+ self._get_assistant_to_target_input_ids()
+ )
+ self._suppress_input_ids: list[int] = self._get_suppress_input_ids()
+ self.logits_processors: Optional[LogitsProcessorList] = None
+ if len(self._suppress_input_ids) > 0:
+ # len(self._suppress_input_ids) = 0 if the assistant vocab is a subset of the target vocab
+ self.logits_processors = LogitsProcessorList(
+ [SuppressTokensLogitsProcessor(self._get_suppress_input_ids(), self._assistant_model_device)]
+ )
+
+ def _get_assistant_to_target_input_ids(self):
+ target_vocab = self._target_tokenizer.get_vocab()
+ assistant_vocab = self._assistant_tokenizer.get_vocab()
+
+ space_str = " "
+ target_space_ids = self._target_tokenizer(space_str, add_special_tokens=False)["input_ids"]
+ if len(target_space_ids) > 0:
+ target_space_sign = self._target_tokenizer.convert_ids_to_tokens(target_space_ids)[0][0]
+
+ assistant_space_ids = self._assistant_tokenizer(space_str, add_special_tokens=False)["input_ids"]
+ if len(assistant_space_ids) > 0:
+ assistant_space_sign = self._assistant_tokenizer.convert_ids_to_tokens(assistant_space_ids)[0][0]
+
+ if target_space_sign != assistant_space_sign:
+ # If the assistant tokenizer has a different space sign than the target tokenizer,
+ # we need to replace the assistant space sign with the target space sign in the assistant_vocab.
+ assistant_vocab = {
+ (
+ tok.replace(assistant_space_sign, target_space_sign, 1)
+ if tok.startswith(assistant_space_sign)
+ else tok
+ ): idx
+ for tok, idx in assistant_vocab.items()
+ }
+
+ max_assistant_index = max(assistant_vocab.values())
+ assistant_to_target_input_ids = torch.full((max_assistant_index + 1,), self.SUPPRESS_TOKEN_ID, dtype=int)
+ target_to_assistant_input_ids: Dict[int, int] = {}
+ for tok, assistant_id in assistant_vocab.items():
+ target_id = target_vocab.get(tok)
+ if target_id is not None:
+ assistant_to_target_input_ids[assistant_id] = target_id
+ target_to_assistant_input_ids[target_id] = assistant_id
+ return assistant_to_target_input_ids.to(self._assistant_model_device), target_to_assistant_input_ids
+
+ def _get_suppress_input_ids(self) -> list[int]:
+ """
+ Get the input ids that are in the assistant vocab but not in the target vocab.
+ """
+ return torch.where(self._assistant_to_target_input_ids == self.SUPPRESS_TOKEN_ID)[0]
+
+ def get_target_ids(
+ self, assistant_input_ids, target_input_ids, assistant_candidate_ids: torch.LongTensor
+ ) -> torch.LongTensor:
+ """
+ Return the target candidate ids that correspond to the assistant candidate ids.
+ Note that we have already the target ids for the prompt and we only need to find the target ids for the new tokens.
+ Moreover, assistant ids of the original prompt does not necessarily appear in _assistant_to_target_input_ids.
+ """
+
+ num_new_tokens = len(assistant_candidate_ids[0]) - assistant_input_ids.shape[1]
+ if num_new_tokens == 0:
+ return target_input_ids
+ else:
+ transformed_slice = self._assistant_to_target_input_ids[assistant_candidate_ids[0, -num_new_tokens:]]
+ return torch.cat((target_input_ids, transformed_slice.unsqueeze(0)), dim=1)
+
+ def get_target_logits(self, assistant_logits: torch.FloatTensor) -> torch.FloatTensor:
+ """
+ Return the target logits that correspond to the assistant logits.
+ """
+
+ target_shape: tuple[int, ...] = (*assistant_logits.shape[:-1], self.target_vocab_size)
+ target_logits: torch.FloatTensor = torch.full(target_shape, self.FILTER_VALUE).to(self._assistant_model_device)
+ # Mask for valid indices
+ assistant_indices_mask = self._assistant_to_target_input_ids != self.SUPPRESS_TOKEN_ID
+ # Exclude invalid indices
+ target_logits_supported_indices = self._assistant_to_target_input_ids[assistant_indices_mask]
+ valid_assistant_logits = assistant_logits[..., : self._assistant_to_target_input_ids.shape[0]]
+
+ target_logits[..., target_logits_supported_indices] = valid_assistant_logits[..., assistant_indices_mask]
+
+ return target_logits
+
+
+class AssistantVocabTranslatorCache:
+ """
+ Cache for `AssistantToTargetTranslator` instances. The instances are computed at
+ pre-processing time, and this cache allows us to avoid recomputing them.
+ """
+
+ _cache = weakref.WeakKeyDictionary()
+
+ @classmethod
+ def get_translator(
+ cls,
+ target_tokenizer: "PreTrainedTokenizerBase",
+ assistant_tokenizer: "PreTrainedTokenizerBase",
+ target_vocab_size: int,
+ assistant_model_device: str = "cpu",
+ ) -> AssistantToTargetTranslator:
+ assistant_dict = cls._cache.get(target_tokenizer)
+ if assistant_dict is None:
+ assistant_dict = weakref.WeakKeyDictionary()
+ cls._cache[target_tokenizer] = assistant_dict
+
+ mapping = assistant_dict.get(assistant_tokenizer)
+ if mapping is None:
+ mapping = AssistantToTargetTranslator(
+ target_tokenizer, assistant_tokenizer, target_vocab_size, assistant_model_device
+ )
+ assistant_dict[assistant_tokenizer] = mapping
+
+ return mapping
+
+ @classmethod
+ def cleanup(cls):
+ """
+ Clean up dead references in the cache.
+ This removes entries where either the target_tokenizer or assistant_tokenizer
+ has been garbage collected.
+ """
+ # Remove entries from the outer cache where the target_tokenizer is no longer alive
+ dead_keys = [key for key in cls._cache if key is None]
+ for key in dead_keys:
+ del cls._cache[key]
+
+ # For each assistant_dict, remove entries where assistant_tokenizer is no longer alive
+ for assistant_dict in cls._cache.values():
+ dead_keys = [key for key in assistant_dict if key is None]
+ for key in dead_keys:
+ del assistant_dict[key]
+
+
+class UniversalSpeculativeDecodingGenerator(AssistedCandidateGeneratorDifferentTokenizers):
+ """
+ `CandidateGenerator` class to be used for Universal Speculative Decoding (USD): speculative decoding with different tokenizers
+ for the assistant and main models. This class generates candidates through the use of a smaller model.
+ """
+
+ def __init__(
+ self,
+ input_ids: torch.LongTensor,
+ assistant_model: "PreTrainedModel",
+ target_tokenizer: "PreTrainedTokenizerBase",
+ assistant_tokenizer: "PreTrainedTokenizerBase",
+ generation_config: "GenerationConfig",
+ model_kwargs: Dict,
+ atm_translator: AssistantToTargetTranslator,
+ inputs_tensor: Optional[torch.Tensor] = None,
+ logits_processor: "LogitsProcessorList" = None,
+ ):
+ # Initialize translator before parent class
+ self._atm_translator = atm_translator
+ super().__init__(
+ input_ids,
+ assistant_model,
+ target_tokenizer,
+ assistant_tokenizer,
+ generation_config,
+ model_kwargs,
+ inputs_tensor,
+ logits_processor,
+ )
+ # Track sequence lengths and previous assistant IDs
+ self._target_seq_len_with_candidates: int = 0
+ self._prev_assistant_ids: Optional[torch.LongTensor] = None
+
+ def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
+ """
+ Simplified version of get_candidates that uses the translator cache for token conversion.
+ """
+ target_input_ids = input_ids.to(self.assistant_model.device)
+ assistant_input_ids, num_added_tokens = self._prepare_assistant_input_ids(target_input_ids)
+ min_new_tokens, max_new_tokens = self._calculate_new_tokens(target_input_ids)
+
+ if max_new_tokens == 0:
+ return input_ids, None
+
+ self._update_past_and_masks(assistant_input_ids, num_added_tokens=num_added_tokens)
+ generation_args = self._prepare_generation_args(assistant_input_ids, min_new_tokens, max_new_tokens)
+
+ # Ensure scores are returned
+ generation_args["generation_config"].output_scores = True
+ generation_args["generation_config"].return_dict_in_generate = True
+
+ # Generate and process outputs using translator
+ if self._atm_translator.logits_processors is not None:
+ generation_args["logits_processor"] = self._atm_translator.logits_processors
+ self._prev_assistant_ids, assistant_candidate_logits = self._generate_candidates(generation_args)
+
+ # Use translator to convert tokens and logits
+ target_candidate_ids = self._atm_translator.get_target_ids(
+ assistant_input_ids, target_input_ids, self._prev_assistant_ids
+ )
+ self._target_seq_len_with_candidates = target_candidate_ids.shape[-1]
+ target_candidate_logits = self._atm_translator.get_target_logits(assistant_candidate_logits)
+
+ return target_candidate_ids, target_candidate_logits
+
+ def _update_past_and_masks(self, assistant_input_ids: torch.LongTensor, num_added_tokens: int = 1) -> bool:
+ if self._prev_assistant_ids is None:
+ # Prepare attention mask for the first generation.
+ # For subsequent generations, the attention mask is updated in super()_update_past_and_masks.
+ self.assistant_kwargs = _prepare_attention_mask(
+ self.assistant_kwargs, assistant_input_ids.shape[-1], self.assistant_model.config.is_encoder_decoder
+ )
+ return super()._update_past_and_masks(assistant_input_ids, num_added_tokens=num_added_tokens)
+
+ def _prepare_assistant_input_ids(self, target_input_ids: torch.LongTensor) -> torch.LongTensor:
+ """
+ Simplified token conversion that only processes new tokens.
+ """
+ # Calculate new tokens since last call
+ target_seq_len = target_input_ids.shape[-1]
+ if self._target_seq_len_with_candidates == 0:
+ new_token_count = target_seq_len
+ else:
+ new_token_count = 1
+ target_new_ids = target_input_ids[:, -new_token_count:]
+
+ # Convert the new tokens
+ assistant_new_ids = None
+ if self._target_seq_len_with_candidates > 0:
+ # we have only one new token and we can directly convert it
+ assistant_new_ids = self._atm_translator.target_to_assistant_input_ids.get(target_new_ids[0].item())
+ if assistant_new_ids is None:
+ target_new_text = self.target_tokenizer.batch_decode(
+ target_new_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
+ )
+ assistant_new_ids = self.assistant_tokenizer(
+ target_new_text, add_special_tokens=False, return_tensors="pt"
+ )["input_ids"].to(self.assistant_model.device)
+ else:
+ assistant_new_ids = torch.tensor([[assistant_new_ids]], device=self.assistant_model.device)
+
+ # Update or initialize assistant IDs
+ if self._prev_assistant_ids is None:
+ assistant_input_ids = assistant_new_ids
+ else:
+ tokens_to_remove = self._target_seq_len_with_candidates + 1 - target_seq_len
+ # If the number of new tokens is greater than zero, truncate the previous assistant IDs
+ if tokens_to_remove > 0:
+ self._prev_assistant_ids = self._prev_assistant_ids[:, :-tokens_to_remove]
+ assistant_input_ids = torch.cat([self._prev_assistant_ids, assistant_new_ids], dim=-1)
+ assistant_input_ids = assistant_input_ids.to(dtype=torch.long)
+
+ return assistant_input_ids, len(assistant_new_ids[0])
+
+
+class PromptLookupCandidateGenerator(CandidateGenerator):
+ """
+ `CandidateGenerator` class to be used for prompt lookup generation. This class generates candidates by looking up
+ likely continuations in the provided prompt (input_ids) itself.
+ Read the following blog post for more information: https://github.com/apoorvumang/prompt-lookup-decoding
+
+ Args:
+ max_matching_ngram_size (`int`):
+ The maximum ngram size to be considered for matching in the prompt
+ num_output_tokens (`int`):
+ The number of tokens to be output as candidate tokens.
+ max_length (`int`):
+ The number of total maximum tokens that can be generated. For decoder-only models that includes the prompt length.
+ Defaults to 20, which is the max length used as default in generation config.
+ """
+
+ def __init__(
+ self,
+ eos_token_id: torch.Tensor = None,
+ num_output_tokens: int = 10,
+ max_matching_ngram_size: int = None,
+ max_length: int = 20,
+ ):
+ self.num_output_tokens = num_output_tokens
+ self.max_matching_ngram_size = max_matching_ngram_size if max_matching_ngram_size else 2
+ self.max_length = max_length
+ self.eos_token_id = eos_token_id
+
+ if self.max_matching_ngram_size <= 0 or self.num_output_tokens <= 0:
+ raise ValueError("Invalid max_matching_ngram_size or num_output_tokens")
+
+ def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
+ """
+ Fetches the candidates to be tried for the current input.
+
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
+
+ Return:
+ `torch.LongTensor` of shape `(num_candidates, candidate_length)`: The candidate sequences to be tried.
+ """
+ input_length = input_ids.size(1)
+
+ # Don't generate more than `max_length - 1` candidates since the target model generates one extra token.
+ if self.max_length == input_length + 1:
+ return input_ids, None
+
+ chosen_ids = None
+ match_found = False
+ for ngram_size in range(min(self.max_matching_ngram_size, input_length - 1), 0, -1):
+ # Create sliding windows of size ngram_size
+ windows = input_ids.unfold(dimension=1, size=ngram_size, step=1)
+
+ # Convert ngram to a tensor for comparison
+ ngram_tensor = input_ids[0, -ngram_size:]
+
+ # Find where the windows match the ngram
+ matches = (windows == ngram_tensor).all(dim=2)
+
+ # Get the indices of matches
+ match_indices = matches.nonzero(as_tuple=True)[1]
+
+ # Iterate through match indices to find a valid continuation
+ for idx in match_indices:
+ start_idx = idx + ngram_size
+ end_idx = start_idx + self.num_output_tokens
+ end_idx = min(end_idx, input_length, self.max_length)
+
+ if start_idx < end_idx:
+ chosen_ids = input_ids[0, start_idx:end_idx]
+ match_found = True
+
+ # remove remaining candidate ids if an "eos" token is found, otherwise the target model may
+ # accept eos and the rest as valid, thus not stopping generation after "eos"
+ # NOTE: below code is written based on the fact that assisted decoding supports only bs=1
+ mask = isin_mps_friendly(chosen_ids, self.eos_token_id)
+ match_indices_eos = torch.nonzero(mask)
+ if match_indices_eos.numel() > 0:
+ first_eos_index = match_indices_eos[0].item()
+ chosen_ids = chosen_ids[:first_eos_index]
+ break
+ if match_found:
+ break
+
+ if chosen_ids is None or len(chosen_ids) == 0:
+ # In case we didn't find a match return the input sequence unchanged, reverts back to autoregressive decoding
+ return input_ids, None
+
+ # Now need extend input_ids with chosen_ids
+ chosen_ids = chosen_ids.unsqueeze(0)
+ candidate_input_ids = torch.cat((input_ids, chosen_ids), dim=1)
+ # assisted_generation expects logits as well, but we don't have those here, so returning None
+ return candidate_input_ids, None
+
+ def update_candidate_strategy(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, num_matches: int):
+ """
+ Updates the candidate generation strategy based on the outcomes.
+
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
+ scores (`torch.FloatTensor` of shape `(batch_size, candidate_length, config.vocab_size)`):
+ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using
+ beam search or log softmax for each vocabulary token when using beam search
+ num_matches (`int`):
+ The number of matches between the candidate sequences and the model predictions.
+ """
+ # Currently does nothing
+ return
+
+
+class EarlyExitCandidateGenerator(AssistedCandidateGenerator):
+ """
+ `CandidateGenerator` class to be used for assisted generation and speculative decoding. This class generates
+ candidates through the use of **the model itself**, exiting early. Can only be used with models that support early
+ exit, e.g., `facebook/layerskip-llama3.2-1B`.
+
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
+ assistant_model (`PreTrainedModel`):
+ The original model. This model must support early exit (i.e. is trained to compute logits in earlier
+ layers).
+ generation_config (`~generation.GenerationConfig`, *optional*):
+ The generation configuration to be used as base parametrization for the generation call.
+ logits_processor (`LogitsProcessorList`):
+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ model_kwargs (`Dict`):
+ The keyword arguments that will be passed to the main model, and are used as base inputs for the assistant
+ model as well.
+ inputs_tensor (`torch.Tensor`, *optional*):
+ The model input tensor. In encoder-decoder models, this is the encoder input.
+ """
+
+ def __init__(
+ self,
+ input_ids: torch.LongTensor,
+ assistant_model: "PreTrainedModel",
+ generation_config: "GenerationConfig",
+ model_kwargs: Dict,
+ inputs_tensor: Optional[torch.Tensor] = None,
+ logits_processor: "LogitsProcessorList" = None,
+ ):
+ super().__init__(
+ input_ids=input_ids,
+ assistant_model=assistant_model,
+ generation_config=generation_config,
+ model_kwargs=model_kwargs,
+ inputs_tensor=inputs_tensor,
+ logits_processor=logits_processor,
+ )
+ # We have to move early exit out of the generation config, otherwise the assistant will also call `generate`
+ # with early exit
+ self.assistant_early_exit = self.generation_config.assistant_early_exit
+ self.generation_config.assistant_early_exit = None
+
+ def get_candidates(self, input_ids: torch.LongTensor) -> Tuple[torch.LongTensor, Optional[torch.FloatTensor]]:
+ # Temporarily sets the number of hidden layers to the early exit value
+ base_model = getattr(self.assistant_model, self.assistant_model.base_model_prefix)
+ original_num_hidden_layers = base_model.config.num_hidden_layers
+ base_model.config.num_hidden_layers = self.assistant_early_exit
+ candidate_ids, candidate_logits = super().get_candidates(input_ids)
+ base_model.config.num_hidden_layers = original_num_hidden_layers
+ return candidate_ids, candidate_logits
+
+
+def _crop_past_key_values(model, past_key_values, max_length):
+ """Crops the past key values up to a certain maximum length."""
+ new_past = []
+ if model.config.is_encoder_decoder:
+ for idx in range(len(past_key_values)):
+ new_past.append(
+ (
+ past_key_values[idx][0][:, :, :max_length, :],
+ past_key_values[idx][1][:, :, :max_length, :],
+ past_key_values[idx][2],
+ past_key_values[idx][3],
+ )
+ )
+ past_key_values = tuple(new_past)
+ # gptbigcode is special and stores kv in shape (batch_size, seq_len, dim), if it's a multi_query model
+ elif "gptbigcode" in model.__class__.__name__.lower() or (
+ model.config.architectures is not None and "gptbigcode" in model.config.architectures[0].lower()
+ ):
+ if model.config.multi_query:
+ for idx in range(len(past_key_values)):
+ past_key_values[idx] = past_key_values[idx][:, :max_length, :]
+ else:
+ for idx in range(len(past_key_values)):
+ past_key_values[idx] = past_key_values[idx][:, :, :max_length, :]
+ elif isinstance(past_key_values, DynamicCache):
+ past_key_values.crop(max_length)
+ elif past_key_values is not None:
+ for idx in range(len(past_key_values)):
+ if past_key_values[idx] != ([], []):
+ new_past.append(
+ (
+ past_key_values[idx][0][:, :, :max_length, :],
+ past_key_values[idx][1][:, :, :max_length, :],
+ )
+ )
+ else:
+ new_past.append((past_key_values[idx][0], past_key_values[idx][1]))
+ past_key_values = tuple(new_past)
+ return past_key_values
+
+
+def _prepare_attention_mask(model_kwargs: Dict[str, Any], new_length: int, is_encoder_decoder: bool) -> Dict[str, Any]:
+ """Expands or crops the model's mask for decoding purposes, to the defined length"""
+
+ mask_key = "decoder_attention_mask" if is_encoder_decoder else "attention_mask"
+ if mask_key not in model_kwargs:
+ return model_kwargs
+
+ mask = model_kwargs[mask_key]
+ mask_length_diff = new_length - mask.shape[1]
+
+ if mask_length_diff < 0:
+ model_kwargs[mask_key] = mask[:, :mask_length_diff]
+ elif mask_length_diff > 0:
+ model_kwargs[mask_key] = torch.cat([mask, mask.new_ones((mask.shape[0], mask_length_diff))], dim=-1)
+
+ # Handle cross attention models
+ if "cross_attention_mask" in model_kwargs:
+ # Mllama case
+ cross_mask = model_kwargs["cross_attention_mask"]
+ if mask_length_diff < 0:
+ model_kwargs["cross_attention_mask"] = cross_mask[:, :mask_length_diff]
+ elif mask_length_diff > 0:
+ new_mask = cross_mask[:, -1:, :, :].repeat(1, mask_length_diff, 1, 1)
+ model_kwargs["cross_attention_mask"] = torch.cat([cross_mask, new_mask], dim=1)
+ elif "image_attention_mask" in model_kwargs:
+ # IDEFICS case
+ cross_mask = model_kwargs["image_attention_mask"]
+ if mask_length_diff < 0:
+ model_kwargs["image_attention_mask"] = cross_mask[:, :mask_length_diff]
+ elif mask_length_diff > 0:
+ new_mask = cross_mask[:, -1:, :].repeat(1, mask_length_diff, 1)
+ model_kwargs["image_attention_mask"] = torch.cat([cross_mask, new_mask], dim=1)
+
+ return model_kwargs
+
+
+def _prepare_token_type_ids(model_kwargs: Dict[str, Any], new_length: int) -> Dict[str, Any]:
+ """Expands or crops the model's token_type_ids for decoding purposes, to the defined length"""
+ if "token_type_ids" not in model_kwargs or model_kwargs["token_type_ids"] is None:
+ return model_kwargs
+
+ token_type_ids = model_kwargs["token_type_ids"]
+ final_token_type = token_type_ids[:, -1].unsqueeze(-1)
+ type_length_diff = new_length - token_type_ids.shape[1]
+
+ if type_length_diff < 0:
+ token_type_ids = token_type_ids[:, :type_length_diff]
+ elif type_length_diff > 0:
+ token_type_copies = final_token_type.repeat(1, type_length_diff)
+ model_kwargs["token_type_ids"] = torch.cat([model_kwargs["token_type_ids"], token_type_copies], dim=-1)
+ return model_kwargs
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/configuration_utils.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/configuration_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ee48ab3f1a5219c52ab437e2a2d787dd7615c69
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/configuration_utils.py
@@ -0,0 +1,1630 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Generation configuration class and utilities."""
+
+import copy
+import json
+import os
+import warnings
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, is_dataclass
+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
+
+from .. import __version__
+from ..configuration_utils import PretrainedConfig
+from ..utils import (
+ GENERATION_CONFIG_NAME,
+ ExplicitEnum,
+ PushToHubMixin,
+ cached_file,
+ download_url,
+ extract_commit_hash,
+ is_remote_url,
+ is_torch_available,
+ logging,
+)
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+
+
+logger = logging.get_logger(__name__)
+METADATA_FIELDS = ("_from_model_config", "_commit_hash", "_original_object_hash", "transformers_version")
+CACHE_CONFIG_MAPPING = {}
+NEED_SETUP_CACHE_CLASSES_MAPPING = {}
+QUANT_BACKEND_CLASSES_MAPPING = {}
+ALL_CACHE_IMPLEMENTATIONS = []
+
+if is_torch_available():
+ from ..cache_utils import (
+ HQQQuantizedCache,
+ HybridCache,
+ MambaCache,
+ OffloadedStaticCache,
+ QuantizedCacheConfig,
+ QuantoQuantizedCache,
+ SlidingWindowCache,
+ StaticCache,
+ StaticCacheConfig,
+ )
+ from .logits_process import SynthIDTextWatermarkLogitsProcessor, WatermarkLogitsProcessor
+
+ CACHE_CONFIG_MAPPING["quantized"] = QuantizedCacheConfig
+ CACHE_CONFIG_MAPPING["static"] = StaticCacheConfig
+ NEED_SETUP_CACHE_CLASSES_MAPPING = {
+ "static": StaticCache,
+ "offloaded_static": OffloadedStaticCache,
+ "sliding_window": SlidingWindowCache,
+ "hybrid": HybridCache,
+ "mamba": MambaCache,
+ }
+ QUANT_BACKEND_CLASSES_MAPPING = {"quanto": QuantoQuantizedCache, "HQQ": HQQQuantizedCache}
+ ALL_CACHE_IMPLEMENTATIONS = (
+ list(NEED_SETUP_CACHE_CLASSES_MAPPING.keys()) + list(CACHE_CONFIG_MAPPING.keys()) + ["offloaded"]
+ )
+
+
+class GenerationMode(ExplicitEnum):
+ """
+ Possible generation modes, downstream of the [`~generation.GenerationMixin.generate`] method.
+ """
+
+ # Non-beam methods
+ CONTRASTIVE_SEARCH = "contrastive_search"
+ GREEDY_SEARCH = "greedy_search"
+ SAMPLE = "sample"
+ ASSISTED_GENERATION = "assisted_generation"
+ DOLA_GENERATION = "dola_generation"
+ # Beam methods
+ BEAM_SEARCH = "beam_search"
+ BEAM_SAMPLE = "beam_sample"
+ CONSTRAINED_BEAM_SEARCH = "constrained_beam_search"
+ GROUP_BEAM_SEARCH = "group_beam_search"
+
+
+class GenerationConfig(PushToHubMixin):
+ # no-format
+ """
+ Class that holds a configuration for a generation task. A `generate` call supports the following generation methods
+ for text-decoder, text-to-text, speech-to-text, and vision-to-text models:
+
+ - *greedy decoding* if `num_beams=1` and `do_sample=False`
+ - *contrastive search* if `penalty_alpha>0.` and `top_k>1`
+ - *multinomial sampling* if `num_beams=1` and `do_sample=True`
+ - *beam-search decoding* if `num_beams>1` and `do_sample=False`
+ - *beam-search multinomial sampling* if `num_beams>1` and `do_sample=True`
+ - *diverse beam-search decoding* if `num_beams>1` and `num_beam_groups>1`
+ - *constrained beam-search decoding* if `constraints!=None` or `force_words_ids!=None`
+ - *assisted decoding* if `assistant_model` or `prompt_lookup_num_tokens` is passed to `.generate()`
+ - *dola decoding* if `dola_layers` is passed to `.generate()`
+
+ To learn more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).
+
+
+
+ A large number of these flags control the logits or the stopping criteria of the generation. Make sure you check
+ the [generate-related classes](https://huggingface.co/docs/transformers/internal/generation_utils) for a full
+ description of the possible manipulations, as well as examples of their usage.
+
+
+
+ Arg:
+ > Parameters that control the length of the output
+
+ max_length (`int`, *optional*, defaults to 20):
+ The maximum length the generated tokens can have. Corresponds to the length of the input prompt +
+ `max_new_tokens`. Its effect is overridden by `max_new_tokens`, if also set.
+ max_new_tokens (`int`, *optional*):
+ The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.
+ min_length (`int`, *optional*, defaults to 0):
+ The minimum length of the sequence to be generated. Corresponds to the length of the input prompt +
+ `min_new_tokens`. Its effect is overridden by `min_new_tokens`, if also set.
+ min_new_tokens (`int`, *optional*):
+ The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt.
+ early_stopping (`bool` or `str`, *optional*, defaults to `False`):
+ Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:
+ `True`, where the generation stops as soon as there are `num_beams` complete candidates; `False`, where an
+ heuristic is applied and the generation stops when is it very unlikely to find better candidates;
+ `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical
+ beam search algorithm).
+ max_time (`float`, *optional*):
+ The maximum amount of time you allow the computation to run for in seconds. generation will still finish
+ the current pass after allocated time has been passed.
+ stop_strings (`str or List[str]`, *optional*):
+ A string or a list of strings that should terminate generation if the model outputs them.
+
+ > Parameters that control the generation strategy used
+
+ do_sample (`bool`, *optional*, defaults to `False`):
+ Whether or not to use sampling ; use greedy decoding otherwise.
+ num_beams (`int`, *optional*, defaults to 1):
+ Number of beams for beam search. 1 means no beam search.
+ num_beam_groups (`int`, *optional*, defaults to 1):
+ Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams.
+ [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
+ penalty_alpha (`float`, *optional*):
+ The values balance the model confidence and the degeneration penalty in contrastive search decoding.
+ dola_layers (`str` or `List[int]`, *optional*):
+ The layers to use for DoLa decoding. If `None`, DoLa decoding is not used. If a string, it must
+ be one of "low" or "high", which means using the lower part or higher part of the model layers, respectively.
+ "low" means the first half of the layers up to the first 20 layers, and "high" means the last half of the
+ layers up to the last 20 layers.
+ If a list of integers, it must contain the indices of the layers to use for candidate premature layers in DoLa.
+ The 0-th layer is the word embedding layer of the model. Set to `'low'` to improve long-answer reasoning tasks,
+ `'high'` to improve short-answer tasks. Check the [documentation](https://github.com/huggingface/transformers/blob/main/docs/source/en/generation_strategies.md)
+ or [the paper](https://arxiv.org/abs/2309.03883) for more details.
+
+ > Parameters that control the cache
+
+ use_cache (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should use the past last key/values attentions (if applicable to the model) to
+ speed up decoding.
+ cache_implementation (`str`, *optional*, default to `None`):
+ Name of the cache class that will be instantiated in `generate`, for faster decoding. Possible values are:
+
+ - `"static"`: [`StaticCache`]
+ - `"offloaded_static"`: [`OffloadedStaticCache`]
+ - `"sliding_window"`: [`SlidingWindowCache`]
+ - `"hybrid"`: [`HybridCache`]
+ - `"mamba"`: [`MambaCache`]
+ - `"quantized"`: [`QuantizedCache`]
+
+ We support other cache types, but they must be manually instantiated and
+ passed to `generate` through the `past_key_values` argument. See our
+ [cache documentation](https://huggingface.co/docs/transformers/en/kv_cache) for further information.
+ cache_config (`CacheConfig` or `dict`, *optional*, default to `None`):
+ Arguments used in the key-value cache class can be passed in `cache_config`. Can be passed as a `Dict` and
+ it will be converted to its repsective `CacheConfig` internally.
+ Otherwise can be passed as a `CacheConfig` class matching the indicated `cache_implementation`.
+ return_legacy_cache (`bool`, *optional*, default to `True`):
+ Whether to return the legacy or new format of the cache when `DynamicCache` is used by default.
+
+ > Parameters for manipulation of the model output logits
+
+ temperature (`float`, *optional*, defaults to 1.0):
+ The value used to module the next token probabilities. This value is set in a model's `generation_config.json` file. If it isn't set, the default value is 1.0
+ top_k (`int`, *optional*, defaults to 50):
+ The number of highest probability vocabulary tokens to keep for top-k-filtering. This value is set in a model's `generation_config.json` file. If it isn't set, the default value is 50.
+ top_p (`float`, *optional*, defaults to 1.0):
+ If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to
+ `top_p` or higher are kept for generation. This value is set in a model's `generation_config.json` file. If it isn't set, the default value is 1.0
+ min_p (`float`, *optional*):
+ Minimum token probability, which will be scaled by the probability of the most likely token. It must be a
+ value between 0 and 1. Typical values are in the 0.01-0.2 range, comparably selective as setting `top_p` in
+ the 0.99-0.8 range (use the opposite of normal `top_p` values).
+ typical_p (`float`, *optional*, defaults to 1.0):
+ Local typicality measures how similar the conditional probability of predicting a target token next is to
+ the expected conditional probability of predicting a random token next, given the partial text already
+ generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that
+ add up to `typical_p` or higher are kept for generation. See [this
+ paper](https://arxiv.org/pdf/2202.00666.pdf) for more details.
+ epsilon_cutoff (`float`, *optional*, defaults to 0.0):
+ If set to float strictly between 0 and 1, only tokens with a conditional probability greater than
+ `epsilon_cutoff` will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the
+ size of the model. See [Truncation Sampling as Language Model
+ Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
+ eta_cutoff (`float`, *optional*, defaults to 0.0):
+ Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between
+ 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) *
+ exp(-entropy(softmax(next_token_logits)))`. The latter term is intuitively the expected next token
+ probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3,
+ depending on the size of the model. See [Truncation Sampling as Language Model
+ Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
+ diversity_penalty (`float`, *optional*, defaults to 0.0):
+ This value is subtracted from a beam's score if it generates a token same as any beam from other group at a
+ particular time. Note that `diversity_penalty` is only effective if `group beam search` is enabled.
+ repetition_penalty (`float`, *optional*, defaults to 1.0):
+ The parameter for repetition penalty. 1.0 means no penalty. See [this
+ paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
+ encoder_repetition_penalty (`float`, *optional*, defaults to 1.0):
+ The paramater for encoder_repetition_penalty. An exponential penalty on sequences that are not in the
+ original input. 1.0 means no penalty.
+ length_penalty (`float`, *optional*, defaults to 1.0):
+ Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to
+ the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log
+ likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while
+ `length_penalty` < 0.0 encourages shorter sequences.
+ no_repeat_ngram_size (`int`, *optional*, defaults to 0):
+ If set to int > 0, all ngrams of that size can only occur once.
+ bad_words_ids (`List[List[int]]`, *optional*):
+ List of list of token ids that are not allowed to be generated. Check
+ [`~generation.NoBadWordsLogitsProcessor`] for further documentation and examples.
+ force_words_ids (`List[List[int]]` or `List[List[List[int]]]`, *optional*):
+ List of token ids that must be generated. If given a `List[List[int]]`, this is treated as a simple list of
+ words that must be included, the opposite to `bad_words_ids`. If given `List[List[List[int]]]`, this
+ triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one
+ can allow different forms of each word.
+ renormalize_logits (`bool`, *optional*, defaults to `False`):
+ Whether to renormalize the logits after applying all the logits processors (including the custom
+ ones). It's highly recommended to set this flag to `True` as the search algorithms suppose the score logits
+ are normalized but some logit processors break the normalization.
+ constraints (`List[Constraint]`, *optional*):
+ Custom constraints that can be added to the generation to ensure that the output will contain the use of
+ certain tokens as defined by `Constraint` objects, in the most sensible way possible.
+ forced_bos_token_id (`int`, *optional*, defaults to `model.config.forced_bos_token_id`):
+ The id of the token to force as the first generated token after the `decoder_start_token_id`. Useful for
+ multilingual models like [mBART](../model_doc/mbart) where the first generated token needs to be the target
+ language token.
+ forced_eos_token_id (`int` or List[int]`, *optional*, defaults to `model.config.forced_eos_token_id`):
+ The id of the token to force as the last generated token when `max_length` is reached. Optionally, use a
+ list to set multiple *end-of-sequence* tokens.
+ remove_invalid_values (`bool`, *optional*, defaults to `model.config.remove_invalid_values`):
+ Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash.
+ Note that using `remove_invalid_values` can slow down generation.
+ exponential_decay_length_penalty (`tuple(int, float)`, *optional*):
+ This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been
+ generated. The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where
+ penalty starts and `decay_factor` represents the factor of exponential decay
+ suppress_tokens (`List[int]`, *optional*):
+ A list of tokens that will be suppressed at generation. The `SupressTokens` logit processor will set their
+ log probs to `-inf` so that they are not sampled.
+ begin_suppress_tokens (`List[int]`, *optional*):
+ A list of tokens that will be suppressed at the beginning of the generation. The `SupressBeginTokens` logit
+ processor will set their log probs to `-inf` so that they are not sampled.
+ forced_decoder_ids (`List[List[int]]`, *optional*):
+ A list of pairs of integers which indicates a mapping from generation indices to token indices that will be
+ forced before sampling. For example, `[[1, 123]]` means the second generated token will always be a token
+ of index 123.
+ sequence_bias (`Dict[Tuple[int], float]`, *optional*)):
+ Dictionary that maps a sequence of tokens to its bias term. Positive biases increase the odds of the
+ sequence being selected, while negative biases do the opposite. Check
+ [`~generation.SequenceBiasLogitsProcessor`] for further documentation and examples.
+ token_healing (`bool`, *optional*, defaults to `False`):
+ Heal tail tokens of prompts by replacing them with their appropriate extensions.
+ This enhances the quality of completions for prompts affected by greedy tokenization bias.
+ guidance_scale (`float`, *optional*):
+ The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.
+ Higher guidance scale encourages the model to generate samples that are more closely linked to the input
+ prompt, usually at the expense of poorer quality.
+ low_memory (`bool`, *optional*):
+ Switch to sequential beam search and sequential topk for contrastive search to reduce peak memory.
+ Used with beam search and contrastive search.
+ watermarking_config (`BaseWatermarkingConfig` or `dict`, *optional*):
+ Arguments used to watermark the model outputs by adding a small bias to randomly selected set of "green"
+ tokens. See the docs of [`SynthIDTextWatermarkingConfig`] and [`WatermarkingConfig`] for more
+ details. If passed as `Dict`, it will be converted to a `WatermarkingConfig` internally.
+
+ > Parameters that define the output variables of generate
+
+ num_return_sequences (`int`, *optional*, defaults to 1):
+ The number of independently computed returned sequences for each element in the batch.
+ output_attentions (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more details.
+ output_hidden_states (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more details.
+ output_scores (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
+ output_logits (`bool`, *optional*):
+ Whether or not to return the unprocessed prediction logit scores. See `logits` under returned tensors for
+ more details.
+ return_dict_in_generate (`bool`, *optional*, defaults to `False`):
+ Whether or not to return a [`~utils.ModelOutput`], as opposed to returning exclusively the generated
+ sequence. This flag must be set to `True` to return the generation cache (when `use_cache` is `True`)
+ or optional outputs (see flags starting with `output_`)
+
+ > Special tokens that can be used at generation time
+
+ pad_token_id (`int`, *optional*):
+ The id of the *padding* token.
+ bos_token_id (`int`, *optional*):
+ The id of the *beginning-of-sequence* token.
+ eos_token_id (`Union[int, List[int]]`, *optional*):
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
+
+ > Generation parameters exclusive to encoder-decoder models
+
+ encoder_no_repeat_ngram_size (`int`, *optional*, defaults to 0):
+ If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the
+ `decoder_input_ids`.
+ decoder_start_token_id (`int` or `List[int]`, *optional*):
+ If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token or a list of length
+ `batch_size`. Indicating a list enables different start ids for each element in the batch
+ (e.g. multilingual models with different target languages in one batch)
+
+ > Generation parameters exclusive to assistant generation
+ is_assistant (`bool`, *optional*, defaults to `False`):
+ Whether the model is an assistant (draft) model.
+ num_assistant_tokens (`int`, *optional*, defaults to 20):
+ Defines the number of _speculative tokens_ that shall be generated by the assistant model before being
+ checked by the target model at each iteration. Higher values for `num_assistant_tokens` make the generation
+ more _speculative_ : If the assistant model is performant larger speed-ups can be reached, if the assistant
+ model requires lots of corrections, lower speed-ups are reached.
+ num_assistant_tokens_schedule (`str`, *optional*, defaults to `"constant"`):
+ Defines the schedule at which max assistant tokens shall be changed during inference.
+ - `"heuristic"`: When all speculative tokens are correct, increase `num_assistant_tokens` by 2 else
+ reduce by 1. `num_assistant_tokens` value is persistent over multiple generation calls with the same assistant model.
+ - `"heuristic_transient"`: Same as `"heuristic"` but `num_assistant_tokens` is reset to its initial value after each generation call.
+ - `"constant"`: `num_assistant_tokens` stays unchanged during generation
+ assistant_confidence_threshold (`float`, *optional*, defaults to 0.4):
+ The confidence threshold for the assistant model. If the assistant model's confidence in its prediction for the current token is lower
+ than this threshold, the assistant model stops the current token generation iteration, even if the number of _speculative tokens_
+ (defined by `num_assistant_tokens`) is not yet reached. The assistant's confidence threshold is adjusted throughout the speculative iterations to reduce the number of unnecessary draft and target forward passes, biased towards avoiding false negatives.
+ `assistant_confidence_threshold` value is persistent over multiple generation calls with the same assistant model.
+ It is an unsupervised version of the dynamic speculation lookahead
+ from Dynamic Speculation Lookahead Accelerates Speculative Decoding of Large Language Models .
+ prompt_lookup_num_tokens (`int`, *optional*):
+ The number of tokens to be output as candidate tokens.
+ max_matching_ngram_size (`int`, *optional*):
+ The maximum ngram size to be considered for matching in the prompt. Default to 2 if not provided.
+ assistant_early_exit(`int`, *optional*):
+ If set to a positive integer, early exit of the model will be used as an assistant. Can only be used with
+ models that support early exit (i.e. models where logits from intermediate layers can be interpreted by the LM head).
+ assistant_lookbehind(`int`, *optional*, defaults to 10):
+ If set to a positive integer, the re-encodeing process will additionally consider the last `assistant_lookbehind` assistant tokens
+ to correctly align tokens. Can only be used with different tokenizers in speculative decoding.
+ See this [blog](https://huggingface.co/blog/universal_assisted_generation) for more details.
+ target_lookbehind(`int`, *optional*, defaults to 10):
+ If set to a positive integer, the re-encodeing process will additionally consider the last `target_lookbehind` target tokens
+ to correctly align tokens. Can only be used with different tokenizers in speculative decoding.
+ See this [blog](https://huggingface.co/blog/universal_assisted_generation) for more details.
+
+ > Parameters related to performances and compilation
+
+ compile_config (CompileConfig, *optional*):
+ If using a static cache, this controls how `generate` will `compile` the forward pass for performance
+ gains.
+
+ disable_compile (`bool`, *optional*): Whether to disable the compilation of the forward pass when using 'statis' cache
+ implementation.
+
+ > Wild card
+
+ generation_kwargs:
+ Additional generation kwargs will be forwarded to the `generate` function of the model. Kwargs that are not
+ present in `generate`'s signature will be used in the model forward pass.
+ """
+
+ extra_output_flags = ("output_attentions", "output_hidden_states", "output_scores", "output_logits")
+
+ def __init__(self, **kwargs):
+ # Parameters that control the length of the output
+ self.max_length = kwargs.pop("max_length", 20)
+ self.max_new_tokens = kwargs.pop("max_new_tokens", None)
+ self.min_length = kwargs.pop("min_length", 0)
+ self.min_new_tokens = kwargs.pop("min_new_tokens", None)
+ self.early_stopping = kwargs.pop("early_stopping", False)
+ self.max_time = kwargs.pop("max_time", None)
+ self.stop_strings = kwargs.pop("stop_strings", None)
+
+ # Parameters that control the generation strategy used
+ self.do_sample = kwargs.pop("do_sample", False)
+ self.num_beams = kwargs.pop("num_beams", 1)
+ self.num_beam_groups = kwargs.pop("num_beam_groups", 1)
+ self.penalty_alpha = kwargs.pop("penalty_alpha", None)
+ self.dola_layers = kwargs.pop("dola_layers", None)
+
+ # Parameters that control the cache
+ self.use_cache = kwargs.pop("use_cache", True)
+ self.cache_implementation = kwargs.pop("cache_implementation", None)
+ self.cache_config = kwargs.pop("cache_config", None)
+ if self.cache_implementation is not None and self.cache_implementation in CACHE_CONFIG_MAPPING:
+ cache_config_class = CACHE_CONFIG_MAPPING[self.cache_implementation]
+ if isinstance(self.cache_config, dict):
+ self.cache_config = cache_config_class.from_dict(self.cache_config)
+ self.return_legacy_cache = kwargs.pop("return_legacy_cache", None)
+
+ # Parameters for manipulation of the model output logits
+ self.temperature = kwargs.pop("temperature", 1.0)
+ self.top_k = kwargs.pop("top_k", 50)
+ self.top_p = kwargs.pop("top_p", 1.0)
+ self.min_p = kwargs.pop("min_p", None)
+ self.typical_p = kwargs.pop("typical_p", 1.0)
+ self.epsilon_cutoff = kwargs.pop("epsilon_cutoff", 0.0)
+ self.eta_cutoff = kwargs.pop("eta_cutoff", 0.0)
+ self.diversity_penalty = kwargs.pop("diversity_penalty", 0.0)
+ self.repetition_penalty = kwargs.pop("repetition_penalty", 1.0)
+ self.encoder_repetition_penalty = kwargs.pop("encoder_repetition_penalty", 1.0)
+ self.length_penalty = kwargs.pop("length_penalty", 1.0)
+ self.no_repeat_ngram_size = kwargs.pop("no_repeat_ngram_size", 0)
+ self.bad_words_ids = kwargs.pop("bad_words_ids", None)
+ self.force_words_ids = kwargs.pop("force_words_ids", None)
+ self.renormalize_logits = kwargs.pop("renormalize_logits", False)
+ self.constraints = kwargs.pop("constraints", None)
+ self.forced_bos_token_id = kwargs.pop("forced_bos_token_id", None)
+ self.forced_eos_token_id = kwargs.pop("forced_eos_token_id", None)
+ self.remove_invalid_values = kwargs.pop("remove_invalid_values", False)
+ self.exponential_decay_length_penalty = kwargs.pop("exponential_decay_length_penalty", None)
+ self.suppress_tokens = kwargs.pop("suppress_tokens", None)
+ self.begin_suppress_tokens = kwargs.pop("begin_suppress_tokens", None)
+ self.forced_decoder_ids = kwargs.pop("forced_decoder_ids", None)
+ self.sequence_bias = kwargs.pop("sequence_bias", None)
+ self.token_healing = kwargs.pop("token_healing", False)
+ self.guidance_scale = kwargs.pop("guidance_scale", None)
+ self.low_memory = kwargs.pop("low_memory", None)
+ watermarking_config = kwargs.pop("watermarking_config", None)
+ if watermarking_config is None:
+ self.watermarking_config = None
+ elif isinstance(watermarking_config, BaseWatermarkingConfig):
+ self.watermarking_config = watermarking_config
+ else:
+ self.watermarking_config = WatermarkingConfig.from_dict(watermarking_config)
+
+ # Parameters that define the output variables of `generate`
+ self.num_return_sequences = kwargs.pop("num_return_sequences", 1)
+ self.output_attentions = kwargs.pop("output_attentions", False)
+ self.output_hidden_states = kwargs.pop("output_hidden_states", False)
+ self.output_scores = kwargs.pop("output_scores", False)
+ self.output_logits = kwargs.pop("output_logits", None)
+ self.return_dict_in_generate = kwargs.pop("return_dict_in_generate", False)
+
+ # Special tokens that can be used at generation time
+ self.pad_token_id = kwargs.pop("pad_token_id", None)
+ self.bos_token_id = kwargs.pop("bos_token_id", None)
+ self.eos_token_id = kwargs.pop("eos_token_id", None)
+
+ # Generation parameters exclusive to encoder-decoder models
+ self.encoder_no_repeat_ngram_size = kwargs.pop("encoder_no_repeat_ngram_size", 0)
+ self.decoder_start_token_id = kwargs.pop("decoder_start_token_id", None)
+
+ # Assistant generation
+ self.is_assistant = False
+ self.num_assistant_tokens = kwargs.pop("num_assistant_tokens", 20)
+ self.num_assistant_tokens_schedule = kwargs.pop("num_assistant_tokens_schedule", "constant")
+ self.assistant_confidence_threshold = kwargs.pop("assistant_confidence_threshold", 0.4)
+ self.prompt_lookup_num_tokens = kwargs.pop("prompt_lookup_num_tokens", None)
+ self.max_matching_ngram_size = kwargs.pop("max_matching_ngram_size", None)
+ self.assistant_early_exit = kwargs.pop("assistant_early_exit", None)
+ ## assistant generation for different tokenizers, the windows size for assistant/target model
+ self.assistant_lookbehind = kwargs.pop("assistant_lookbehind", 10)
+ self.target_lookbehind = kwargs.pop("target_lookbehind", 10)
+
+ # Performance
+ self.compile_config = kwargs.pop("compile_config", CompileConfig())
+ self.disable_compile = kwargs.pop("disable_compile", False)
+ # Wild card
+ self.generation_kwargs = kwargs.pop("generation_kwargs", {})
+
+ # The remaining attributes do not parametrize `.generate()`, but are informative and/or used by the hub
+ # interface.
+ self._from_model_config = kwargs.pop("_from_model_config", False)
+ self._commit_hash = kwargs.pop("_commit_hash", None)
+ self.transformers_version = kwargs.pop("transformers_version", __version__)
+
+ # Additional attributes without default values
+ if not self._from_model_config:
+ # we don't want to copy values from the model config if we're initializing a `GenerationConfig` from a
+ # model's default configuration file
+ for key, value in kwargs.items():
+ try:
+ setattr(self, key, value)
+ except AttributeError as err:
+ logger.error(f"Can't set {key} with value {value} for {self}")
+ raise err
+
+ # Validate the values of the attributes
+ self.validate(is_init=True)
+
+ def __hash__(self):
+ return hash(self.to_json_string(ignore_metadata=True))
+
+ def __eq__(self, other):
+ if not isinstance(other, GenerationConfig):
+ return False
+
+ self_without_metadata = self.to_json_string(use_diff=False, ignore_metadata=True)
+ other_without_metadata = other.to_json_string(use_diff=False, ignore_metadata=True)
+ return self_without_metadata == other_without_metadata
+
+ def __repr__(self):
+ return f"{self.__class__.__name__} {self.to_json_string(ignore_metadata=True)}"
+
+ def get_generation_mode(self, assistant_model: Optional["PreTrainedModel"] = None) -> GenerationMode:
+ """
+ Returns the generation mode triggered by the [`GenerationConfig`] instance.
+
+ Arg:
+ assistant_model (`PreTrainedModel`, *optional*):
+ The assistant model to be used for assisted generation. If set, the generation mode will be
+ assisted generation.
+
+ Returns:
+ `GenerationMode`: The generation mode triggered by the instance.
+ """
+ # TODO joao: find out a way of not depending on external fields (e.g. `assistant_model`), then make this a
+ # property and part of the `__repr__`
+ if self.constraints is not None or self.force_words_ids is not None:
+ generation_mode = GenerationMode.CONSTRAINED_BEAM_SEARCH
+ elif self.num_beams == 1:
+ if self.do_sample is False:
+ if (
+ self.top_k is not None
+ and self.top_k > 1
+ and self.penalty_alpha is not None
+ and self.penalty_alpha > 0
+ ):
+ generation_mode = GenerationMode.CONTRASTIVE_SEARCH
+ else:
+ generation_mode = GenerationMode.GREEDY_SEARCH
+ else:
+ generation_mode = GenerationMode.SAMPLE
+ else:
+ if self.num_beam_groups > 1:
+ generation_mode = GenerationMode.GROUP_BEAM_SEARCH
+ elif self.do_sample is True:
+ generation_mode = GenerationMode.BEAM_SAMPLE
+ else:
+ generation_mode = GenerationMode.BEAM_SEARCH
+
+ # Assisted generation may extend some generation modes
+ if (
+ assistant_model is not None
+ or self.prompt_lookup_num_tokens is not None
+ or self.assistant_early_exit is not None
+ ):
+ if generation_mode in ("greedy_search", "sample"):
+ generation_mode = GenerationMode.ASSISTED_GENERATION
+ else:
+ raise ValueError(
+ "You've set `assistant_model`, which triggers assisted generate. Currently, assisted generate "
+ "is only supported with Greedy Search and Sample."
+ )
+
+ # DoLa generation may extend some generation modes
+ if self.dola_layers is not None:
+ if generation_mode in ("greedy_search", "sample"):
+ generation_mode = GenerationMode.DOLA_GENERATION
+ else:
+ raise ValueError(
+ "You've set `dola_layers`, which triggers DoLa generate. Currently, DoLa generate "
+ "is only supported with Greedy Search and Sample."
+ )
+ return generation_mode
+
+ def validate(self, is_init=False):
+ """
+ Validates the values of the attributes of the [`GenerationConfig`] instance. Raises exceptions in the presence
+ of parameterization that can be detected as incorrect from the configuration instance alone.
+
+ Note that some parameters not validated here are best validated at generate runtime, as they may depend on
+ other inputs and/or the model, such as parameters related to the generation length.
+
+ Arg:
+ is_init (`bool`, *optional*, defaults to `False`):
+ Whether the validation is performed during the initialization of the instance.
+ """
+
+ # Validation of individual attributes
+ if self.early_stopping not in {True, False, "never"}:
+ raise ValueError(f"`early_stopping` must be a boolean or 'never', but is {self.early_stopping}.")
+ if self.max_new_tokens is not None and self.max_new_tokens <= 0:
+ raise ValueError(f"`max_new_tokens` must be greater than 0, but is {self.max_new_tokens}.")
+ if self.pad_token_id is not None and self.pad_token_id < 0:
+ warnings.warn(
+ f"`pad_token_id` should be positive but got {self.pad_token_id}. This will cause errors when batch "
+ "generating, if there is padding. Please set `pad_token_id` explicitly as "
+ "`model.generation_config.pad_token_id=PAD_TOKEN_ID` to avoid errors in generation"
+ )
+
+ # Validation of attribute relations:
+ fix_location = ""
+ if is_init:
+ fix_location = (
+ " This was detected when initializing the generation config instance, which means the corresponding "
+ "file may hold incorrect parameterization and should be fixed."
+ )
+
+ # 1. detect sampling-only parameterization when not in sampling mode
+ if self.do_sample is False:
+ greedy_wrong_parameter_msg = (
+ "`do_sample` is set to `False`. However, `{flag_name}` is set to `{flag_value}` -- this flag is only "
+ "used in sample-based generation modes. You should set `do_sample=True` or unset `{flag_name}`."
+ + fix_location
+ )
+ if self.temperature is not None and self.temperature != 1.0:
+ warnings.warn(
+ greedy_wrong_parameter_msg.format(flag_name="temperature", flag_value=self.temperature),
+ UserWarning,
+ )
+ if self.top_p is not None and self.top_p != 1.0:
+ warnings.warn(
+ greedy_wrong_parameter_msg.format(flag_name="top_p", flag_value=self.top_p),
+ UserWarning,
+ )
+ if self.min_p is not None:
+ warnings.warn(
+ greedy_wrong_parameter_msg.format(flag_name="min_p", flag_value=self.min_p),
+ UserWarning,
+ )
+ if self.typical_p is not None and self.typical_p != 1.0:
+ warnings.warn(
+ greedy_wrong_parameter_msg.format(flag_name="typical_p", flag_value=self.typical_p),
+ UserWarning,
+ )
+ if (
+ self.top_k is not None and self.top_k != 50 and self.penalty_alpha is None
+ ): # contrastive search uses top_k
+ warnings.warn(
+ greedy_wrong_parameter_msg.format(flag_name="top_k", flag_value=self.top_k),
+ UserWarning,
+ )
+ if self.epsilon_cutoff is not None and self.epsilon_cutoff != 0.0:
+ warnings.warn(
+ greedy_wrong_parameter_msg.format(flag_name="epsilon_cutoff", flag_value=self.epsilon_cutoff),
+ UserWarning,
+ )
+ if self.eta_cutoff is not None and self.eta_cutoff != 0.0:
+ warnings.warn(
+ greedy_wrong_parameter_msg.format(flag_name="eta_cutoff", flag_value=self.eta_cutoff),
+ UserWarning,
+ )
+
+ # 2. detect beam-only parameterization when not in beam mode
+ if self.num_beams is None:
+ warnings.warn("`num_beams` is set to None - defaulting to 1.", UserWarning)
+ self.num_beams = 1
+
+ if self.num_beams == 1:
+ single_beam_wrong_parameter_msg = (
+ "`num_beams` is set to 1. However, `{flag_name}` is set to `{flag_value}` -- this flag is only used "
+ "in beam-based generation modes. You should set `num_beams>1` or unset `{flag_name}`." + fix_location
+ )
+ if self.early_stopping is not False:
+ warnings.warn(
+ single_beam_wrong_parameter_msg.format(flag_name="early_stopping", flag_value=self.early_stopping),
+ UserWarning,
+ )
+ if self.num_beam_groups is not None and self.num_beam_groups != 1:
+ warnings.warn(
+ single_beam_wrong_parameter_msg.format(
+ flag_name="num_beam_groups", flag_value=self.num_beam_groups
+ ),
+ UserWarning,
+ )
+ if self.diversity_penalty is not None and self.diversity_penalty != 0.0:
+ warnings.warn(
+ single_beam_wrong_parameter_msg.format(
+ flag_name="diversity_penalty", flag_value=self.diversity_penalty
+ ),
+ UserWarning,
+ )
+ if self.length_penalty is not None and self.length_penalty != 1.0:
+ warnings.warn(
+ single_beam_wrong_parameter_msg.format(flag_name="length_penalty", flag_value=self.length_penalty),
+ UserWarning,
+ )
+ if self.constraints is not None:
+ warnings.warn(
+ single_beam_wrong_parameter_msg.format(flag_name="constraints", flag_value=self.constraints),
+ UserWarning,
+ )
+
+ # 3. detect incorrect paramaterization specific to advanced beam modes
+ else:
+ # constrained beam search
+ if self.constraints is not None or self.force_words_ids is not None:
+ constrained_wrong_parameter_msg = (
+ "one of `constraints`, `force_words_ids` is not `None`, triggering constrained beam search. However, "
+ "`{flag_name}` is set to `{flag_value}`, which is incompatible with this generation mode. Set "
+ "`constraints` and `force_words_ids` to `None` or unset `{flag_name}` to continue." + fix_location
+ )
+ if self.do_sample is True:
+ raise ValueError(
+ constrained_wrong_parameter_msg.format(flag_name="do_sample", flag_value=self.do_sample)
+ )
+ if self.num_beam_groups is not None and self.num_beam_groups != 1:
+ raise ValueError(
+ constrained_wrong_parameter_msg.format(
+ flag_name="num_beam_groups", flag_value=self.num_beam_groups
+ )
+ )
+ # group beam search
+ if self.diversity_penalty != 0.0 or self.num_beam_groups != 1:
+ group_error_prefix = (
+ "`diversity_penalty` is not 0.0 or `num_beam_groups` is not 1, triggering group beam search. In "
+ "this generation mode, "
+ )
+ if self.do_sample is True:
+ raise ValueError(group_error_prefix + "`do_sample` must be set to `False`")
+ if self.num_beams % self.num_beam_groups != 0:
+ raise ValueError(group_error_prefix + "`num_beams` should be divisible by `num_beam_groups`")
+ if self.diversity_penalty == 0.0:
+ raise ValueError(
+ group_error_prefix
+ + "`diversity_penalty` should be greater than `0.0`, otherwise your groups will be identical."
+ )
+ # DoLa generation
+ if self.dola_layers is not None and (self.repetition_penalty is None or self.repetition_penalty < 1.2):
+ warnings.warn(
+ "`dola_layers` is set to trigger DoLa decoding, but `repetition_penalty` is set to a value of "
+ f"{self.repetition_penalty}, which could induce unwanted repetition. The recommended value for "
+ "DoLa decoding is `repetition_penalty>=1.2`.",
+ UserWarning,
+ )
+
+ # 4. check `num_return_sequences`
+ if self.num_return_sequences != 1:
+ if self.num_beams == 1:
+ if self.do_sample is False:
+ raise ValueError(
+ "Greedy methods without beam search do not support `num_return_sequences` different than 1 "
+ f"(got {self.num_return_sequences})."
+ )
+ elif self.num_return_sequences > self.num_beams:
+ raise ValueError(
+ f"`num_return_sequences` ({self.num_return_sequences}) has to be smaller or equal to `num_beams` "
+ f"({self.num_beams})."
+ )
+
+ # 5. check cache-related arguments
+ if self.cache_implementation is not None and self.cache_implementation not in ALL_CACHE_IMPLEMENTATIONS:
+ raise ValueError(
+ f"Invalid `cache_implementation` ({self.cache_implementation}). Choose one of: "
+ f"{ALL_CACHE_IMPLEMENTATIONS}"
+ )
+ if self.cache_config is not None:
+ cache_class = CACHE_CONFIG_MAPPING.get(self.cache_implementation)
+ if cache_class is None:
+ raise ValueError(
+ "You provided a `cache_config` but the cache implementation you are using "
+ f"({self.cache_implementation}) does not require any config. Make sure to use the "
+ "correct cache implementation matching your cache config."
+ )
+ if not isinstance(self.cache_config, cache_class):
+ self.cache_config = cache_class.from_dict(self.cache_config)
+ self.cache_config.validate()
+ if self.use_cache is False:
+ # In this case, all cache-related arguments should be unset. However, since `use_cache=False` is often used
+ # passed to `generate` directly to hot-fix cache issues, let's raise a warning instead of an error
+ # (otherwise a user might need to overwrite several parameters).
+ no_cache_warning = (
+ "You have set `use_cache` to `False`, but {cache_arg} is set to {cache_arg_value}. {cache_arg} will "
+ "have no effect."
+ )
+ for arg_name in ("cache_implementation", "cache_config", "return_legacy_cache"):
+ if getattr(self, arg_name) is not None:
+ logger.warning_once(
+ no_cache_warning.format(cache_arg=arg_name, cache_arg_value=getattr(self, arg_name))
+ )
+
+ # 6. check watermarking arguments
+ if self.watermarking_config is not None:
+ if not (
+ isinstance(self.watermarking_config, WatermarkingConfig)
+ or isinstance(self.watermarking_config, SynthIDTextWatermarkingConfig)
+ ):
+ warnings.warn(
+ "`watermarking_config` as a dict is deprecated. Please construct `watermarking_config` object with "
+ "`WatermarkingConfig` or `SynthIDTextWatermarkingConfig` class.",
+ FutureWarning,
+ )
+ self.watermarking_config = WatermarkingConfig.from_dict(self.watermarking_config)
+ self.watermarking_config.validate()
+
+ # 7. performances arguments
+ if not isinstance(self.compile_config, CompileConfig):
+ raise ValueError(
+ f"You provided `compile_config` as an instance of {type(self.compile_config)}, but it must be an instance of `CompileConfig`."
+ )
+
+ # 8. other incorrect combinations
+ if self.return_dict_in_generate is not True:
+ for extra_output_flag in self.extra_output_flags:
+ if getattr(self, extra_output_flag) is True:
+ warnings.warn(
+ f"`return_dict_in_generate` is NOT set to `True`, but `{extra_output_flag}` is. When "
+ f"`return_dict_in_generate` is not `True`, `{extra_output_flag}` is ignored.",
+ UserWarning,
+ )
+
+ # 8. check common issue: passing `generate` arguments inside the generation config
+ generate_arguments = (
+ "logits_processor",
+ "stopping_criteria",
+ "prefix_allowed_tokens_fn",
+ "synced_gpus",
+ "assistant_model",
+ "streamer",
+ "negative_prompt_ids",
+ "negative_prompt_attention_mask",
+ )
+ for arg in generate_arguments:
+ if hasattr(self, arg):
+ raise ValueError(
+ f"Argument `{arg}` is not a valid argument of `GenerationConfig`. It should be passed to "
+ "`generate()` (or a pipeline) directly."
+ )
+
+ def save_pretrained(
+ self,
+ save_directory: Union[str, os.PathLike],
+ config_file_name: Optional[Union[str, os.PathLike]] = None,
+ push_to_hub: bool = False,
+ **kwargs,
+ ):
+ r"""
+ Save a generation configuration object to the directory `save_directory`, so that it can be re-loaded using the
+ [`~GenerationConfig.from_pretrained`] class method.
+
+ Args:
+ save_directory (`str` or `os.PathLike`):
+ Directory where the configuration JSON file will be saved (will be created if it does not exist).
+ config_file_name (`str` or `os.PathLike`, *optional*, defaults to `"generation_config.json"`):
+ Name of the generation configuration JSON file to be saved in `save_directory`.
+ push_to_hub (`bool`, *optional*, defaults to `False`):
+ Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
+ repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
+ namespace).
+ kwargs (`Dict[str, Any]`, *optional*):
+ Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
+ """
+
+ # At save time, validate the instance -- if any warning/exception is thrown, we refuse to save the instance.
+ # This strictness is enforced to prevent bad configurations from being saved and re-used.
+ try:
+ with warnings.catch_warnings(record=True) as caught_warnings:
+ self.validate()
+ if len(caught_warnings) > 0:
+ raise ValueError(str([w.message for w in caught_warnings]))
+ except ValueError as exc:
+ raise ValueError(
+ "The generation config instance is invalid -- `.validate()` throws warnings and/or exceptions. "
+ "Fix these issues to save the configuration.\n\nThrown during validation:\n" + str(exc)
+ )
+
+ use_auth_token = kwargs.pop("use_auth_token", None)
+
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. "
+ "Please use `token` instead.",
+ FutureWarning,
+ )
+ if kwargs.get("token", None) is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ kwargs["token"] = use_auth_token
+
+ config_file_name = config_file_name if config_file_name is not None else GENERATION_CONFIG_NAME
+
+ if os.path.isfile(save_directory):
+ raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
+
+ os.makedirs(save_directory, exist_ok=True)
+
+ if push_to_hub:
+ commit_message = kwargs.pop("commit_message", None)
+ repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
+ repo_id = self._create_repo(repo_id, **kwargs)
+ files_timestamps = self._get_files_timestamps(save_directory)
+
+ output_config_file = os.path.join(save_directory, config_file_name)
+
+ self.to_json_file(output_config_file, use_diff=True)
+ logger.info(f"Configuration saved in {output_config_file}")
+
+ if push_to_hub:
+ self._upload_modified_files(
+ save_directory,
+ repo_id,
+ files_timestamps,
+ commit_message=commit_message,
+ token=kwargs.get("token"),
+ )
+
+ @classmethod
+ def from_pretrained(
+ cls,
+ pretrained_model_name: Union[str, os.PathLike],
+ config_file_name: Optional[Union[str, os.PathLike]] = None,
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
+ force_download: bool = False,
+ local_files_only: bool = False,
+ token: Optional[Union[str, bool]] = None,
+ revision: str = "main",
+ **kwargs,
+ ) -> "GenerationConfig":
+ r"""
+ Instantiate a [`GenerationConfig`] from a generation configuration file.
+
+ Args:
+ pretrained_model_name (`str` or `os.PathLike`):
+ This can be either:
+
+ - a string, the *model id* of a pretrained model configuration hosted inside a model repo on
+ huggingface.co.
+ - a path to a *directory* containing a configuration file saved using the
+ [`~GenerationConfig.save_pretrained`] method, e.g., `./my_model_directory/`.
+ config_file_name (`str` or `os.PathLike`, *optional*, defaults to `"generation_config.json"`):
+ Name of the generation configuration JSON file to be loaded from `pretrained_model_name`.
+ 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`, or not specified, 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/"`.
+
+
+
+ return_unused_kwargs (`bool`, *optional*, defaults to `False`):
+ If `False`, then this function returns just the final configuration object.
+
+ If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where *unused_kwargs* is a
+ dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the
+ part of `kwargs` which has not been used to update `config` and is otherwise ignored.
+ 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.
+ kwargs (`Dict[str, Any]`, *optional*):
+ The values in kwargs of any keys which are configuration attributes will be used to override the loaded
+ values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled
+ by the `return_unused_kwargs` keyword parameter.
+
+ Returns:
+ [`GenerationConfig`]: The configuration object instantiated from this pretrained model.
+
+ Examples:
+
+ ```python
+ >>> from transformers import GenerationConfig
+
+ >>> # Download configuration from huggingface.co and cache.
+ >>> generation_config = GenerationConfig.from_pretrained("openai-community/gpt2")
+
+ >>> # E.g. config was saved using *save_pretrained('./test/saved_model/')*
+ >>> generation_config.save_pretrained("./test/saved_model/")
+ >>> generation_config = GenerationConfig.from_pretrained("./test/saved_model/")
+
+ >>> # You can also specify configuration names to your generation configuration file
+ >>> generation_config.save_pretrained("./test/saved_model/", config_file_name="my_configuration.json")
+ >>> generation_config = GenerationConfig.from_pretrained("./test/saved_model/", "my_configuration.json")
+
+ >>> # If you'd like to try a minor variation to an existing configuration, you can also pass generation
+ >>> # arguments to `.from_pretrained()`. Be mindful that typos and unused arguments will be ignored
+ >>> generation_config, unused_kwargs = GenerationConfig.from_pretrained(
+ ... "openai-community/gpt2", top_k=1, foo=False, do_sample=True, return_unused_kwargs=True
+ ... )
+ >>> generation_config.top_k
+ 1
+
+ >>> unused_kwargs
+ {'foo': False}
+ ```"""
+ config_file_name = config_file_name if config_file_name is not None else GENERATION_CONFIG_NAME
+
+ resume_download = kwargs.pop("resume_download", None)
+ proxies = kwargs.pop("proxies", None)
+ use_auth_token = kwargs.pop("use_auth_token", None)
+ subfolder = kwargs.pop("subfolder", "")
+ from_pipeline = kwargs.pop("_from_pipeline", None)
+ from_auto_class = kwargs.pop("_from_auto", False)
+ commit_hash = kwargs.pop("_commit_hash", 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
+
+ user_agent = {"file_type": "config", "from_auto_class": from_auto_class}
+ if from_pipeline is not None:
+ user_agent["using_pipeline"] = from_pipeline
+
+ config_path = os.path.join(pretrained_model_name, config_file_name)
+ config_path = str(config_path)
+
+ is_local = os.path.exists(config_path)
+ if os.path.isfile(os.path.join(subfolder, config_path)):
+ # Special case when config_path is a local file
+ resolved_config_file = config_path
+ is_local = True
+ elif is_remote_url(config_path):
+ configuration_file = config_path
+ resolved_config_file = download_url(config_path)
+ else:
+ configuration_file = config_file_name
+ try:
+ # Load from local folder or from cache or download from model Hub and cache
+ resolved_config_file = cached_file(
+ pretrained_model_name,
+ configuration_file,
+ 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,
+ )
+ commit_hash = extract_commit_hash(resolved_config_file, commit_hash)
+ except EnvironmentError:
+ # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to
+ # the original exception.
+ raise
+ except Exception:
+ # For any other exception, we throw a generic error.
+ raise EnvironmentError(
+ f"Can't load the configuration of '{pretrained_model_name}'. If you were trying to load it"
+ " from 'https://huggingface.co/models', make sure you don't have a local directory with the same"
+ f" name. Otherwise, make sure '{pretrained_model_name}' is the correct path to a directory"
+ f" containing a {configuration_file} file"
+ )
+
+ try:
+ # Load config dict
+ config_dict = cls._dict_from_json_file(resolved_config_file)
+ config_dict["_commit_hash"] = commit_hash
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ raise EnvironmentError(
+ f"It looks like the config file at '{resolved_config_file}' is not a valid JSON file."
+ )
+
+ if is_local:
+ logger.info(f"loading configuration file {resolved_config_file}")
+ else:
+ logger.info(f"loading configuration file {configuration_file} from cache at {resolved_config_file}")
+
+ if kwargs.get("return_unused_kwargs") is True:
+ config, unused_kwargs = cls.from_dict(config_dict, **kwargs)
+ config._original_object_hash = hash(config) # Hash to detect whether the instance was modified
+ return config, unused_kwargs
+ else:
+ config = cls.from_dict(config_dict, **kwargs)
+ config._original_object_hash = hash(config) # Hash to detect whether the instance was modified
+ return config
+
+ @classmethod
+ def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):
+ with open(json_file, "r", encoding="utf-8") as reader:
+ text = reader.read()
+ return json.loads(text)
+
+ @classmethod
+ def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "GenerationConfig":
+ """
+ Instantiates a [`GenerationConfig`] from a Python dictionary of parameters.
+
+ Args:
+ config_dict (`Dict[str, Any]`):
+ Dictionary that will be used to instantiate the configuration object.
+ kwargs (`Dict[str, Any]`):
+ Additional parameters from which to initialize the configuration object.
+
+ Returns:
+ [`GenerationConfig`]: The configuration object instantiated from those parameters.
+ """
+ return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
+ # Those arguments may be passed along for our internal telemetry.
+ # We remove them so they don't appear in `return_unused_kwargs`.
+ kwargs.pop("_from_auto", None)
+ kwargs.pop("_from_pipeline", None)
+ # The commit hash might have been updated in the `config_dict`, we don't want the kwargs to erase that update.
+ if "_commit_hash" in kwargs and "_commit_hash" in config_dict:
+ kwargs["_commit_hash"] = config_dict["_commit_hash"]
+
+ # The line below allows model-specific config to be loaded as well through kwargs, with safety checks.
+ # See https://github.com/huggingface/transformers/pull/21269
+ config = cls(**{**config_dict, **kwargs})
+ unused_kwargs = config.update(**kwargs)
+
+ logger.info(f"Generate config {config}")
+ if return_unused_kwargs:
+ return config, unused_kwargs
+ else:
+ return config
+
+ def dict_torch_dtype_to_str(self, d: Dict[str, Any]) -> None:
+ """
+ Checks whether the passed dictionary and its nested dicts have a *torch_dtype* key and if it's not None,
+ converts torch.dtype to a string of just the type. For example, `torch.float32` get converted into *"float32"*
+ string, which can then be stored in the json format.
+ """
+ if d.get("torch_dtype", None) is not None and not isinstance(d["torch_dtype"], str):
+ d["torch_dtype"] = str(d["torch_dtype"]).split(".")[1]
+ for value in d.values():
+ if isinstance(value, dict):
+ self.dict_torch_dtype_to_str(value)
+
+ 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 = GenerationConfig().to_dict()
+
+ serializable_config_dict = {}
+
+ # only serialize values that differ from the default config
+ for key, value in config_dict.items():
+ if key not in default_config_dict or key == "transformers_version" or value != default_config_dict[key]:
+ serializable_config_dict[key] = value
+
+ self.dict_torch_dtype_to_str(serializable_config_dict)
+ return serializable_config_dict
+
+ 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__)
+
+ # Fields to ignore at serialization time
+ if "_commit_hash" in output:
+ del output["_commit_hash"]
+ if "_original_object_hash" in output:
+ del output["_original_object_hash"]
+ if "compile_config" in output:
+ del output["compile_config"]
+
+ # Transformers version when serializing this file
+ output["transformers_version"] = __version__
+
+ self.dict_torch_dtype_to_str(output)
+ return output
+
+ def to_json_string(self, use_diff: bool = True, ignore_metadata: bool = False) -> 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 `GenerationConfig()`
+ is serialized to JSON string.
+ ignore_metadata (`bool`, *optional*, defaults to `False`):
+ Whether to ignore the metadata fields present in the instance
+
+ 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()
+
+ if ignore_metadata:
+ for metadata_field in METADATA_FIELDS:
+ config_dict.pop(metadata_field, None)
+
+ def convert_keys_to_string(obj):
+ if isinstance(obj, dict):
+ return {str(key): convert_keys_to_string(value) for key, value in obj.items()}
+ elif isinstance(obj, list):
+ return [convert_keys_to_string(item) for item in obj]
+ else:
+ return obj
+
+ def convert_dataclass_to_dict(obj):
+ if isinstance(obj, dict):
+ return {key: convert_dataclass_to_dict(value) for key, value in obj.items()}
+ elif is_dataclass(obj):
+ return obj.to_dict()
+ else:
+ return obj
+
+ config_dict = convert_keys_to_string(config_dict)
+ config_dict = convert_dataclass_to_dict(config_dict)
+
+ return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
+
+ def to_json_file(self, json_file_path: Union[str, os.PathLike], use_diff: bool = True):
+ """
+ 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 `GenerationConfig()`
+ is serialized to JSON file.
+ """
+ with open(json_file_path, "w", encoding="utf-8") as writer:
+ writer.write(self.to_json_string(use_diff=use_diff))
+
+ @classmethod
+ def from_model_config(cls, model_config: PretrainedConfig) -> "GenerationConfig":
+ """
+ Instantiates a [`GenerationConfig`] from a [`PretrainedConfig`]. This function is useful to convert legacy
+ [`PretrainedConfig`] objects, which may contain generation parameters, into a stand-alone [`GenerationConfig`].
+
+ Args:
+ model_config (`PretrainedConfig`):
+ The model config that will be used to instantiate the generation config.
+
+ Returns:
+ [`GenerationConfig`]: The configuration object instantiated from those parameters.
+ """
+ config_dict = model_config.to_dict()
+ config_dict.pop("_from_model_config", None)
+
+ # Removes all `None` from the model config dict -- this lets the generation config defaults to take hold
+ config_dict = {key: value for key, value in config_dict.items() if value is not None}
+
+ generation_config = cls.from_dict(config_dict, return_unused_kwargs=False, _from_model_config=True)
+
+ # Special case: some models have generation attributes set in the decoder. Use them if still unset in the
+ # generation config (which in turn is defined from the outer attributes of model config).
+ decoder_config = model_config.get_text_config(decoder=True)
+ if decoder_config is not model_config:
+ default_generation_config = GenerationConfig()
+ decoder_config_dict = decoder_config.to_dict()
+ for attr in generation_config.to_dict().keys():
+ is_unset = getattr(generation_config, attr) == getattr(default_generation_config, attr)
+ if attr in decoder_config_dict and is_unset:
+ setattr(generation_config, attr, decoder_config_dict[attr])
+
+ # If any `output_...` flag is set to `True`, we ensure `return_dict_in_generate` is set to `True`.
+ if generation_config.return_dict_in_generate is False:
+ if any(
+ getattr(generation_config, extra_output_flag, False)
+ for extra_output_flag in generation_config.extra_output_flags
+ ):
+ generation_config.return_dict_in_generate = True
+
+ # Hash to detect whether the instance was modified
+ generation_config._original_object_hash = hash(generation_config)
+ return generation_config
+
+ 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)
+
+ # Confirm that the updated instance is still valid
+ self.validate()
+
+ # 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 BaseWatermarkingConfig(ABC):
+ """Generic watermarking config"""
+
+ @classmethod
+ def from_dict(cls, config_dict, **kwargs):
+ """
+ Constructs a BaseWatermarkingConfig instance from a dictionary of parameters.
+
+ Args:
+ config_dict (Dict[str, Any]): Dictionary containing configuration parameters.
+ **kwargs: Additional keyword arguments to override dictionary values.
+
+ Returns:
+ BaseWatermarkingConfig: Instance of BaseWatermarkingConfig constructed from the dictionary.
+ """
+ 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)
+ 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 (Union[str, os.PathLike]): Path to the JSON file in which this configuration instance's parameters will be saved.
+ """
+ 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.
+ """
+ output = copy.deepcopy(self.__dict__)
+ return output
+
+ def __iter__(self):
+ 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):
+ """
+ Serializes this instance to a JSON formatted string.
+
+ Returns:
+ str: JSON formatted string representing the configuration instance.
+ """
+ return json.dumps(self.__dict__, indent=2) + "\n"
+
+ def update(self, **kwargs):
+ """
+ Update the configuration attributes with new values.
+
+ Args:
+ **kwargs: Keyword arguments representing configuration attributes and their new values.
+ """
+ for key, value in kwargs.items():
+ if hasattr(self, key):
+ setattr(self, key, value)
+
+ @abstractmethod
+ def validate(self): ...
+
+ @abstractmethod
+ def construct_processor(self, vocab_size): ...
+
+
+@dataclass
+class WatermarkingConfig(BaseWatermarkingConfig):
+ """
+ Class that holds arguments for watermark generation and should be passed into `GenerationConfig` during `generate`.
+ See [this paper](https://arxiv.org/abs/2306.04634) for more details on the arguments.
+
+ Accepts the following keys:
+ - greenlist_ratio (`float`):
+ Used for watermarking. The ratio of "green" tokens used to the vocabulary size. Defaults to 0.25.
+ - bias (`float`):
+ Used with watermarking. The bias added to the selected "green" tokens' logits. Defaults to 2.0.
+ - hashing_key (`int`):
+ Hashing key used for watermarking. Defaults to 15485863 (the millionth prime).
+ - seeding_scheme (`str`):
+ Algorithm to use for watermarking. Accepts values:
+ - "lefthash" (default): "green" tokens selection depend on the last token (Algorithm 2 from the paper)
+ - "selfhash": "green" tokens selection depends on the current token itself (Algorithm 3 from the paper)
+ The downside of this scheme is that it considers all possible next tokens and can be slower than "lefthash".
+ - context_width(`int`):
+ The context length of previous tokens to use in seeding. Higher context length makes watermarking more robust.
+ """
+
+ def __init__(
+ self,
+ greenlist_ratio: Optional[float] = 0.25,
+ bias: Optional[float] = 2.0,
+ hashing_key: Optional[int] = 15485863,
+ seeding_scheme: Optional[str] = "lefthash",
+ context_width: Optional[int] = 1,
+ ):
+ self.greenlist_ratio = greenlist_ratio
+ self.bias = bias
+ self.hashing_key = hashing_key
+ self.seeding_scheme = seeding_scheme
+ self.context_width = context_width
+
+ def validate(self):
+ watermark_missing_arg_msg = (
+ "Some of the keys in `watermarking_config` are defined incorrectly. `{key}` should be {correct_value}` "
+ "but found {found_value}"
+ )
+ if self.seeding_scheme not in ["selfhash", "lefthash"]:
+ raise ValueError(
+ watermark_missing_arg_msg.format(
+ key="seeding_scheme",
+ correct_value="[`selfhash`, `lefthash`]",
+ found_value=self.seeding_scheme,
+ ),
+ )
+ if not 0.0 <= self.greenlist_ratio <= 1.0:
+ raise ValueError(
+ watermark_missing_arg_msg.format(
+ key="greenlist_ratio",
+ correct_value="in range between 0.0 and 1.0",
+ found_value=self.seeding_scheme,
+ ),
+ )
+ if not self.context_width >= 1:
+ raise ValueError(
+ watermark_missing_arg_msg.format(
+ key="context_width",
+ correct_value="a positive integer",
+ found_value=self.context_width,
+ ),
+ )
+
+ def construct_processor(self, vocab_size: int, device) -> "WatermarkLogitsProcessor":
+ return WatermarkLogitsProcessor(
+ vocab_size=vocab_size,
+ device=device,
+ greenlist_ratio=self.greenlist_ratio,
+ bias=self.bias,
+ hashing_key=self.hashing_key,
+ seeding_scheme=self.seeding_scheme,
+ context_width=self.context_width,
+ )
+
+
+@dataclass
+class SynthIDTextWatermarkingConfig(BaseWatermarkingConfig):
+ """
+ Class that holds arguments for watermark generation and should be passed into `GenerationConfig` during `generate`.
+ See [this paper](https://www.nature.com/articles/s41586-024-08025-4) for more details on the arguments.
+
+ Args:
+ ngram_len (`int`):
+ Ngram length.
+ keys (`List[int]`):
+ A sequence of watermarking keys, one for each depth.
+ context_history_size (`int`, *optional*, defaults to 1024):
+ Size of the tensor to keep track of seen contexts.
+ sampling_table_seed (`int`, *optional*, defaults to 0):
+ Random seed to generate the sampling table.
+ sampling_table_size (`int`, *optional*, defaults to 65536):
+ Size of the sampling table.
+ skip_first_ngram_calls (`bool`, *optional*, defaults to `False`):
+ Whether to skip first ngram calls.
+ debug_mode (`bool`, optional, *optional*, defaults to `False`):
+ Logits are modified to uniform one got before watermarking modification is applied. This is to test the
+ implementation.
+
+ Examples:
+ ```python
+ >>> from transformers import AutoModelForCausalLM, AutoTokenizer, SynthIDTextWatermarkingConfig
+
+ >>> tokenizer = AutoTokenizer.from_pretrained('google/gemma-2-2b', padding_side="left")
+ >>> model = AutoModelForCausalLM.from_pretrained('google/gemma-2-2b')
+
+ >>> # SynthID Text configuration
+ >>> watermarking_config = SynthIDTextWatermarkingConfig(
+ ... keys=[654, 400, 836, 123, 340, 443, 597, 160, 57],
+ ... ngram_len=5,
+ ... )
+
+ >>> # Generation with watermarking
+ >>> tokenized_prompts = tokenizer(["Once upon a time, "], return_tensors="pt", padding=True)
+ >>> output_sequences = model.generate(
+ ... **tokenized_prompts, watermarking_config=watermarking_config, do_sample=True, max_new_tokens=10
+ ... )
+ >>> watermarked_text = tokenizer.batch_decode(output_sequences, skip_special_tokens=True)
+ ```
+ """
+
+ def __init__(
+ self,
+ ngram_len: int,
+ keys: List[int],
+ context_history_size: int = 1024,
+ sampling_table_seed: int = 0,
+ sampling_table_size: int = 2**16,
+ skip_first_ngram_calls: bool = False,
+ debug_mode: bool = False,
+ ):
+ self.ngram_len = ngram_len
+ self.keys = keys
+ self.sampling_table_size = sampling_table_size
+ self.sampling_table_seed = sampling_table_seed
+ self.context_history_size = context_history_size
+ self.skip_first_ngram_calls = skip_first_ngram_calls
+ self.debug_mode = debug_mode
+
+ def validate(self):
+ watermark_missing_arg_msg = (
+ "Some of the keys in `watermarking_config` are defined incorrectly. `{key}` should be {correct_value}` "
+ "but found {found_value}"
+ )
+ if self.sampling_table_size > 2**24:
+ raise ValueError(
+ watermark_missing_arg_msg.format(
+ key="sampling_table_size",
+ correct_value="< 2**24",
+ found_value=self.sampling_table_size,
+ ),
+ )
+
+ def construct_processor(self, vocab_size: int, device) -> "WatermarkLogitsProcessor":
+ return SynthIDTextWatermarkLogitsProcessor(
+ ngram_len=self.ngram_len,
+ keys=self.keys,
+ sampling_table_size=self.sampling_table_size,
+ sampling_table_seed=self.sampling_table_seed,
+ context_history_size=self.context_history_size,
+ device=device,
+ skip_first_ngram_calls=self.skip_first_ngram_calls,
+ debug_mode=self.debug_mode,
+ )
+
+
+@dataclass
+class CompileConfig:
+ """
+ Class that holds arguments relative to `torch.compile` behavior, when using automatic compilation in `generate`.
+ See [`torch.compile`](https://pytorch.org/docs/stable/generated/torch.compile.html) for more details on the arguments.
+
+ Args:
+ fullgraph (`bool`, *optional*, defaults to `True`):
+ If `True`, requires that the whole forward be capturable in a single graph.
+ dynamic (`bool` or `None`, *optional*):
+ Whether to try to use dynamic shape graphs.
+ backend (`str` or `Callable`, *optional*, defaults to `"inductor"`):
+ Backend to be used.
+ mode (`str`, *optional*, defaults to `"reduce-overhead"`):
+ Controls balance between performance and overhead.
+ options (`dict`, *optional*):
+ A dictionary of options to pass to the backend.
+
+ Examples:
+ ```python
+ >>> from transformers import AutoModelForCausalLM, AutoTokenizer, CompileConfig
+
+ >>> tokenizer = AutoTokenizer.from_pretrained('google/gemma-2-2b')
+ >>> model = AutoModelForCausalLM.from_pretrained('google/gemma-2-2b').cuda()
+
+ >>> # Automatic compile configuration, used with static cache
+ >>> compile_config = CompileConfig(dynamic=True)
+
+ >>> # Generation with static cache and compile config
+ >>> input = tokenizer.encode("Hello there, how", return_tensors="pt").cuda()
+ >>> output = model.generate(
+ ... input, do_sample=False, max_new_tokens=300, cache_implementation="static", compile_config=compile_config
+ ... )
+ >>> output_text = tokenizer.batch_decode(output, skip_special_tokens=True)[0]
+ ```
+ """
+
+ fullgraph: bool = True
+ dynamic: Optional[bool] = None
+ backend: Union[str, Callable] = "inductor"
+ mode: str = "reduce-overhead"
+ options: Optional[dict] = None
+ # Used to flag our `generate` call to compile on e.g. CPU. Often not optimal, but useful for testing purposes.
+ _compile_all_devices = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Serializes this instance to a Python dictionary."""
+ return copy.deepcopy({key: value for key, value in self.__dict__.items() if key != "_compile_all_devices"})
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/flax_logits_process.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/flax_logits_process.py
new file mode 100644
index 0000000000000000000000000000000000000000..d106c32defa4db3577d3a72158550d355aa5ece7
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/flax_logits_process.py
@@ -0,0 +1,544 @@
+# 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 inspect
+
+import jax
+import jax.lax as lax
+import jax.numpy as jnp
+from jax.experimental import sparse
+
+from ..utils import add_start_docstrings
+from ..utils.logging import get_logger
+
+
+logger = get_logger(__name__)
+
+
+LOGITS_PROCESSOR_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):
+ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam
+ search or log softmax for each vocabulary token when using beam search
+ kwargs (`Dict[str, Any]`, *optional*):
+ Additional logits processor specific kwargs.
+
+ Return:
+ `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.
+
+"""
+
+
+class FlaxLogitsProcessor:
+ """Abstract base class for all logit processors that can be applied during generation."""
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: jnp.ndarray, scores: jnp.ndarray) -> jnp.ndarray:
+ """Flax method for processing logits."""
+ raise NotImplementedError(
+ f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
+ )
+
+
+class FlaxLogitsWarper:
+ """Abstract base class for all logit warpers that can be applied during generation with multinomial sampling."""
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: jnp.ndarray, scores: jnp.ndarray) -> jnp.ndarray:
+ """Flax method for warping logits."""
+ raise NotImplementedError(
+ f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
+ )
+
+
+class FlaxLogitsProcessorList(list):
+ """
+ This class can be used to create a list of [`FlaxLogitsProcessor`] or [`FlaxLogitsWarper`] to subsequently process
+ a `scores` input tensor. This class inherits from list and adds a specific *__call__* method to apply each
+ [`FlaxLogitsProcessor`] or [`FlaxLogitsWarper`] to the inputs.
+ """
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: jnp.ndarray, scores: jnp.ndarray, cur_len: int, **kwargs) -> jnp.ndarray:
+ for processor in self:
+ function_args = inspect.signature(processor.__call__).parameters
+ if len(function_args) > 3:
+ if not all(arg in kwargs for arg in list(function_args.keys())[2:]):
+ raise ValueError(
+ f"Make sure that all the required parameters: {list(function_args.keys())} for "
+ f"{processor.__class__} are passed to the logits processor."
+ )
+ scores = processor(input_ids, scores, cur_len, **kwargs)
+ else:
+ scores = processor(input_ids, scores, cur_len)
+ return scores
+
+
+class FlaxTemperatureLogitsWarper(FlaxLogitsWarper):
+ r"""
+ [`FlaxLogitsWarper`] for temperature (exponential scaling output probability distribution).
+
+ Args:
+ temperature (`float`):
+ The value used to module the logits distribution.
+ """
+
+ def __init__(self, temperature: float):
+ if not isinstance(temperature, float) or not (temperature > 0):
+ raise ValueError(f"`temperature` has to be a strictly positive float, but is {temperature}")
+
+ self.temperature = temperature
+
+ def __call__(self, input_ids: jnp.ndarray, scores: jnp.ndarray, cur_len: int) -> jnp.ndarray:
+ scores = scores / self.temperature
+ return scores
+
+
+class FlaxTopPLogitsWarper(FlaxLogitsWarper):
+ """
+ [`FlaxLogitsWarper`] that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off.
+
+ Args:
+ top_p (`float`):
+ If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or
+ higher are kept for generation.
+ filter_value (`float`, *optional*, defaults to -inf):
+ All filtered values will be set to this float value.
+ min_tokens_to_keep (`int`, *optional*, defaults to 1):
+ Minimum number of tokens that cannot be filtered.
+ """
+
+ def __init__(self, top_p: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
+ if not isinstance(top_p, float) or (top_p < 0 or top_p > 1.0):
+ raise ValueError(f"`top_p` has to be a float > 0 and < 1, but is {top_p}")
+ if not isinstance(min_tokens_to_keep, int) or (min_tokens_to_keep < 1):
+ raise ValueError(f"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}")
+
+ self.top_p = top_p
+ self.filter_value = filter_value
+ self.min_tokens_to_keep = min_tokens_to_keep
+
+ def __call__(self, input_ids: jnp.ndarray, scores: jnp.ndarray, cur_len: int) -> jnp.ndarray:
+ topk_scores, topk_indices = lax.top_k(scores, scores.shape[-1])
+
+ mask_scores = jnp.full_like(scores, self.filter_value)
+ cumulative_probs = jax.nn.softmax(topk_scores, axis=-1).cumsum(axis=-1)
+ score_mask = cumulative_probs < self.top_p
+
+ # include the token that is higher than top_p as well
+ score_mask = jnp.roll(score_mask, 1)
+ score_mask |= score_mask.at[:, 0].set(True)
+
+ # min tokens to keep
+ score_mask = score_mask.at[:, : self.min_tokens_to_keep].set(True)
+
+ topk_next_scores = jnp.where(score_mask, topk_scores, mask_scores)
+ next_scores = jax.lax.sort_key_val(topk_indices, topk_next_scores)[-1]
+
+ return next_scores
+
+
+class FlaxTopKLogitsWarper(FlaxLogitsWarper):
+ r"""
+ [`FlaxLogitsWarper`] that performs top-k, i.e. restricting to the k highest probability elements.
+
+ Args:
+ top_k (`int`):
+ The number of highest probability vocabulary tokens to keep for top-k-filtering.
+ filter_value (`float`, *optional*, defaults to -inf):
+ All filtered values will be set to this float value.
+ min_tokens_to_keep (`int`, *optional*, defaults to 1):
+ Minimum number of tokens that cannot be filtered.
+ """
+
+ def __init__(self, top_k: int, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
+ if not isinstance(top_k, int) or top_k <= 0:
+ raise ValueError(f"`top_k` has to be a strictly positive integer, but is {top_k}")
+
+ self.top_k = max(top_k, min_tokens_to_keep)
+ self.filter_value = filter_value
+
+ def __call__(self, input_ids: jnp.ndarray, scores: jnp.ndarray, cur_len: int) -> jnp.ndarray:
+ batch_size, vocab_size = scores.shape
+ next_scores_flat = jnp.full(batch_size * vocab_size, self.filter_value)
+
+ topk = min(self.top_k, scores.shape[-1]) # Safety check
+ topk_scores, topk_indices = lax.top_k(scores, topk)
+ shift = jnp.broadcast_to((jnp.arange(batch_size) * vocab_size)[:, None], (batch_size, topk)).flatten()
+ topk_scores_flat = topk_scores.flatten()
+ topk_indices_flat = topk_indices.flatten() + shift
+
+ next_scores_flat = next_scores_flat.at[topk_indices_flat].set(topk_scores_flat)
+ next_scores = next_scores_flat.reshape(batch_size, vocab_size)
+ return next_scores
+
+
+class FlaxForcedBOSTokenLogitsProcessor(FlaxLogitsProcessor):
+ r"""
+ [`FlaxLogitsProcessor`] that enforces the specified token as the first generated token.
+
+ Args:
+ bos_token_id (`int`):
+ The id of the token to force as the first generated token.
+ """
+
+ def __init__(self, bos_token_id: int):
+ self.bos_token_id = bos_token_id
+
+ def __call__(self, input_ids: jnp.ndarray, scores: jnp.ndarray, cur_len: int) -> jnp.ndarray:
+ new_scores = jnp.full(scores.shape, -float("inf"))
+
+ apply_penalty = 1 - jnp.bool_(cur_len - 1)
+
+ scores = jnp.where(apply_penalty, new_scores.at[:, self.bos_token_id].set(0), scores)
+
+ return scores
+
+
+class FlaxForcedEOSTokenLogitsProcessor(FlaxLogitsProcessor):
+ r"""
+ [`FlaxLogitsProcessor`] that enforces the specified token as the last generated token when `max_length` is reached.
+
+ Args:
+ max_length (`int`):
+ The maximum length of the sequence to be generated.
+ eos_token_id (`int`):
+ The id of the token to force as the last generated token when `max_length` is reached.
+ """
+
+ def __init__(self, max_length: int, eos_token_id: int):
+ self.max_length = max_length
+ self.eos_token_id = eos_token_id
+
+ def __call__(self, input_ids: jnp.ndarray, scores: jnp.ndarray, cur_len: int) -> jnp.ndarray:
+ new_scores = jnp.full(scores.shape, -float("inf"))
+
+ apply_penalty = 1 - jnp.bool_(cur_len - self.max_length + 1)
+
+ scores = jnp.where(apply_penalty, new_scores.at[:, self.eos_token_id].set(0), scores)
+
+ return scores
+
+
+class FlaxMinLengthLogitsProcessor(FlaxLogitsProcessor):
+ r"""
+ [`FlaxLogitsProcessor`] enforcing a min-length by setting EOS probability to 0.
+
+ Args:
+ min_length (`int`):
+ The minimum length below which the score of `eos_token_id` is set to `-float("Inf")`.
+ eos_token_id (`int`):
+ The id of the *end-of-sequence* token.
+ """
+
+ def __init__(self, min_length: int, eos_token_id: int):
+ if not isinstance(min_length, int) or min_length < 0:
+ raise ValueError(f"`min_length` has to be a positive integer, but is {min_length}")
+
+ if not isinstance(eos_token_id, int) or eos_token_id < 0:
+ raise ValueError(f"`eos_token_id` has to be a positive integer, but is {eos_token_id}")
+
+ self.min_length = min_length
+ self.eos_token_id = eos_token_id
+
+ def __call__(self, input_ids: jnp.ndarray, scores: jnp.ndarray, cur_len: int) -> jnp.ndarray:
+ # create boolean flag to decide if min length penalty should be applied
+ apply_penalty = 1 - jnp.clip(cur_len - self.min_length, 0, 1)
+
+ scores = jnp.where(apply_penalty, scores.at[:, self.eos_token_id].set(-float("inf")), scores)
+
+ return scores
+
+
+class FlaxSuppressTokensAtBeginLogitsProcessor(FlaxLogitsProcessor):
+ r"""
+ [`FlaxLogitsProcessor`] supressing a list of tokens as soon as the `generate` function starts generating using
+ `begin_index` tokens. This should ensure that the tokens defined by `begin_suppress_tokens` are not sampled at the
+ beginning of the generation.
+
+ Args:
+ begin_suppress_tokens (`List[int]`):
+ Tokens to not sample.
+ begin_index (`int`):
+ Index where the tokens are suppressed.
+ """
+
+ def __init__(self, begin_suppress_tokens, begin_index):
+ self.begin_suppress_tokens = list(begin_suppress_tokens)
+ self.begin_index = begin_index
+
+ def __call__(self, input_ids, scores, cur_len: int):
+ apply_penalty = 1 - jnp.bool_(cur_len - self.begin_index)
+
+ scores = jnp.where(apply_penalty, scores.at[:, self.begin_suppress_tokens].set(-float("inf")), scores)
+
+ return scores
+
+
+class FlaxSuppressTokensLogitsProcessor(FlaxLogitsProcessor):
+ r"""
+ [`FlaxLogitsProcessor`] suppressing a list of tokens at each decoding step. The processor will set their log probs
+ to be `-inf` so they are not sampled.
+
+ Args:
+ suppress_tokens (`list`):
+ Tokens to not sample.
+ """
+
+ def __init__(self, suppress_tokens: list):
+ self.suppress_tokens = list(suppress_tokens)
+
+ def __call__(self, input_ids: jnp.ndarray, scores: jnp.ndarray, cur_len: int) -> jnp.ndarray:
+ scores = scores.at[..., self.suppress_tokens].set(-float("inf"))
+
+ return scores
+
+
+class FlaxForceTokensLogitsProcessor(FlaxLogitsProcessor):
+ r"""
+ [`FlaxLogitsProcessor`] that takes a list of pairs of integers which indicates a mapping from generation indices to
+ token indices that will be forced before sampling. The processor will set their log probs to 0 and all other tokens
+ to `-inf` so that they are sampled at their corresponding index.
+
+ Args:
+ force_token_map (`list`):
+ Map giving token ids and indices where they will be forced to be sampled.
+ """
+
+ def __init__(self, force_token_map):
+ force_token_map = dict(force_token_map)
+ # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the
+ # index of the array corresponds to the index of the token to be forced, for XLA compatibility.
+ # Indexes without forced tokens will have a negative value.
+ force_token_array = jnp.ones((max(force_token_map.keys()) + 1), dtype=jnp.int32) * -1
+ for index, token in force_token_map.items():
+ if token is not None:
+ force_token_array = force_token_array.at[index].set(token)
+ self.force_token_array = jnp.int32(force_token_array)
+
+ def __call__(self, input_ids: jnp.ndarray, scores: jnp.ndarray, cur_len: int) -> jnp.ndarray:
+ def _force_token(generation_idx):
+ batch_size = scores.shape[0]
+ current_token = self.force_token_array[generation_idx]
+
+ new_scores = jnp.ones_like(scores, dtype=scores.dtype) * -float("inf")
+ updates = jnp.zeros((batch_size, 1), dtype=scores.dtype)
+ new_scores = lax.dynamic_update_slice(new_scores, updates, (0, current_token))
+ return new_scores
+
+ scores = lax.cond(
+ cur_len >= self.force_token_array.shape[0],
+ # If the current length is geq than the length of force_token_array, the processor does nothing.
+ lambda: scores,
+ # Otherwise, it may force a certain token.
+ lambda: lax.cond(
+ self.force_token_array[cur_len] >= 0,
+ # Only valid (positive) tokens are forced
+ lambda: _force_token(cur_len),
+ # Otherwise, the processor does nothing.
+ lambda: scores,
+ ),
+ )
+ return scores
+
+
+class FlaxWhisperTimeStampLogitsProcessor(FlaxLogitsProcessor):
+ r"""
+ Whisper specific Processor. This processor can be used to force a list of tokens. The processor will set their log
+ probs to `inf` so that they are sampled at their corresponding index.
+
+ Args:
+ generate_config (`GenerateConfig`):
+ The generate config used to generate the output. The following parameters are required:
+ eos_token_id (`int`, *optional*, defaults to 50257):
+ The id of the *end-of-sequence* token.
+ no_timestamps_token_id (`int`, *optional*, defaults to 50363):
+ The id of the `"<|notimestamps|>"` token.
+ max_initial_timestamp_index (`int`, *optional*, defaults to 1):
+ Used to set the maximum value of the initial timestamp. This is used to prevent the model from
+ predicting timestamps that are too far in the future.
+ """
+
+ def __init__(self, generate_config, model_config, decoder_input_length):
+ self.eos_token_id = generate_config.eos_token_id
+ self.no_timestamps_token_id = generate_config.no_timestamps_token_id
+ self.timestamp_begin = generate_config.no_timestamps_token_id + 1
+
+ self.begin_index = decoder_input_length + 1
+
+ if generate_config.is_multilingual:
+ # room for language token and task token
+ self.begin_index += 2
+ if hasattr(generate_config, "max_initial_timestamp_index"):
+ self.max_initial_timestamp_index = generate_config.max_initial_timestamp_index
+ else:
+ self.max_initial_timestamp_index = model_config.vocab_size
+ if self.max_initial_timestamp_index is None:
+ self.max_initial_timestamp_index = model_config.vocab_size
+
+ def __call__(self, input_ids, scores, cur_len):
+ # suppress <|notimestamps|> which is handled by without_timestamps
+ scores = scores.at[:, self.no_timestamps_token_id].set(-float("inf"))
+
+ def handle_pairs(input_ids_k, scores_k):
+ last_was_timestamp = jnp.where((cur_len - self.begin_index) >= 1, True, False)
+ last_was_timestamp = jnp.where(
+ input_ids_k[cur_len - 1] >= self.timestamp_begin,
+ True and last_was_timestamp,
+ False,
+ )
+
+ penultimate_was_timestamp = jnp.where((cur_len - self.begin_index) < 2, True, False)
+ penultimate_was_timestamp = jnp.where(
+ input_ids_k[cur_len - 2] >= self.timestamp_begin,
+ True,
+ penultimate_was_timestamp,
+ )
+
+ return jnp.where(
+ last_was_timestamp,
+ jnp.where(
+ penultimate_was_timestamp > 0,
+ scores_k.at[self.timestamp_begin :].set(-float("inf")),
+ scores_k.at[: self.eos_token_id].set(-float("inf")),
+ ),
+ scores_k,
+ )
+
+ scores = jax.vmap(handle_pairs)(input_ids, scores)
+
+ apply_max_initial_timestamp = jnp.where(cur_len == self.begin_index, True, False)
+ apply_max_initial_timestamp = jnp.where(
+ self.max_initial_timestamp_index is not None,
+ True and apply_max_initial_timestamp,
+ False,
+ )
+
+ last_allowed = self.timestamp_begin + self.max_initial_timestamp_index
+
+ scores = jnp.where(
+ apply_max_initial_timestamp,
+ scores.at[:, last_allowed + 1 :].set(-float("inf")),
+ scores,
+ )
+
+ # if sum of probability over timestamps is above any other token, sample timestamp
+ logprobs = jax.nn.log_softmax(scores, axis=-1)
+
+ def handle_cumulative_probs(logprobs_k, scores_k):
+ timestamp_logprob = jax.nn.logsumexp(logprobs_k[self.timestamp_begin :], axis=-1)
+ max_text_token_logprob = jnp.max(logprobs_k[: self.timestamp_begin])
+ return jnp.where(
+ timestamp_logprob > max_text_token_logprob,
+ scores_k.at[: self.timestamp_begin].set(-float("inf")),
+ scores_k,
+ )
+
+ scores = jax.vmap(handle_cumulative_probs)(logprobs, scores)
+
+ return scores
+
+
+class FlaxNoRepeatNGramLogitsProcessor(FlaxLogitsProcessor):
+ r"""
+ [`FlaxLogitsProcessor`] that enforces no repetition of n-grams. See
+ [Fairseq](https://github.com/pytorch/fairseq/blob/a07cb6f40480928c9e0548b737aadd36ee66ac76/fairseq/sequence_generator.py#L345).
+
+ Args:
+ ngram_size (`int`):
+ All ngrams of size `ngram_size` can only occur once.
+ """
+
+ def __init__(self, ngram_size: int):
+ if not isinstance(ngram_size, int) or ngram_size <= 0:
+ raise ValueError(f"`ngram_size` has to be a strictly positive integer, but is {ngram_size}")
+ self.ngram_size = ngram_size
+
+ def get_previous_ngrams(self, input_ids: jnp.ndarray, vocab_size: int, cur_len: int):
+ """
+ get a matrix of size (batch_size,) + (vocab_size,)*n (for n-grams) that
+ represent the n-grams that occurred previously.
+ The BCOO representation allow to store only the few non-zero entries, instead of the full (huge) matrix
+ """
+ batch_size, seq_len = input_ids.shape
+ # number of n-grams in the whole sequence
+ seq_ngrams = seq_len - (self.ngram_size - 1)
+ # number of n-grams in the currently generated sequence
+ cur_ngrams = cur_len - (self.ngram_size - 1)
+
+ def body_fun(i, val):
+ b = i % batch_size
+ pos = i // batch_size
+ return val.at[i].set(
+ jnp.array(
+ [
+ b,
+ ]
+ + [jnp.array(input_ids)[b, pos + j] for j in range(self.ngram_size)]
+ )
+ )
+
+ shape = (batch_size * seq_ngrams, self.ngram_size + 1)
+ all_update_indices = jax.lax.fori_loop(
+ 0, batch_size * cur_ngrams, body_fun, jnp.zeros(shape, dtype=input_ids.dtype)
+ )
+
+ # ignore the n-grams not yet generated
+ data = (jnp.arange(batch_size * seq_ngrams) < batch_size * cur_ngrams).astype("float32")
+
+ return sparse.BCOO((data, all_update_indices), shape=(batch_size,) + (vocab_size,) * self.ngram_size)
+
+ def get_banned_tokens_mask(self, latest_tokens: jnp.ndarray, previous_ngrams) -> jnp.ndarray:
+ """
+ Determines which tokens must be banned given latest tokens and the previously seen
+ ngrams.
+ """
+
+ @sparse.sparsify
+ @jax.vmap
+ def inner_fn(latest_tokens, previous_ngrams):
+ return previous_ngrams[tuple(latest_tokens)]
+
+ return sparse.bcoo_todense(inner_fn(latest_tokens, previous_ngrams))
+
+ def __call__(self, input_ids: jnp.ndarray, scores: jnp.ndarray, cur_len: int) -> jnp.ndarray:
+ def true_fn():
+ _, vocab_size = scores.shape
+ # store the previously seen n-grams
+ previous_ngrams = self.get_previous_ngrams(input_ids, vocab_size, cur_len)
+
+ # get the n-1 last tokens that prefix the n-gram being generated
+ latest_tokens = jnp.zeros((input_ids.shape[0], self.ngram_size - 1), dtype=input_ids.dtype)
+ latest_tokens = jax.lax.dynamic_update_slice(
+ latest_tokens,
+ jax.lax.dynamic_slice(
+ input_ids, (0, cur_len - (self.ngram_size - 1)), (input_ids.shape[0], (self.ngram_size - 1))
+ ),
+ (0, 0),
+ )
+
+ # compute the banned tokens, ie all the tokens that when added to the latest tokens lead to a n-gram that was previously generated
+ banned_tokens_indices_mask = self.get_banned_tokens_mask(latest_tokens, previous_ngrams).astype("bool")
+ return jnp.where(banned_tokens_indices_mask, -float("inf"), scores)
+
+ output = jax.lax.cond((cur_len >= self.ngram_size - 1), true_fn, lambda: scores)
+ return output
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/flax_utils.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/flax_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f6f2a0041c919a003052a04bc0c18323d937c6e
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/flax_utils.py
@@ -0,0 +1,1027 @@
+# coding=utf-8
+# Copyright 2021 The Google AI Flax Team Authors, and The HuggingFace Inc. team.
+# Copyright (c) 2020, NVIDIA CORPORATION. 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 inspect
+import warnings
+from functools import partial
+from typing import Any, Dict, Optional, Union
+
+import flax
+import jax
+import jax.numpy as jnp
+import numpy as np
+from jax import lax
+
+from ..models.auto import (
+ FLAX_MODEL_FOR_CAUSAL_LM_MAPPING,
+ FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
+ FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING,
+)
+from ..utils import ModelOutput, logging
+from .configuration_utils import GenerationConfig
+from .flax_logits_process import (
+ FlaxForcedBOSTokenLogitsProcessor,
+ FlaxForcedEOSTokenLogitsProcessor,
+ FlaxForceTokensLogitsProcessor,
+ FlaxLogitsProcessorList,
+ FlaxMinLengthLogitsProcessor,
+ FlaxNoRepeatNGramLogitsProcessor,
+ FlaxSuppressTokensAtBeginLogitsProcessor,
+ FlaxSuppressTokensLogitsProcessor,
+ FlaxTemperatureLogitsWarper,
+ FlaxTopKLogitsWarper,
+ FlaxTopPLogitsWarper,
+)
+
+
+logger = logging.get_logger(__name__)
+
+
+@flax.struct.dataclass
+class FlaxGreedySearchOutput(ModelOutput):
+ """
+ Flax Base class for outputs of decoder-only generation models using greedy search.
+
+
+ Args:
+ sequences (`jnp.ndarray` of shape `(batch_size, max_length)`):
+ The generated sequences.
+ """
+
+ sequences: jnp.ndarray = None
+
+
+@flax.struct.dataclass
+class FlaxSampleOutput(ModelOutput):
+ """
+ Flax Base class for outputs of decoder-only generation models using sampling.
+
+
+ Args:
+ sequences (`jnp.ndarray` of shape `(batch_size, max_length)`):
+ The generated sequences.
+ """
+
+ sequences: jnp.ndarray = None
+
+
+@flax.struct.dataclass
+class FlaxBeamSearchOutput(ModelOutput):
+ """
+ Flax Base class for outputs of decoder-only generation models using greedy search.
+
+
+ Args:
+ sequences (`jnp.ndarray` of shape `(batch_size, max_length)`):
+ The generated sequences.
+ scores (`jnp.ndarray` of shape `(batch_size,)`):
+ The scores (log probabilities) of the generated sequences.
+ """
+
+ sequences: jnp.ndarray = None
+ scores: jnp.ndarray = None
+
+
+@flax.struct.dataclass
+class GreedyState:
+ cur_len: jnp.ndarray
+ sequences: jnp.ndarray
+ running_token: jnp.ndarray
+ is_sent_finished: jnp.ndarray
+ model_kwargs: Dict[str, jnp.ndarray]
+
+
+@flax.struct.dataclass
+class SampleState:
+ cur_len: jnp.ndarray
+ sequences: jnp.ndarray
+ running_token: jnp.ndarray
+ is_sent_finished: jnp.ndarray
+ prng_key: jnp.ndarray
+ model_kwargs: Dict[str, jnp.ndarray]
+
+
+@flax.struct.dataclass
+class BeamSearchState:
+ cur_len: jnp.ndarray
+ running_sequences: jnp.ndarray
+ running_scores: jnp.ndarray
+ sequences: jnp.ndarray
+ scores: jnp.ndarray
+ is_sent_finished: jnp.ndarray
+ model_kwargs: Dict[str, jnp.ndarray]
+
+
+class FlaxGenerationMixin:
+ """
+ A class containing all functions for auto-regressive text generation, to be used as a mixin in
+ [`FlaxPreTrainedModel`].
+
+ The class exposes [`~generation.FlaxGenerationMixin.generate`], which can be used for:
+ - *greedy decoding* by calling [`~generation.FlaxGenerationMixin._greedy_search`] if `num_beams=1` and
+ `do_sample=False`
+ - *multinomial sampling* by calling [`~generation.FlaxGenerationMixin._sample`] if `num_beams=1` and
+ `do_sample=True`
+ - *beam-search decoding* by calling [`~generation.FlaxGenerationMixin._beam_search`] if `num_beams>1` and
+ `do_sample=False`
+
+ You do not need to call any of the above methods directly. Pass custom parameter values to 'generate' instead. To
+ learn more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).
+ """
+
+ def prepare_inputs_for_generation(self, *args, **kwargs):
+ raise NotImplementedError(
+ "A model class needs to define a `prepare_inputs_for_generation` method in order to use `generate`."
+ )
+
+ @staticmethod
+ def _run_loop_in_debug(cond_fn, body_fn, init_state):
+ """
+ Run generation in untraced mode. This should only be used for debugging purposes.
+ """
+ state = init_state
+ while cond_fn(state):
+ state = body_fn(state)
+ return state
+
+ def _prepare_encoder_decoder_kwargs_for_generation(self, input_ids, params, model_kwargs):
+ encoder_kwargs = {
+ argument: value
+ for argument, value in model_kwargs.items()
+ if not (argument.startswith("decoder_") or argument.startswith("cross_attn"))
+ }
+ model_kwargs["encoder_outputs"] = self.encode(input_ids, params=params, return_dict=True, **encoder_kwargs)
+ return model_kwargs
+
+ def _prepare_decoder_input_ids_for_generation(
+ self,
+ batch_size: int,
+ decoder_start_token_id: int = None,
+ bos_token_id: int = None,
+ model_kwargs: Optional[Dict[str, jnp.ndarray]] = None,
+ ) -> jnp.ndarray:
+ if model_kwargs is not None and "decoder_input_ids" in model_kwargs:
+ # Only use this arg if not None, otherwise just remove from model_kwargs
+ decoder_input_ids = model_kwargs.pop("decoder_input_ids")
+ if decoder_input_ids is not None:
+ return decoder_input_ids
+ decoder_start_token_id = self._get_decoder_start_token_id(decoder_start_token_id, bos_token_id)
+ return jnp.array(decoder_start_token_id, dtype="i4").reshape(1, -1).repeat(batch_size, axis=0)
+
+ def _get_decoder_start_token_id(self, decoder_start_token_id: int = None, bos_token_id: int = None) -> int:
+ # retrieve decoder_start_token_id for encoder-decoder models
+ # fall back to bos_token_id if necessary
+ decoder_start_token_id = (
+ decoder_start_token_id
+ if decoder_start_token_id is not None
+ else self.generation_config.decoder_start_token_id
+ )
+ bos_token_id = bos_token_id if bos_token_id is not None else self.generation_config.bos_token_id
+ if decoder_start_token_id is not None:
+ return decoder_start_token_id
+ elif (
+ hasattr(self.config, "decoder")
+ and hasattr(self.config.decoder, "decoder_start_token_id")
+ and self.config.decoder.decoder_start_token_id is not None
+ ):
+ return self.config.decoder.decoder_start_token_id
+ elif bos_token_id is not None:
+ return bos_token_id
+ elif (
+ hasattr(self.config, "decoder")
+ and hasattr(self.config.decoder, "bos_token_id")
+ and self.config.decoder.bos_token_id is not None
+ ):
+ return self.config.decoder.bos_token_id
+ raise ValueError(
+ "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation."
+ )
+
+ @staticmethod
+ def _expand_to_num_beams(tensor, num_beams):
+ return jnp.broadcast_to(tensor[:, None], (tensor.shape[0], num_beams) + tensor.shape[1:])
+
+ def _adapt_logits_for_beam_search(self, logits):
+ """
+ This function can be overwritten in the specific modeling_flax_.py classes to allow for custom beam
+ search behavior. Note that the only model that overwrites this method is [`~transformes.FlaxMarianMTModel`].
+ """
+ return logits
+
+ def _validate_model_class(self):
+ """
+ Confirms that the model class is compatible with generation. If not, raises an exception that points to the
+ right class to use.
+ """
+ if not self.can_generate():
+ generate_compatible_mappings = [
+ FLAX_MODEL_FOR_CAUSAL_LM_MAPPING,
+ FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING,
+ FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
+ ]
+ generate_compatible_classes = set()
+ for model_mapping in generate_compatible_mappings:
+ supported_models = model_mapping.get(type(self.config), default=None)
+ if supported_models is not None:
+ generate_compatible_classes.add(supported_models.__name__)
+ exception_message = (
+ f"The current model class ({self.__class__.__name__}) is not compatible with `.generate()`, as "
+ "it doesn't have a language model head."
+ )
+ if generate_compatible_classes:
+ exception_message += f" Please use one of the following classes instead: {generate_compatible_classes}"
+ raise TypeError(exception_message)
+
+ def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]):
+ """Validates model kwargs for generation. Generate argument typos will also be caught here."""
+ unused_model_args = []
+ model_args = set(inspect.signature(self.prepare_inputs_for_generation).parameters)
+ # `kwargs`/`model_kwargs` is often used to handle optional forward pass inputs like `attention_mask`. If
+ # `prepare_inputs_for_generation` doesn't accept them, then a stricter check can be made ;)
+ if "kwargs" in model_args or "model_kwargs" in model_args:
+ model_args |= set(inspect.signature(self.__call__).parameters)
+ for key, value in model_kwargs.items():
+ if value is not None and key not in model_args:
+ unused_model_args.append(key)
+
+ if unused_model_args:
+ raise ValueError(
+ f"The following `model_kwargs` are not used by the model: {unused_model_args} (note: typos in the"
+ " generate arguments will also show up in this list)"
+ )
+
+ def generate(
+ self,
+ input_ids: jnp.ndarray,
+ generation_config: Optional[GenerationConfig] = None,
+ prng_key: Optional[jnp.ndarray] = None,
+ trace: bool = True,
+ params: Optional[Dict[str, jnp.ndarray]] = None,
+ logits_processor: Optional[FlaxLogitsProcessorList] = None,
+ **kwargs,
+ ):
+ r"""
+ Generates sequences of token ids for models with a language modeling head.
+
+ Parameters:
+ input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
+ The sequence used as a prompt for the generation.
+ generation_config (`~generation.GenerationConfig`, *optional*):
+ The generation configuration to be used as base parametrization for the generation call. `**kwargs`
+ passed to generate matching the attributes of `generation_config` will override them. If
+ `generation_config` is not provided, the default will be used, which had the following loading
+ priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
+ configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
+ default values, whose documentation should be checked to parameterize generation.
+ trace (`bool`, *optional*, defaults to `True`):
+ Whether to trace generation. Setting `trace=False` should only be used for debugging and will lead to a
+ considerably slower runtime.
+ params (`Dict[str, jnp.ndarray]`, *optional*):
+ Optionally the model parameters can be passed. Can be useful for parallelized generation.
+ logits_processor (`FlaxLogitsProcessorList `, *optional*):
+ Custom logits processors that complement the default logits processors built from arguments and
+ generation config. If a logit processor is passed that is already created with the arguments or a
+ generation config an error is thrown. This feature is intended for advanced users.
+ kwargs (`Dict[str, Any]`, *optional*):
+ Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be
+ forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
+ specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.
+
+ Return:
+ [`~utils.ModelOutput`].
+
+ """
+ # Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call
+ self._validate_model_class()
+
+ # priority: `generation_config` argument > `model.generation_config` (the default generation config)
+ if generation_config is None:
+ # legacy: users may modify the model configuration to control generation. To trigger this legacy behavior,
+ # two conditions must be met
+ # 1) the generation config must have been created from the model config (`_from_model_config` field);
+ # 2) the generation config must have seen no modification since its creation (the hash is the same).
+ if self.generation_config._from_model_config and self.generation_config._original_object_hash == hash(
+ self.generation_config
+ ):
+ new_generation_config = GenerationConfig.from_model_config(self.config)
+ if new_generation_config != self.generation_config:
+ warnings.warn(
+ "You have modified the pretrained model configuration to control generation. This is a"
+ " deprecated strategy to control generation and will be removed soon, in a future version."
+ " Please use and modify the model generation configuration (see"
+ " https://huggingface.co/docs/transformers/generation_strategies#default-text-generation-configuration )"
+ )
+ self.generation_config = new_generation_config
+ generation_config = self.generation_config
+
+ generation_config = copy.deepcopy(generation_config)
+ model_kwargs = generation_config.update(**kwargs) # All unused kwargs must be model kwargs
+ self._validate_model_kwargs(model_kwargs.copy())
+
+ logits_processor = logits_processor if logits_processor is not None else FlaxLogitsProcessorList()
+
+ # set init values
+ prng_key = prng_key if prng_key is not None else jax.random.PRNGKey(0)
+
+ if generation_config.pad_token_id is None and generation_config.eos_token_id is not None:
+ if model_kwargs.get("attention_mask") is None:
+ logger.warning(
+ "The attention mask and the pad token id were not set. As a consequence, you may observe "
+ "unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results."
+ )
+ eos_token_id = generation_config.eos_token_id
+ if isinstance(eos_token_id, list):
+ eos_token_id = eos_token_id[0]
+ generation_config.pad_token_id = eos_token_id
+
+ if generation_config.decoder_start_token_id is None and self.config.is_encoder_decoder:
+ raise ValueError("`decoder_start_token_id` has to be defined for encoder-decoder generation.")
+
+ # decoder-only models should use left-padding for generation (can't be checked with `trace=True`)
+ if not self.config.is_encoder_decoder and not trace:
+ if (
+ generation_config.pad_token_id is not None
+ and jnp.sum(input_ids[:, -1] == generation_config.pad_token_id) > 0
+ ):
+ logger.warning(
+ "A decoder-only architecture is being used, but right-padding was detected! For correct "
+ "generation results, please set `padding_side='left'` when initializing the tokenizer."
+ )
+
+ batch_size = input_ids.shape[0]
+
+ if self.config.is_encoder_decoder:
+ # add encoder_outputs to model_kwargs
+ if model_kwargs.get("encoder_outputs") is None:
+ model_kwargs = self._prepare_encoder_decoder_kwargs_for_generation(input_ids, params, model_kwargs)
+ # prepare decoder_input_ids for generation
+ input_ids = self._prepare_decoder_input_ids_for_generation(
+ batch_size,
+ decoder_start_token_id=generation_config.decoder_start_token_id,
+ bos_token_id=generation_config.bos_token_id,
+ model_kwargs=model_kwargs,
+ )
+
+ # Prepare `max_length` depending on other stopping criteria.
+ input_ids_seq_length = input_ids.shape[-1]
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
+ if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length == 20:
+ # 20 is the default max_length of the generation config
+ warnings.warn(
+ f"Using the model-agnostic default `max_length` (={generation_config.max_length}) "
+ "to control the generation length. recommend setting `max_new_tokens` to control the maximum length of the generation.",
+ UserWarning,
+ )
+ elif generation_config.max_new_tokens is not None:
+ if not has_default_max_length and generation_config.max_length is not None:
+ logger.warning(
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
+ "Please refer to the documentation for more information. "
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
+ )
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
+ else: # by default let's always generate 20 new tokens
+ if generation_config.max_length == GenerationConfig().max_length:
+ generation_config.max_length = generation_config.max_length + input_ids_seq_length
+ max_position_embeddings = getattr(self.config, "max_position_embeddings", None)
+ if max_position_embeddings is not None:
+ generation_config.max_length = min(generation_config.max_length, max_position_embeddings)
+
+ if generation_config.min_length is not None and generation_config.min_length > generation_config.max_length:
+ raise ValueError(
+ f"Unfeasable length constraints: the minimum length ({generation_config.min_length}) is larger than"
+ f" the maximum length ({generation_config.max_length})"
+ )
+ if input_ids_seq_length >= generation_config.max_length:
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
+ logger.warning(
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
+ " increasing`max_new_tokens`."
+ )
+
+ logits_processor = self._get_logits_processor(
+ generation_config=generation_config,
+ input_ids_seq_length=input_ids_seq_length,
+ logits_processor=logits_processor,
+ )
+
+ if not generation_config.do_sample and generation_config.num_beams == 1:
+ return self._greedy_search(
+ input_ids,
+ generation_config.max_length,
+ generation_config.pad_token_id,
+ generation_config.eos_token_id,
+ logits_processor=logits_processor,
+ trace=trace,
+ params=params,
+ model_kwargs=model_kwargs,
+ )
+ elif generation_config.do_sample and generation_config.num_beams == 1:
+ logits_warper = self._get_logits_warper(generation_config=generation_config)
+ return self._sample(
+ input_ids,
+ generation_config.max_length,
+ generation_config.pad_token_id,
+ generation_config.eos_token_id,
+ prng_key,
+ logits_warper=logits_warper,
+ logits_processor=logits_processor,
+ trace=trace,
+ params=params,
+ model_kwargs=model_kwargs,
+ )
+ elif not generation_config.do_sample and generation_config.num_beams > 1:
+ # broadcast input_ids & encoder_outputs
+ input_ids = self._expand_to_num_beams(input_ids, num_beams=generation_config.num_beams)
+
+ if "encoder_outputs" in model_kwargs:
+ model_kwargs["encoder_outputs"]["last_hidden_state"] = self._expand_to_num_beams(
+ model_kwargs["encoder_outputs"]["last_hidden_state"], num_beams=generation_config.num_beams
+ )
+
+ for kwarg in ["attention_mask", "decoder_attention_mask"]:
+ if kwarg in model_kwargs:
+ model_kwargs[kwarg] = self._expand_to_num_beams(
+ model_kwargs[kwarg], num_beams=generation_config.num_beams
+ )
+
+ return self._beam_search(
+ input_ids,
+ generation_config.max_length,
+ generation_config.pad_token_id,
+ generation_config.eos_token_id,
+ length_penalty=generation_config.length_penalty,
+ early_stopping=generation_config.early_stopping,
+ logits_processor=logits_processor,
+ trace=trace,
+ params=params,
+ num_return_sequences=generation_config.num_return_sequences,
+ model_kwargs=model_kwargs,
+ )
+ else:
+ raise NotImplementedError("`Beam sampling is currently not implemented.")
+
+ def _get_logits_warper(self, generation_config: GenerationConfig) -> FlaxLogitsProcessorList:
+ """
+ This class returns a [`FlaxLogitsProcessorList`] list object that contains all relevant [`FlaxLogitsWarper`]
+ instances used for multinomial sampling.
+ """
+ warpers = FlaxLogitsProcessorList()
+
+ if generation_config.temperature is not None and generation_config.temperature != 1.0:
+ warpers.append(FlaxTemperatureLogitsWarper(generation_config.temperature))
+ if generation_config.top_k is not None and generation_config.top_k != 0:
+ warpers.append(FlaxTopKLogitsWarper(top_k=generation_config.top_k, min_tokens_to_keep=1))
+ if generation_config.top_p is not None and generation_config.top_p < 1.0:
+ warpers.append(FlaxTopPLogitsWarper(top_p=generation_config.top_p, min_tokens_to_keep=1))
+
+ return warpers
+
+ def _get_logits_processor(
+ self,
+ generation_config: GenerationConfig,
+ input_ids_seq_length: int,
+ logits_processor: Optional[FlaxLogitsProcessorList],
+ ) -> FlaxLogitsProcessorList:
+ """
+ This class returns a [`FlaxLogitsProcessorList`] list object that contains all relevant [`FlaxLogitsProcessor`]
+ instances used to modify the scores of the language model head.
+ """
+ processors = FlaxLogitsProcessorList()
+
+ if (
+ generation_config.min_length is not None
+ and generation_config.eos_token_id is not None
+ and generation_config.min_length > -1
+ ):
+ processors.append(
+ FlaxMinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id)
+ )
+ if generation_config.forced_bos_token_id is not None:
+ processors.append(FlaxForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id))
+ if generation_config.forced_eos_token_id is not None:
+ processors.append(
+ FlaxForcedEOSTokenLogitsProcessor(generation_config.max_length, generation_config.forced_eos_token_id)
+ )
+ if generation_config.suppress_tokens is not None:
+ processors.append(FlaxSuppressTokensLogitsProcessor(generation_config.suppress_tokens))
+ if generation_config.begin_suppress_tokens is not None:
+ begin_index = input_ids_seq_length
+ begin_index = (
+ begin_index
+ if (input_ids_seq_length > 1 or generation_config.forced_bos_token_id is None)
+ else begin_index + 1
+ )
+ if generation_config.forced_decoder_ids is not None and len(generation_config.forced_decoder_ids) > 0:
+ # generation starts after the last token that is forced
+ begin_index += generation_config.forced_decoder_ids[-1][0]
+ processors.append(
+ FlaxSuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index)
+ )
+ if generation_config.forced_decoder_ids is not None:
+ forced_decoder_ids = [
+ [input_ids_seq_length + i[0] - 1, i[1]] for i in generation_config.forced_decoder_ids
+ ]
+ processors.append(FlaxForceTokensLogitsProcessor(forced_decoder_ids))
+ if generation_config.no_repeat_ngram_size is not None and generation_config.no_repeat_ngram_size > 0:
+ processors.append(FlaxNoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size))
+ processors = self._merge_criteria_processor_list(processors, logits_processor)
+
+ return processors
+
+ def _merge_criteria_processor_list(
+ self,
+ default_list: FlaxLogitsProcessorList,
+ custom_list: FlaxLogitsProcessorList,
+ ) -> FlaxLogitsProcessorList:
+ if len(custom_list) == 0:
+ return default_list
+ for default in default_list:
+ for custom in custom_list:
+ if type(custom) is type(default):
+ object_type = "logits processor"
+ raise ValueError(
+ f"A custom {object_type} of type {type(custom)} with values {custom} has been passed to"
+ f" `generate`, but it has already been created with the values {default}. {default} has been"
+ " created by passing the corresponding arguments to generate or by the model's config default"
+ f" values. If you just want to change the default values of {object_type} consider passing"
+ f" them as arguments to `generate` instead of using a custom {object_type}."
+ )
+ default_list.extend(custom_list)
+ return default_list
+
+ def _greedy_search(
+ self,
+ input_ids: None,
+ max_length: Optional[int] = None,
+ pad_token_id: Optional[int] = None,
+ eos_token_id: Optional[int] = None,
+ logits_processor: Optional[FlaxLogitsProcessorList] = None,
+ trace: bool = True,
+ params: Optional[Dict[str, jnp.ndarray]] = None,
+ model_kwargs: Optional[Dict[str, jnp.ndarray]] = None,
+ ):
+ # init values
+ max_length = max_length if max_length is not None else self.generation_config.max_length
+ pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
+ eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
+
+ batch_size, cur_len = input_ids.shape
+
+ eos_token_id = jnp.array(eos_token_id, dtype=jnp.int32 if eos_token_id is not None else None)
+ pad_token_id = jnp.array(pad_token_id, dtype=jnp.int32)
+ cur_len = jnp.array(cur_len)
+
+ # per batch-item holding current token in loop.
+ sequences = jnp.full((batch_size, max_length), pad_token_id, dtype=jnp.int32)
+ sequences = lax.dynamic_update_slice(sequences, input_ids, (0, 0))
+
+ # per batch-item state bit indicating if sentence has finished.
+ is_sent_finished = jnp.zeros((batch_size,), dtype=jnp.bool_)
+
+ # For Seq2Seq generation, we only need to use the decoder instead of the whole model in generation loop
+ # and pass it the `encoder_outputs`, which are part of the `model_kwargs`.
+ model = self.decode if self.config.is_encoder_decoder else self
+ # initialize model specific kwargs
+ model_kwargs = self.prepare_inputs_for_generation(input_ids, max_length, **model_kwargs)
+
+ # initialize state
+ state = GreedyState(
+ cur_len=cur_len,
+ sequences=sequences,
+ running_token=input_ids,
+ is_sent_finished=is_sent_finished,
+ model_kwargs=model_kwargs,
+ )
+
+ def greedy_search_cond_fn(state):
+ """state termination condition fn."""
+ has_reached_max_length = state.cur_len == max_length
+ all_sequence_finished = jnp.all(state.is_sent_finished)
+ finish_generation = jnp.logical_or(has_reached_max_length, all_sequence_finished)
+ return ~finish_generation
+
+ def greedy_search_body_fn(state):
+ """state update fn."""
+ model_outputs = model(state.running_token, params=params, **state.model_kwargs)
+ logits = model_outputs.logits[:, -1]
+
+ # apply min_length, ...
+ logits = logits_processor(state.sequences, logits, state.cur_len)
+
+ next_token = jnp.argmax(logits, axis=-1)
+
+ next_token = next_token * ~state.is_sent_finished + pad_token_id * state.is_sent_finished
+ next_is_sent_finished = state.is_sent_finished | (next_token == eos_token_id)
+ next_token = next_token[:, None]
+
+ next_sequences = lax.dynamic_update_slice(state.sequences, next_token, (0, state.cur_len))
+ next_model_kwargs = self.update_inputs_for_generation(model_outputs, state.model_kwargs)
+ return GreedyState(
+ cur_len=state.cur_len + 1,
+ sequences=next_sequences,
+ running_token=next_token,
+ is_sent_finished=next_is_sent_finished,
+ model_kwargs=next_model_kwargs,
+ )
+
+ # The very first prompt often has sequence length > 1, so run outside of `lax.while_loop` to comply with TPU
+ if input_ids.shape[1] > 1:
+ state = greedy_search_body_fn(state)
+
+ if not trace:
+ state = self._run_loop_in_debug(greedy_search_cond_fn, greedy_search_body_fn, state)
+ else:
+ state = lax.while_loop(greedy_search_cond_fn, greedy_search_body_fn, state)
+
+ return FlaxGreedySearchOutput(sequences=state.sequences)
+
+ def _sample(
+ self,
+ input_ids: None,
+ max_length: Optional[int] = None,
+ pad_token_id: Optional[int] = None,
+ eos_token_id: Optional[int] = None,
+ prng_key: Optional[jnp.ndarray] = None,
+ logits_processor: Optional[FlaxLogitsProcessorList] = None,
+ logits_warper: Optional[FlaxLogitsProcessorList] = None,
+ trace: bool = True,
+ params: Optional[Dict[str, jnp.ndarray]] = None,
+ model_kwargs: Optional[Dict[str, jnp.ndarray]] = None,
+ ):
+ # init values
+ max_length = max_length if max_length is not None else self.generation_config.max_length
+ pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
+ eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
+ prng_key = prng_key if prng_key is not None else jax.random.PRNGKey(0)
+
+ batch_size, cur_len = input_ids.shape
+
+ eos_token_id = jnp.array(eos_token_id, dtype=jnp.int32 if eos_token_id is not None else None)
+ pad_token_id = jnp.array(pad_token_id, dtype=jnp.int32)
+ cur_len = jnp.array(cur_len)
+
+ # per batch-item holding current token in loop.
+ sequences = jnp.full((batch_size, max_length), pad_token_id, dtype=jnp.int32)
+ sequences = lax.dynamic_update_slice(sequences, input_ids, (0, 0))
+
+ # per batch-item state bit indicating if sentence has finished.
+ is_sent_finished = jnp.zeros((batch_size,), dtype=jnp.bool_)
+
+ # For Seq2Seq generation, we only need to use the decoder instead of the whole model in generation loop
+ # and pass it the `encoder_outputs`, which are part of the `model_kwargs`.
+ model = self.decode if self.config.is_encoder_decoder else self
+
+ # initialize model specific kwargs
+ model_kwargs = self.prepare_inputs_for_generation(input_ids, max_length, **model_kwargs)
+
+ # initialize state
+ state = SampleState(
+ cur_len=cur_len,
+ sequences=sequences,
+ running_token=input_ids,
+ is_sent_finished=is_sent_finished,
+ prng_key=prng_key,
+ model_kwargs=model_kwargs,
+ )
+
+ def sample_search_cond_fn(state):
+ """state termination condition fn."""
+ has_reached_max_length = state.cur_len == max_length
+ all_sequence_finished = jnp.all(state.is_sent_finished)
+ finish_generation = jnp.logical_or(has_reached_max_length, all_sequence_finished)
+ return ~finish_generation
+
+ def sample_search_body_fn(state):
+ """state update fn."""
+ prng_key, prng_key_next = jax.random.split(state.prng_key)
+ model_outputs = model(state.running_token, params=params, **state.model_kwargs)
+
+ logits = model_outputs.logits[:, -1]
+
+ # apply min_length, ...
+ logits = logits_processor(state.sequences, logits, state.cur_len)
+ # apply top_p, top_k, temperature
+ logits = logits_warper(logits, logits, state.cur_len)
+
+ next_token = jax.random.categorical(prng_key, logits, axis=-1)
+
+ next_token = next_token * ~state.is_sent_finished + pad_token_id * state.is_sent_finished
+ next_is_sent_finished = state.is_sent_finished | (next_token == eos_token_id)
+ next_token = next_token[:, None]
+
+ next_sequences = lax.dynamic_update_slice(state.sequences, next_token, (0, state.cur_len))
+ next_model_kwargs = self.update_inputs_for_generation(model_outputs, state.model_kwargs)
+
+ return SampleState(
+ cur_len=state.cur_len + 1,
+ sequences=next_sequences,
+ running_token=next_token,
+ is_sent_finished=next_is_sent_finished,
+ model_kwargs=next_model_kwargs,
+ prng_key=prng_key_next,
+ )
+
+ # The very first prompt often has sequence length > 1, so run outside of `lax.while_loop` to comply with TPU
+ if input_ids.shape[1] > 1:
+ state = sample_search_body_fn(state)
+
+ if not trace:
+ state = self._run_loop_in_debug(sample_search_cond_fn, sample_search_body_fn, state)
+ else:
+ state = lax.while_loop(sample_search_cond_fn, sample_search_body_fn, state)
+
+ return FlaxSampleOutput(sequences=state.sequences)
+
+ def _beam_search(
+ self,
+ input_ids: None,
+ max_length: Optional[int] = None,
+ pad_token_id: Optional[int] = None,
+ eos_token_id: Optional[int] = None,
+ length_penalty: Optional[float] = None,
+ early_stopping: Optional[Union[bool, str]] = None,
+ logits_processor: Optional[FlaxLogitsProcessorList] = None,
+ trace: bool = True,
+ params: Optional[Dict[str, jnp.ndarray]] = None,
+ num_return_sequences: Optional[int] = None,
+ model_kwargs: Optional[Dict[str, jnp.ndarray]] = None,
+ ):
+ """
+ This beam search function is heavily inspired by Flax's official example:
+ https://github.com/google/flax/blob/main/examples/wmt/decode.py
+ """
+
+ def flatten_beam_dim(tensor):
+ """Flattens the first two dimensions of a non-scalar array."""
+ # ignore scalars (e.g. cache index)
+ if tensor.ndim == 0:
+ return tensor
+ return tensor.reshape((tensor.shape[0] * tensor.shape[1],) + tensor.shape[2:])
+
+ def unflatten_beam_dim(tensor, batch_size, num_beams):
+ """Unflattens the first, flat batch*beam dimension of a non-scalar array."""
+ # ignore scalars (e.g. cache index)
+ if tensor.ndim == 0:
+ return tensor
+ return tensor.reshape((batch_size, num_beams) + tensor.shape[1:])
+
+ def gather_beams(nested, beam_indices, batch_size, new_num_beams):
+ """
+ Gathers the beam slices indexed by beam_indices into new beam array.
+ """
+ batch_indices = jnp.reshape(
+ jnp.arange(batch_size * new_num_beams) // new_num_beams, (batch_size, new_num_beams)
+ )
+
+ def gather_fn(tensor):
+ # ignore scalars (e.g. cache index)
+ if tensor.ndim == 0:
+ return tensor
+ else:
+ return tensor[batch_indices, beam_indices]
+
+ return jax.tree_util.tree_map(gather_fn, nested)
+
+ # init values
+ max_length = max_length if max_length is not None else self.generation_config.max_length
+ pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
+ eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
+ length_penalty = length_penalty if length_penalty is not None else self.generation_config.length_penalty
+ early_stopping = early_stopping if early_stopping is not None else self.generation_config.early_stopping
+ num_return_sequences = (
+ num_return_sequences if num_return_sequences is not None else self.generation_config.num_return_sequences
+ )
+
+ batch_size, num_beams, cur_len = input_ids.shape
+
+ eos_token_id = jnp.array(eos_token_id, dtype=jnp.int32 if eos_token_id is not None else None)
+ pad_token_id = jnp.array(pad_token_id, dtype=jnp.int32)
+ cur_len = jnp.array(cur_len)
+
+ # record the prompt length of decoder
+ decoder_prompt_len = input_ids.shape[-1]
+
+ # per batch,beam-item holding current token in loop.
+ sequences = jnp.full((batch_size, num_beams, max_length), pad_token_id, dtype=jnp.int32)
+ running_sequences = jnp.full((batch_size, num_beams, max_length), pad_token_id, dtype=jnp.int32)
+ running_sequences = lax.dynamic_update_slice(sequences, input_ids, (0, 0, 0))
+
+ # per batch,beam-item state bit indicating if sentence has finished.
+ is_sent_finished = jnp.zeros((batch_size, num_beams), dtype=jnp.bool_)
+
+ # per batch,beam-item score, logprobs
+ running_scores = jnp.tile(jnp.array([0.0] + [np.array(-1.0e7)] * (num_beams - 1)), [batch_size, 1])
+ scores = jnp.ones((batch_size, num_beams)) * np.array(-1.0e7)
+
+ # For Seq2Seq generation, we only need to use the decoder instead of the whole model in generation loop
+ # and pass it the `encoder_outputs`, which are part of the `model_kwargs`.
+ model = self.decode if self.config.is_encoder_decoder else self
+
+ # flatten beam dim
+ if "encoder_outputs" in model_kwargs:
+ model_kwargs["encoder_outputs"]["last_hidden_state"] = flatten_beam_dim(
+ model_kwargs["encoder_outputs"]["last_hidden_state"]
+ )
+ for kwarg in ["attention_mask", "decoder_attention_mask"]:
+ if kwarg in model_kwargs:
+ model_kwargs[kwarg] = flatten_beam_dim(model_kwargs[kwarg])
+
+ # initialize model specific kwargs
+ model_kwargs = self.prepare_inputs_for_generation(flatten_beam_dim(input_ids), max_length, **model_kwargs)
+
+ # initialize state
+ state = BeamSearchState(
+ cur_len=cur_len,
+ running_sequences=running_sequences,
+ running_scores=running_scores,
+ sequences=sequences,
+ scores=scores,
+ is_sent_finished=is_sent_finished,
+ model_kwargs=model_kwargs,
+ )
+
+ def beam_search_cond_fn(state):
+ """beam search state termination condition fn."""
+
+ # 1. is less than max length?
+ not_max_length_yet = state.cur_len < max_length
+
+ # 2. can the new beams still improve?
+ # early_stopping == False -> apply heuristic = always get the best score from `cur_len`. See the discussion
+ # below for more details.
+ # https://github.com/huggingface/transformers/pull/20901#issuecomment-1369845565
+ # early_stopping == "never" -> compute the best score from max_length or cur_len, depending on the sign of
+ # length_penalty. Positive length_penalty favors longer sequences, thus we use max_length there.
+ if early_stopping == "never" and length_penalty > 0.0:
+ best_running_score = state.running_scores[:, :1] / (
+ (max_length - decoder_prompt_len) ** length_penalty
+ )
+ else:
+ best_running_score = state.running_scores[:, :1] / (
+ (state.cur_len - decoder_prompt_len) ** length_penalty
+ )
+ worst_finished_score = jnp.where(
+ state.is_sent_finished, jnp.min(state.scores, axis=1, keepdims=True), np.array(-1.0e7)
+ )
+ improvement_still_possible = jnp.any(best_running_score > worst_finished_score)
+
+ # 3. is there still a beam that has not finished?
+ still_open_beam = ~(jnp.all(state.is_sent_finished) & (early_stopping is True))
+
+ return not_max_length_yet & still_open_beam & improvement_still_possible
+
+ def beam_search_body_fn(state, input_ids_length=1):
+ """beam search state update fn."""
+ # 1. Forward current tokens
+ # Collect the current position slice along length to feed the fast
+ # autoregressive decoder model. Flatten the beam dimension into batch
+ # dimension for feeding into the model.
+ # unflatten beam dimension
+ # Unflatten beam dimension in attention cache arrays
+ input_token = flatten_beam_dim(
+ lax.dynamic_slice(
+ state.running_sequences,
+ (0, 0, state.cur_len - input_ids_length),
+ (batch_size, num_beams, input_ids_length),
+ )
+ )
+ model_outputs = model(input_token, params=params, **state.model_kwargs)
+
+ logits = unflatten_beam_dim(model_outputs.logits[:, -1], batch_size, num_beams)
+ cache = jax.tree_util.tree_map(
+ lambda tensor: unflatten_beam_dim(tensor, batch_size, num_beams), model_outputs.past_key_values
+ )
+
+ # adapt logits for FlaxMarianMTModel
+ logits = self._adapt_logits_for_beam_search(logits)
+
+ # 2. Compute log probs
+ # get log probabilities from logits,
+ # process logits with processors (*e.g.* min_length, ...), and
+ # add new logprobs to existing running logprobs scores.
+ log_probs = jax.nn.log_softmax(logits)
+ log_probs = logits_processor(
+ flatten_beam_dim(state.running_sequences), flatten_beam_dim(log_probs), state.cur_len
+ )
+ log_probs = unflatten_beam_dim(log_probs, batch_size, num_beams)
+ log_probs = log_probs + jnp.expand_dims(state.running_scores, axis=2)
+ vocab_size = log_probs.shape[2]
+ log_probs = log_probs.reshape((batch_size, num_beams * vocab_size))
+
+ # 3. Retrieve top-K
+ # Each item in batch has num_beams * vocab_size candidate sequences.
+ # For each item, get the top 2*k candidates with the highest log-
+ # probabilities. We gather the top 2*K beams here so that even if the best
+ # K sequences reach EOS simultaneously, we have another K sequences
+ # remaining to continue the live beam search.
+ # Gather the top 2*K scores from _all_ beams.
+ # Gather 2*k top beams.
+ # Recover the beam index by floor division.
+ # Recover token id by modulo division and expand Id array for broadcasting.
+ # Update sequences for the 2*K top-k new sequences.
+ beams_to_keep = 2 * num_beams
+ topk_log_probs, topk_indices = lax.top_k(log_probs, k=beams_to_keep)
+ topk_beam_indices = topk_indices // vocab_size
+ topk_running_sequences = gather_beams(
+ state.running_sequences, topk_beam_indices, batch_size, beams_to_keep
+ )
+ topk_ids = jnp.expand_dims(topk_indices % vocab_size, axis=2)
+ topk_sequences = lax.dynamic_update_slice(topk_running_sequences, topk_ids, (0, 0, state.cur_len))
+
+ # 4. Check which sequences have ended
+ # Update current sequences:
+ # Did any of these sequences reach an end marker?
+ # To prevent these just finished sequences from being added to the current sequences
+ # set of active beam search sequences, set their log probs to a very large
+ # negative value.
+ did_topk_just_finished = topk_sequences[:, :, state.cur_len] == eos_token_id
+ running_topk_log_probs = topk_log_probs + did_topk_just_finished * np.array(-1.0e7)
+ # 5. Get running sequences scores for next
+ # Determine the top k beam indices (from top 2*k beams) from log probs
+ # and gather top k beams (from top 2*k beams).
+ next_topk_indices = lax.top_k(running_topk_log_probs, k=num_beams)[1]
+ next_running_sequences, next_running_scores = gather_beams(
+ [topk_sequences, running_topk_log_probs], next_topk_indices, batch_size, num_beams
+ )
+
+ # 6. Process topk logits
+ # Further process log probs:
+ # - add length penalty
+ # - make sure no scores can be added anymore if beam is full
+ # - make sure still running sequences cannot be chosen as finalized beam
+ topk_log_probs = topk_log_probs / ((state.cur_len + 1 - decoder_prompt_len) ** length_penalty)
+ beams_in_batch_are_full = jnp.broadcast_to(
+ state.is_sent_finished.all(axis=-1, keepdims=True), did_topk_just_finished.shape
+ ) & (early_stopping is True)
+ add_penalty = ~did_topk_just_finished | beams_in_batch_are_full
+ topk_log_probs += add_penalty * np.array(-1.0e7)
+
+ # 7. Get scores, sequences, is sentence finished for next.
+ # Combine sequences, scores, and flags along the beam dimension and compare
+ # new finished sequence scores to existing finished scores and select the
+ # best from the new set of beams
+ merged_sequences = jnp.concatenate([state.sequences, topk_sequences], axis=1)
+ merged_scores = jnp.concatenate([state.scores, topk_log_probs], axis=1)
+ merged_is_sent_finished = jnp.concatenate([state.is_sent_finished, did_topk_just_finished], axis=1)
+ topk_merged_indices = lax.top_k(merged_scores, k=num_beams)[1]
+ next_sequences, next_scores, next_is_sent_finished = gather_beams(
+ [merged_sequences, merged_scores, merged_is_sent_finished], topk_merged_indices, batch_size, num_beams
+ )
+
+ # 8. Update model kwargs.
+ # Determine the top k beam indices from the original set of all beams.
+ # With these, gather the top k beam-associated caches.
+ next_running_indices = gather_beams(topk_beam_indices, next_topk_indices, batch_size, num_beams)
+ next_cache = gather_beams(cache, next_running_indices, batch_size, num_beams)
+ model_outputs["past_key_values"] = jax.tree_util.tree_map(lambda x: flatten_beam_dim(x), next_cache)
+ next_model_kwargs = self.update_inputs_for_generation(model_outputs, state.model_kwargs)
+
+ return BeamSearchState(
+ cur_len=state.cur_len + 1,
+ running_scores=next_running_scores,
+ running_sequences=next_running_sequences,
+ scores=next_scores,
+ sequences=next_sequences,
+ is_sent_finished=next_is_sent_finished,
+ model_kwargs=next_model_kwargs,
+ )
+
+ # Always run first iteration outside of `lax.while_loop` to avoid calling `beam_search_cond_fn`
+ # when `state.cur_len` equals `decoder_prompt_len`. This also helps to comply with TPU when
+ # the very first prompt has sequence length > 1.
+ state = partial(beam_search_body_fn, input_ids_length=input_ids.shape[-1])(state)
+
+ if not trace:
+ state = self._run_loop_in_debug(beam_search_cond_fn, beam_search_body_fn, state)
+ else:
+ state = lax.while_loop(beam_search_cond_fn, beam_search_body_fn, state)
+
+ # Account for the edge-case where there are no finished sequences for a
+ # particular batch item. If so, return running sequences for that batch item.
+ none_finished = jnp.any(state.is_sent_finished, axis=1)
+ sequences = jnp.where(none_finished[:, None, None], state.sequences, state.running_sequences)
+ scores = jnp.where(none_finished[:, None], state.scores, state.running_scores)
+
+ # Take best beams for each batch (the score is sorted in descending order)
+ sequences = flatten_beam_dim(sequences[:, :num_return_sequences, :])
+ scores = flatten_beam_dim(scores[:, :num_return_sequences])
+
+ return FlaxBeamSearchOutput(sequences=sequences, scores=scores)
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/logits_process.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/logits_process.py
new file mode 100644
index 0000000000000000000000000000000000000000..16e69538b621e00371d3ce0c4c6f022c2447ff2f
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/logits_process.py
@@ -0,0 +1,2944 @@
+# coding=utf-8
+# Copyright 2024 The HuggingFace Inc. team and Google DeepMind.
+#
+# 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 inspect
+import math
+from typing import Callable, Iterable, List, Optional, Tuple, Union
+
+import numpy as np
+import torch
+
+from ..pytorch_utils import isin_mps_friendly
+from ..utils import add_start_docstrings
+from ..utils.logging import get_logger
+
+
+logger = get_logger(__name__)
+
+
+LOGITS_PROCESSOR_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
+ scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
+ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam
+ search or log softmax for each vocabulary token when using beam search
+
+ Return:
+ `torch.FloatTensor` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.
+
+"""
+
+
+class LogitsProcessor:
+ """Abstract base class for all logit processors that can be applied during generation."""
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ raise NotImplementedError(
+ f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
+ )
+
+
+class LogitsProcessorList(list):
+ """
+ This class can be used to create a list of [`LogitsProcessor`] to subsequently process a `scores` input tensor.
+ This class inherits from list and adds a specific *__call__* method to apply each [`LogitsProcessor`] to the
+ inputs.
+ """
+
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.FloatTensor:
+ r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
+ scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
+ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using
+ beam search or log softmax for each vocabulary token when using beam search
+ kwargs (`Dict[str, Any]`, *optional*):
+ Additional kwargs that are specific to a logits processor.
+
+ Return:
+ `torch.FloatTensor` of shape `(batch_size, config.vocab_size)`:
+ The processed prediction scores.
+
+ """
+ for processor in self:
+ function_args = inspect.signature(processor.__call__).parameters
+ if len(function_args) > 2:
+ if not all(arg in kwargs for arg in list(function_args.keys())[2:]):
+ raise ValueError(
+ f"Make sure that all the required parameters: {list(function_args.keys())} for "
+ f"{processor.__class__} are passed to the logits processor."
+ )
+ scores = processor(input_ids, scores, **kwargs)
+ else:
+ scores = processor(input_ids, scores)
+
+ return scores
+
+
+class MinLengthLogitsProcessor(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] enforcing a min-length by setting EOS probability to 0. Note that, for decoder-only models
+ like most LLMs, the length includes the prompt.
+
+ Args:
+ min_length (`int`):
+ The minimum length below which the score of `eos_token_id` is set to `-float("Inf")`.
+ eos_token_id (`Union[int, List[int], torch.Tensor]`):
+ The id(s) of the *end-of-sequence* token.
+ device (`str`, *optional*, defaults to `"cpu"`):
+ The device to allocate the tensors.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoModelForCausalLM, AutoTokenizer
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m")
+ >>> model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m")
+
+ >>> inputs = tokenizer("A number:", return_tensors="pt")
+ >>> gen_out = model.generate(**inputs)
+ >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])
+ A number: one
+
+ >>> # setting `min_length` to a value smaller than the uncontrolled output length has no impact
+ >>> gen_out = model.generate(**inputs, min_length=3)
+ >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])
+ A number: one
+
+ >>> # setting a larger `min_length` will force the model to generate beyond its natural ending point, which is not
+ >>> # necessarily incorrect
+ >>> gen_out = model.generate(**inputs, min_length=10)
+ >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])
+ A number: one thousand, nine hundred and ninety-four
+ ```
+ """
+
+ def __init__(self, min_length: int, eos_token_id: Union[int, List[int], torch.Tensor], device: str = "cpu"):
+ if not isinstance(min_length, int) or min_length < 0:
+ raise ValueError(f"`min_length` has to be a non-negative integer, but is {min_length}")
+
+ if not isinstance(eos_token_id, torch.Tensor):
+ if isinstance(eos_token_id, int):
+ eos_token_id = [eos_token_id]
+ eos_token_id = torch.tensor(eos_token_id, device=device)
+
+ self.min_length = min_length
+ self.eos_token_id = eos_token_id
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ vocab_tensor = torch.arange(scores.shape[-1], device=scores.device)
+ eos_token_mask = isin_mps_friendly(vocab_tensor, self.eos_token_id)
+ scores_processed = scores.clone()
+ if input_ids.shape[-1] < self.min_length:
+ scores_processed = torch.where(eos_token_mask, -math.inf, scores)
+ return scores_processed
+
+
+class MinNewTokensLengthLogitsProcessor(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] enforcing a min-length of new tokens by setting EOS (End-Of-Sequence) token probability to 0.
+ Contrarily to [`MinLengthLogitsProcessor`], this processor ignores the prompt.
+
+ Args:
+ prompt_length_to_skip (`int`):
+ The input tokens length. Not a valid argument when used with `generate` as it will automatically assign the
+ input length.
+ min_new_tokens (`int`):
+ The minimum *new* tokens length below which the score of `eos_token_id` is set to `-float("Inf")`.
+ eos_token_id (`Union[int, List[int], torch.Tensor]`):
+ The id(s) of the *end-of-sequence* token.
+ device (`str`, *optional*, defaults to `"cpu"`):
+ The device to allocate the tensors.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoModelForCausalLM, AutoTokenizer
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m")
+ >>> model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m")
+
+ >>> inputs = tokenizer(["A number:"], return_tensors="pt")
+ >>> gen_out = model.generate(**inputs)
+ >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])
+ A number: one
+
+ >>> # setting `min_new_tokens` will force the model to generate beyond its natural ending point, which is not
+ >>> # necessarily incorrect
+ >>> gen_out = model.generate(**inputs, min_new_tokens=2)
+ >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])
+ A number: one thousand
+ ```
+ """
+
+ def __init__(
+ self,
+ prompt_length_to_skip: int,
+ min_new_tokens: int,
+ eos_token_id: Union[int, List[int], torch.Tensor],
+ device: str = "cpu",
+ ):
+ for arg_name, arg_value in [
+ ("prompt_length_to_skip", prompt_length_to_skip),
+ ("min_new_tokens", min_new_tokens),
+ ]:
+ if not isinstance(arg_value, int) or arg_value < 0:
+ raise ValueError(f"`{arg_name}` has to be a positive integer, but is {arg_value}")
+
+ if not isinstance(eos_token_id, torch.Tensor):
+ if isinstance(eos_token_id, int):
+ eos_token_id = [eos_token_id]
+ eos_token_id = torch.tensor(eos_token_id, device=device)
+
+ self.prompt_length_to_skip = prompt_length_to_skip
+ self.min_new_tokens = min_new_tokens
+ self.eos_token_id = eos_token_id
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ new_tokens_length = input_ids.shape[-1] - self.prompt_length_to_skip
+ scores_processed = scores.clone()
+ vocab_tensor = torch.arange(scores.shape[-1], device=scores.device)
+ eos_token_mask = isin_mps_friendly(vocab_tensor, self.eos_token_id)
+ if new_tokens_length < self.min_new_tokens:
+ scores_processed = torch.where(eos_token_mask, -math.inf, scores)
+
+ return scores_processed
+
+
+class TemperatureLogitsWarper(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] for temperature (exponential scaling output probability distribution), which effectively means
+ that it can control the randomness of the predicted tokens. Often used together with [`TopPLogitsWarper`] and
+ [`TopKLogitsWarper`].
+
+
+
+ Make sure that `do_sample=True` is included in the `generate` arguments otherwise the temperature value won't have
+ any effect.
+
+
+
+ Args:
+ temperature (`float`):
+ Strictly positive float value used to modulate the logits distribution. A value smaller than `1` decreases
+ randomness (and vice versa), with `0` being equivalent to shifting all probability mass to the most likely
+ token.
+
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
+
+ >>> set_seed(0) # for reproducibility
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
+ >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
+ >>> model.config.pad_token_id = model.config.eos_token_id
+ >>> inputs = tokenizer(["Hugging Face Company is"], return_tensors="pt")
+
+ >>> # With temperature=1.0, the default, we consistently get random outputs due to random sampling.
+ >>> generate_kwargs = {"max_new_tokens": 10, "do_sample": True, "temperature": 1.0, "num_return_sequences": 2}
+ >>> outputs = model.generate(**inputs, **generate_kwargs)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True))
+ ['Hugging Face Company is one of these companies that is going to take a',
+ "Hugging Face Company is a brand created by Brian A. O'Neil"]
+
+ >>> # However, with temperature close to 0, it approximates greedy decoding strategies (invariant)
+ >>> generate_kwargs["temperature"] = 0.0001
+ >>> outputs = model.generate(**inputs, **generate_kwargs)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True))
+ ['Hugging Face Company is a company that has been around for over 20 years',
+ 'Hugging Face Company is a company that has been around for over 20 years']
+ ```
+ """
+
+ def __init__(self, temperature: float):
+ if not isinstance(temperature, float) or not (temperature > 0):
+ except_msg = (
+ f"`temperature` (={temperature}) has to be a strictly positive float, otherwise your next token "
+ "scores will be invalid."
+ )
+ if isinstance(temperature, float) and temperature == 0.0:
+ except_msg += " If you're looking for greedy decoding strategies, set `do_sample=False`."
+ raise ValueError(except_msg)
+
+ self.temperature = temperature
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ scores_processed = scores / self.temperature
+ return scores_processed
+
+
+class RepetitionPenaltyLogitsProcessor(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] that prevents the repetition of previous tokens through a penalty. This penalty is applied at
+ most once per token. Note that, for decoder-only models like most LLMs, the considered tokens include the prompt.
+
+ In the original [paper](https://arxiv.org/pdf/1909.05858.pdf), the authors suggest the use of a penalty of around
+ 1.2 to achieve a good balance between truthful generation and lack of repetition. To penalize and reduce
+ repetition, use `penalty` values above 1.0, where a higher value penalizes more strongly. To reward and encourage
+ repetition, use `penalty` values between 0.0 and 1.0, where a lower value rewards more strongly.
+
+ Args:
+ penalty (`float`):
+ The parameter for repetition penalty. 1.0 means no penalty. Above 1.0 penalizes previously generated
+ tokens. Between 0.0 and 1.0 rewards previously generated tokens.
+
+ Examples:
+
+ ```py
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
+
+ >>> # Initializing the model and tokenizer for it
+ >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
+ >>> inputs = tokenizer(["I'm not going to"], return_tensors="pt")
+
+ >>> # This shows a normal generate without any specific parameters
+ >>> summary_ids = model.generate(**inputs)
+ >>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True)[0])
+ I'm not going to be able to do that. I'm going to be able to do that
+
+ >>> # This generates a penalty for repeated tokens
+ >>> penalized_ids = model.generate(**inputs, repetition_penalty=1.1)
+ >>> print(tokenizer.batch_decode(penalized_ids, skip_special_tokens=True)[0])
+ I'm not going to be able to do that. I'll just have to go out and play
+ ```
+ """
+
+ def __init__(self, penalty: float):
+ if not isinstance(penalty, float) or not (penalty > 0):
+ raise ValueError(f"`penalty` has to be a strictly positive float, but is {penalty}")
+
+ self.penalty = penalty
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ score = torch.gather(scores, 1, input_ids)
+
+ # if score < 0 then repetition penalty has to be multiplied to reduce the token probabilities
+ score = torch.where(score < 0, score * self.penalty, score / self.penalty)
+
+ scores_processed = scores.scatter(1, input_ids, score)
+ return scores_processed
+
+
+class EncoderRepetitionPenaltyLogitsProcessor(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] that works similarly to [`RepetitionPenaltyLogitsProcessor`], but with an *inverse* penalty
+ that is applied to the tokens present in the prompt. In other words, a penalty above 1.0 increases the odds of
+ selecting tokens that were present in the prompt.
+
+ It was designed to avoid hallucination in input-grounded tasks, like summarization. Although originally intended
+ for encoder-decoder models, it can also be used with decoder-only models like LLMs.
+
+ Args:
+ penalty (`float`):
+ The parameter for repetition penalty. 1.0 means no penalty. Above 1.0 rewards prompt tokens. Between 0.0
+ and 1.0 penalizes prompt tokens.
+ encoder_input_ids (`torch.LongTensor`):
+ The encoder_input_ids that should be repeated within the decoder ids.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoModelForCausalLM, AutoTokenizer
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m")
+ >>> model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m")
+
+ >>> inputs = tokenizer(["Alice and Bob. The third member's name was"], return_tensors="pt")
+ >>> gen_out = model.generate(**inputs)
+ >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])
+ Alice and Bob. The third member's name was not mentioned.
+
+ >>> # With the `encoder_repetition_penalty` argument we can trigger this logits processor in `generate`, which can
+ >>> # promote the use of prompt tokens ("Bob" in this example)
+ >>> gen_out = model.generate(**inputs, encoder_repetition_penalty=1.2)
+ >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])
+ Alice and Bob. The third member's name was Bob. The third member's name was Bob.
+ ```
+ """
+
+ def __init__(self, penalty: float, encoder_input_ids: torch.LongTensor):
+ if not isinstance(penalty, float) or not (penalty > 0):
+ raise ValueError(f"`penalty` has to be a strictly positive float, but is {penalty}")
+
+ self.penalty = 1 / penalty
+ self.encoder_input_ids = encoder_input_ids
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ score = torch.gather(scores, 1, self.encoder_input_ids)
+
+ # if score < 0 then hallucination penalty has to be multiplied to increase the token probabilities
+ score = torch.where(score < 0, score * self.penalty, score / self.penalty)
+
+ scores_processed = scores.scatter(1, self.encoder_input_ids, score)
+ return scores_processed
+
+
+class TopPLogitsWarper(LogitsProcessor):
+ """
+ [`LogitsProcessor`] that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off.
+ Often used together with [`TemperatureLogitsWarper`] and [`TopKLogitsWarper`].
+
+ Args:
+ top_p (`float`):
+ If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or
+ higher are kept for generation.
+ filter_value (`float`, *optional*, defaults to -inf):
+ All filtered values will be set to this float value.
+ min_tokens_to_keep (`int`, *optional*, defaults to 1):
+ Minimum number of tokens that cannot be filtered.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
+
+ >>> set_seed(1)
+ >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
+
+ >>> inputs = tokenizer("A sequence: 1, 2", return_tensors="pt")
+
+ >>> # With sampling, the output is unexpected -- sometimes too unexpected.
+ >>> outputs = model.generate(**inputs, do_sample=True)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ A sequence: 1, 2, 3 | < 4 (left-hand pointer) ;
+
+
+
+ >>> # With `top_p` sampling, the output gets restricted to high-probability tokens.
+ >>> # Pro tip: In practice, LLMs use `top_p` in the 0.9-0.95 range.
+ >>> outputs = model.generate(**inputs, do_sample=True, top_p=0.1)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9
+ ```
+ """
+
+ def __init__(self, top_p: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
+ top_p = float(top_p)
+ if top_p < 0 or top_p > 1.0:
+ raise ValueError(f"`top_p` has to be a float > 0 and < 1, but is {top_p}")
+ if not isinstance(min_tokens_to_keep, int) or (min_tokens_to_keep < 1):
+ raise ValueError(f"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}")
+
+ self.top_p = top_p
+ self.filter_value = filter_value
+ self.min_tokens_to_keep = min_tokens_to_keep
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ sorted_logits, sorted_indices = torch.sort(scores, descending=False)
+ cumulative_probs = sorted_logits.softmax(dim=-1).cumsum(dim=-1)
+
+ # Remove tokens with cumulative top_p above the threshold (token with 0 are kept)
+ sorted_indices_to_remove = cumulative_probs <= (1 - self.top_p)
+ # Keep at least min_tokens_to_keep
+ sorted_indices_to_remove[..., -self.min_tokens_to_keep :] = 0
+
+ # scatter sorted tensors to original indexing
+ indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
+ scores_processed = scores.masked_fill(indices_to_remove, self.filter_value)
+ return scores_processed
+
+
+class TopKLogitsWarper(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] that performs top-k, i.e. restricting to the k highest probability elements. Often used
+ together with [`TemperatureLogitsWarper`] and [`TopPLogitsWarper`].
+
+ Args:
+ top_k (`int`):
+ The number of highest probability vocabulary tokens to keep for top-k-filtering.
+ filter_value (`float`, *optional*, defaults to -inf):
+ All filtered values will be set to this float value.
+ min_tokens_to_keep (`int`, *optional*, defaults to 1):
+ Minimum number of tokens that cannot be filtered.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
+
+ >>> set_seed(1)
+ >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
+
+ >>> inputs = tokenizer("A sequence: A, B, C, D", return_tensors="pt")
+
+ >>> # With sampling, the output is unexpected -- sometimes too unexpected.
+ >>> outputs = model.generate(**inputs, do_sample=True)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ A sequence: A, B, C, D, E — S — O, P — R
+
+ >>> # With `top_k` sampling, the output gets restricted the k most likely tokens.
+ >>> # Pro tip: In practice, LLMs use `top_k` in the 5-50 range.
+ >>> outputs = model.generate(**inputs, do_sample=True, top_k=2)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ A sequence: A, B, C, D, E, F, G, H, I
+ ```
+ """
+
+ def __init__(self, top_k: int, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
+ if not isinstance(top_k, int) or top_k <= 0:
+ raise ValueError(f"`top_k` has to be a strictly positive integer, but is {top_k}")
+
+ self.top_k = max(top_k, min_tokens_to_keep)
+ self.filter_value = filter_value
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ top_k = min(self.top_k, scores.size(-1)) # Safety check
+ # Remove all tokens with a probability less than the last token of the top-k
+ indices_to_remove = scores < torch.topk(scores, top_k)[0][..., -1, None]
+ scores_processed = scores.masked_fill(indices_to_remove, self.filter_value)
+ return scores_processed
+
+
+class MinPLogitsWarper(LogitsProcessor):
+ """
+ [`LogitsProcessor`] that performs min-p, i.e. keeps all tokens that are above a minimum probability, scaled by the
+ probability of the most likely token. As a result, the filter becomes more agressive in the presence of
+ high-probability tokens, which is a sign of a confident output that we shouldn't deviate from.
+
+ Often used together with [`TemperatureLogitsWarper`]. Used as an alternative to [`TopPLogitsWarper`] and
+ [`TopKLogitsWarper`].
+
+ Created by @menhguin and @kalomaze (github handles). Code adapted from [this external PR](https://github.com/oobabooga/text-generation-webui/pull/4449/files)
+
+ Args:
+ min_p (`float`):
+ Minimum token probability, which will be scaled by the probability of the most likely token. It must be a
+ value between 0 and 1. Typical values are in the 0.01-0.2 range, comparably selective as setting `top_p` in
+ the 0.99-0.8 range (use the opposite of normal `top_p` values).
+ filter_value (`float`, *optional*, defaults to -inf):
+ All filtered values will be set to this float value.
+ min_tokens_to_keep (`int`, *optional*, defaults to 1):
+ Minimum number of tokens that cannot be filtered.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
+
+ >>> set_seed(1)
+ >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
+
+ >>> inputs = tokenizer("A sequence: 1, 2", return_tensors="pt")
+
+ >>> # With sampling, the output is unexpected -- sometimes too unexpected.
+ >>> outputs = model.generate(**inputs, do_sample=True)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ A sequence: 1, 2, 3 | < 4 (left-hand pointer) ;
+
+
+
+ >>> # With `min_p` sampling, the output gets restricted to high-probability tokens.
+ >>> # Pro tip: In practice, LLMs use `min_p` in the 0.01-0.2 range.
+ >>> outputs = model.generate(**inputs, do_sample=True, min_p=0.1)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9
+ ```
+ """
+
+ def __init__(self, min_p: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
+ if not (0 <= min_p <= 1.0):
+ raise ValueError(f"`min_p` has to be a float in the [0, 1] interval, but is {min_p}")
+ if not isinstance(min_tokens_to_keep, int) or (min_tokens_to_keep < 1):
+ raise ValueError(f"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}")
+
+ self.min_p = min_p
+ self.filter_value = filter_value
+ self.min_tokens_to_keep = min_tokens_to_keep
+
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ # Convert logits to probabilities
+ probs = torch.softmax(scores, dim=-1)
+ # Get the probability of the top token for each sequence in the batch
+ top_probs, _ = probs.max(dim=-1, keepdim=True)
+ # Calculate the actual min_p threshold by scaling min_p with the top token's probability
+ scaled_min_p = self.min_p * top_probs
+ # Create a mask for tokens that have a probability less than the scaled min_p
+ tokens_to_remove = probs < scaled_min_p
+
+ sorted_indices = torch.argsort(scores, descending=True, dim=-1)
+ sorted_indices_to_remove = torch.gather(tokens_to_remove, dim=-1, index=sorted_indices)
+ # Keep at least min_tokens_to_keep
+ sorted_indices_to_remove[..., : self.min_tokens_to_keep] = False
+
+ indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
+ scores_processed = scores.masked_fill(indices_to_remove, self.filter_value)
+ return scores_processed
+
+
+class TypicalLogitsWarper(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] that performs typical decoding. Inspired on how humans use language, it prioritizes tokens
+ whose log probability is close to the entropy of the token probability distribution. This means that the most
+ likely tokens may be discarded in the process.
+
+ See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information.
+
+ Args:
+ mass (`float`, *optional*, defaults to 0.9):
+ Value of typical_p between 0 and 1 inclusive, defaults to 0.9.
+ filter_value (`float`, *optional*, defaults to -inf):
+ All filtered values will be set to this float value.
+ min_tokens_to_keep (`int`, *optional*, defaults to 1):
+ Minimum number of tokens that cannot be filtered.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
+
+ >>> model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m")
+ >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m")
+
+ >>> inputs = tokenizer("1, 2, 3", return_tensors="pt")
+
+ >>> # We can see that greedy decoding produces a sequence of numbers
+ >>> outputs = model.generate(**inputs)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
+
+ >>> # For this particular seed, we can see that sampling produces nearly the same low-information (= low entropy)
+ >>> # sequence
+ >>> set_seed(18)
+ >>> outputs = model.generate(**inputs, do_sample=True)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10
+
+ >>> # With `typical_p` set, the most obvious sequence is no longer produced, which may be good for your problem
+ >>> set_seed(18)
+ >>> outputs = model.generate(
+ ... **inputs, do_sample=True, typical_p=0.1, return_dict_in_generate=True, output_scores=True
+ ... )
+ >>> print(tokenizer.batch_decode(outputs.sequences, skip_special_tokens=True)[0])
+ 1, 2, 3 and 5
+
+ >>> # We can see that the token corresponding to "4" (token 934) in the second position, the most likely token
+ >>> # as seen with greedy decoding, was entirely blocked out
+ >>> print(outputs.scores[1][0, 934])
+ tensor(-inf)
+ ```
+ """
+
+ def __init__(self, mass: float = 0.9, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
+ mass = float(mass)
+ if not (mass > 0 and mass < 1):
+ raise ValueError(f"`typical_p` has to be a float > 0 and < 1, but is {mass}")
+ if not isinstance(min_tokens_to_keep, int) or (min_tokens_to_keep < 1):
+ raise ValueError(f"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}")
+
+ self.filter_value = filter_value
+ self.mass = mass
+ self.min_tokens_to_keep = min_tokens_to_keep
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ # calculate entropy
+ normalized = torch.nn.functional.log_softmax(scores, dim=-1)
+ p = torch.exp(normalized)
+ ent = -(normalized * p).nansum(-1, keepdim=True)
+
+ # shift and sort
+ shifted_scores = torch.abs((-normalized) - ent)
+ sorted_scores, sorted_indices = torch.sort(shifted_scores, descending=False)
+ sorted_logits = scores.gather(-1, sorted_indices)
+ cumulative_probs = sorted_logits.softmax(dim=-1).cumsum(dim=-1)
+
+ # Remove tokens with cumulative mass above the threshold
+ last_ind = (cumulative_probs < self.mass).sum(dim=1)
+ last_ind.clamp_(max=sorted_scores.shape[-1] - 1)
+ sorted_indices_to_remove = sorted_scores > sorted_scores.gather(1, last_ind.view(-1, 1))
+ sorted_indices_to_remove[..., : self.min_tokens_to_keep] = 0
+ indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
+
+ scores_processed = scores.masked_fill(indices_to_remove, self.filter_value)
+ return scores_processed
+
+
+class EpsilonLogitsWarper(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] that performs epsilon-sampling, i.e. restricting to tokens with `prob >= epsilon`. Takes the
+ largest min_tokens_to_keep tokens if no tokens satisfy this constraint. See [Truncation Sampling as Language Model
+ Desmoothing](https://arxiv.org/abs/2210.15191) for more information.
+
+ Args:
+ epsilon (`float`):
+ If set to > 0, only the most tokens with probabilities `epsilon` or higher are kept for generation.
+ filter_value (`float`, *optional*, defaults to -inf):
+ All filtered values will be set to this float value.
+ min_tokens_to_keep (`int`, *optional*, defaults to 1):
+ Minimum number of tokens that cannot be filtered.
+
+ Examples:
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
+
+ >>> set_seed(1)
+ >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
+
+ >>> inputs = tokenizer("A sequence: 1, 2", return_tensors="pt")
+
+ >>> # With sampling, the output is unexpected -- sometimes too unexpected.
+ >>> outputs = model.generate(**inputs, do_sample=True)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ A sequence: 1, 2, 3 | < 4 (left-hand pointer) ;
+
+
+
+ >>> # With epsilon sampling, the output gets restricted to high-probability tokens. Note that this is similar to
+ >>> # Top P sampling, which restricts tokens based on their cumulative probability.
+ >>> # Pro tip: The paper recomends using `epsilon_cutoff` values between 3e-4 and 9e-4
+ >>> outputs = model.generate(**inputs, do_sample=True, epsilon_cutoff=0.1)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9
+ ```
+ """
+
+ def __init__(self, epsilon: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
+ epsilon = float(epsilon)
+ if epsilon <= 0 or epsilon >= 1:
+ raise ValueError(f"`epsilon_cutoff` has to be a float > 0 and < 1, but is {epsilon}")
+
+ min_tokens_to_keep = int(min_tokens_to_keep)
+ if min_tokens_to_keep < 1:
+ raise ValueError(
+ f"`min_tokens_to_keep` has to be a strictly positive integer, but is {min_tokens_to_keep}"
+ )
+
+ self.epsilon = epsilon
+ self.filter_value = filter_value
+ self.min_tokens_to_keep = min_tokens_to_keep
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ # Determine which indices to remove
+ probabilities = scores.softmax(dim=-1)
+ indices_to_remove = probabilities < self.epsilon
+
+ # Keep the words with the 'min_tokens_to_keep'-highest probabilities
+ top_k = min(self.min_tokens_to_keep, scores.size(-1)) # Safety check
+ indices_to_remove = indices_to_remove & (scores < torch.topk(scores, top_k)[0][..., -1, None])
+
+ scores_processed = scores.masked_fill(indices_to_remove, self.filter_value)
+ return scores_processed
+
+
+class EtaLogitsWarper(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] that performs eta-sampling, a technique to filter out tokens with probabilities below a dynamic
+ cutoff value, `eta`, which is calculated based on a combination of the hyperparameter `epsilon` and the entropy of
+ the token probabilities, i.e. `eta := min(epsilon, sqrt(epsilon * e^-entropy(probabilities)))`. Takes the largest
+ min_tokens_to_keep tokens if no tokens satisfy this constraint. It addresses the issue of poor quality in long
+ samples of text generated by neural language models leading to more coherent and fluent text. See [Truncation
+ Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more information. Note: `do_sample`
+ must be set to `True` for this `LogitsProcessor` to work.
+
+
+ Args:
+ epsilon (`float`):
+ A float value in the range (0, 1). Hyperparameter used to calculate the dynamic cutoff value, `eta`. The
+ suggested values from the paper ranges from 3e-4 to 4e-3 depending on the size of the model.
+ filter_value (`float`, *optional*, defaults to -inf):
+ All values that are found to be below the dynamic cutoff value, `eta`, are set to this float value. This
+ parameter is useful when logits need to be modified for very low probability tokens that should be excluded
+ from generation entirely.
+ min_tokens_to_keep (`int`, *optional*, defaults to 1):
+ Specifies the minimum number of tokens that must be kept for generation, regardless of their probabilities.
+ For example, if `min_tokens_to_keep` is set to 1, at least one token will always be kept for generation,
+ even if all tokens have probabilities below the cutoff `eta`.
+ device (`str`, *optional*, defaults to `"cpu"`):
+ The device to allocate the tensors.
+
+ Examples:
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
+
+ >>> set_seed(1)
+ >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
+
+ >>> inputs = tokenizer("A sequence: 1, 2", return_tensors="pt")
+
+ >>> # With sampling, the output is unexpected -- sometimes too unexpected.
+ >>> outputs = model.generate(**inputs, do_sample=True)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ A sequence: 1, 2, 3 | < 4 (left-hand pointer) ;
+
+
+
+ >>> # With eta sampling, the output gets restricted to high-probability tokens. You can see it as a dynamic form of
+ >>> # epsilon sampling that adapts its cutoff probability based on the entropy (high entropy = lower cutoff).
+ >>> # Pro tip: The paper recomends using `eta_cutoff` values between 3e-4 to 4e-3
+ >>> outputs = model.generate(**inputs, do_sample=True, eta_cutoff=0.1)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9
+ ```
+ """
+
+ def __init__(
+ self, epsilon: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1, device: str = "cpu"
+ ):
+ epsilon = float(epsilon)
+ if epsilon <= 0 or epsilon >= 1:
+ raise ValueError(f"`eta_cutoff` has to be a float > 0 and < 1, but is {epsilon}")
+
+ min_tokens_to_keep = int(min_tokens_to_keep)
+ if min_tokens_to_keep < 1:
+ raise ValueError(
+ f"`min_tokens_to_keep` has to be a strictly positive integer, but is {min_tokens_to_keep}"
+ )
+
+ self.epsilon = torch.tensor(epsilon, device=device)
+ self.filter_value = filter_value
+ self.min_tokens_to_keep = min_tokens_to_keep
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ probabilities = scores.softmax(dim=-1)
+ entropy = torch.distributions.Categorical(logits=scores).entropy()
+ eta = torch.min(self.epsilon, torch.sqrt(self.epsilon) * torch.exp(-entropy))[..., None]
+ indices_to_remove = probabilities < eta
+
+ # Keep the words with the 'min_tokens_to_keep'-highest probabilities
+ top_k = min(self.min_tokens_to_keep, scores.size(-1)) # Safety check
+ indices_to_remove = indices_to_remove & (scores < torch.topk(scores, top_k)[0][..., -1, None])
+
+ scores_processed = scores.masked_fill(indices_to_remove, self.filter_value)
+ return scores_processed
+
+
+def _get_ngrams(ngram_size: int, prev_input_ids: torch.Tensor, num_hypos: int):
+ """
+ Assume ngram_size=2 and prev_input_ids=tensor([[40, 2883, 2712, 4346]]). The output of generated ngrams look like
+ this {(40,): [2883], (2883,): [2712], (2712,): [4346]}.
+
+ Args:
+ ngram_size (`int`):
+ The number sequential tokens taken as a group which may only occur once before being banned.
+ prev_input_ids (`torch.Tensor`):
+ Generated token ids for the current hypothesis.
+ num_hypos (`int`):
+ The number of hypotheses for which n-grams need to be generated.
+
+ Returns:
+ generated_ngrams (`dict`):
+ Dictionary of generated ngrams.
+ """
+ # Initialize an empty list of dictionaries, one for each hypothesis (index) in the range of num_hypos
+ generated_ngrams = [{} for _ in range(num_hypos)]
+ for idx in range(num_hypos):
+ gen_tokens = prev_input_ids[idx].tolist()
+ generated_ngram = generated_ngrams[idx]
+ # Loop through each n-gram of size ngram_size in the list of tokens (gen_tokens)
+ for ngram in zip(*[gen_tokens[i:] for i in range(ngram_size)]):
+ prev_ngram_tuple = tuple(ngram[:-1])
+ generated_ngram[prev_ngram_tuple] = generated_ngram.get(prev_ngram_tuple, []) + [ngram[-1]]
+ return generated_ngrams
+
+
+def _get_generated_ngrams(banned_ngrams, prev_input_ids, ngram_size, cur_len):
+ """
+ Determines the banned tokens for the current hypothesis based on previously generated n-grams.
+
+ Args:
+ banned_ngrams (`dict`):
+ A dictionary containing previously generated n-grams for each hypothesis.
+ prev_input_ids (`torch.Tensor`):
+ Generated token ids for the current hypothesis.
+ ngram_size (`int`):
+ The number sequential tokens taken as a group which may only occur once before being banned.
+ cur_len (`int`):
+ The current length of the token sequences for which the n-grams are being checked.
+
+ Returns:
+ List of tokens that are banned.
+ """
+ # Before decoding the next token, prevent decoding of ngrams that have already appeared
+ start_idx = cur_len + 1 - ngram_size
+ ngram_idx = tuple(prev_input_ids[start_idx:cur_len].tolist())
+ return banned_ngrams.get(ngram_idx, [])
+
+
+def _calc_banned_ngram_tokens(
+ ngram_size: int, prev_input_ids: torch.Tensor, num_hypos: int, cur_len: int
+) -> List[Iterable[int]]:
+ """Copied from fairseq for no_repeat_ngram in beam_search"""
+ if cur_len + 1 < ngram_size:
+ # return no banned tokens if we haven't generated no_repeat_ngram_size tokens yet
+ return [[] for _ in range(num_hypos)]
+ generated_ngrams = _get_ngrams(ngram_size, prev_input_ids, num_hypos)
+ banned_tokens = [
+ _get_generated_ngrams(generated_ngrams[hypo_idx], prev_input_ids[hypo_idx], ngram_size, cur_len)
+ for hypo_idx in range(num_hypos)
+ ]
+ return banned_tokens
+
+
+class NoRepeatNGramLogitsProcessor(LogitsProcessor):
+ r"""
+ N-grams are groups of "n" consecutive words, characters, or tokens taken from a sequence of text. Given the
+ sentence: "She runs fast", the bi-grams (n=2) would be ("she", "runs") and ("runs", "fast"). In text generation,
+ avoiding repetitions of word sequences provides a more diverse output. This [`LogitsProcessor`] enforces no
+ repetition of n-grams by setting the scores of banned tokens to negative infinity which eliminates those tokens
+ from consideration when further processing the scores. Note that, for decoder-only models like most LLMs, the
+ prompt is also considered to obtain the n-grams.
+ [Fairseq](https://github.com/pytorch/fairseq/blob/a07cb6f40480928c9e0548b737aadd36ee66ac76/fairseq/sequence_generator.py#L345).
+
+
+
+ Use n-gram penalties with care. For instance, penalizing 2-grams (bigrams) in an article about the city of New York
+ might lead to undesirable outcomes where the city's name appears only once in the entire text.
+ [Reference](https://huggingface.co/blog/how-to-generate)
+
+
+
+ Args:
+ ngram_size (`int`):
+ All ngrams of size `ngram_size` can only occur once.
+
+ Examples:
+
+ ```py
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
+
+ >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
+ >>> inputs = tokenizer(["Today I"], return_tensors="pt")
+
+ >>> output = model.generate(**inputs)
+ >>> print(tokenizer.decode(output[0], skip_special_tokens=True))
+ Today I’m not sure if I’m going to be able to do it.
+
+ >>> # Now let's add ngram size using `no_repeat_ngram_size`. This stops the repetitions ("I’m") in the output.
+ >>> output = model.generate(**inputs, no_repeat_ngram_size=2)
+ >>> print(tokenizer.decode(output[0], skip_special_tokens=True))
+ Today I’m not sure if I can get a better understanding of the nature of this issue
+ ```
+ """
+
+ def __init__(self, ngram_size: int):
+ if not isinstance(ngram_size, int) or ngram_size <= 0:
+ raise ValueError(f"`ngram_size` has to be a strictly positive integer, but is {ngram_size}")
+ self.ngram_size = ngram_size
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ num_batch_hypotheses = scores.shape[0]
+ cur_len = input_ids.shape[-1]
+ scores_processed = scores.clone()
+ banned_batch_tokens = _calc_banned_ngram_tokens(self.ngram_size, input_ids, num_batch_hypotheses, cur_len)
+ for i, banned_tokens in enumerate(banned_batch_tokens):
+ scores_processed[i, banned_tokens] = -float("inf")
+
+ return scores_processed
+
+
+class EncoderNoRepeatNGramLogitsProcessor(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] that works similarly to [`NoRepeatNGramLogitsProcessor`], but applied exclusively to prevent
+ the repetition of n-grams present in the prompt.
+
+ It was designed to promote chattiness in a language model, by preventing the generation of n-grams present in
+ previous conversation rounds.
+
+ Args:
+ encoder_ngram_size (`int`):
+ All ngrams of size `ngram_size` can only occur within the encoder input ids.
+ encoder_input_ids (`int`):
+ The encoder_input_ids that should not be repeated within the decoder ids.
+
+ Examples:
+
+ ```py
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
+
+ >>> model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m")
+ >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m")
+
+ >>> inputs = tokenizer("Alice: I love cats. What do you love?\nBob:", return_tensors="pt")
+
+ >>> # With greedy decoding, we see Bob repeating Alice's opinion. If Bob was a chatbot, it would be a poor one.
+ >>> outputs = model.generate(**inputs)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ Alice: I love cats. What do you love?
+ Bob: I love cats. What do you
+
+ >>> # With this logits processor, we can prevent Bob from repeating Alice's opinion.
+ >>> outputs = model.generate(**inputs, encoder_no_repeat_ngram_size=2)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ Alice: I love cats. What do you love?
+ Bob: My cats are very cute.
+ ```
+ """
+
+ def __init__(self, encoder_ngram_size: int, encoder_input_ids: torch.LongTensor):
+ if not isinstance(encoder_ngram_size, int) or encoder_ngram_size <= 0:
+ raise ValueError(
+ f"`encoder_ngram_size` has to be a strictly positive integer, but is {encoder_ngram_size}"
+ )
+ self.ngram_size = encoder_ngram_size
+ if len(encoder_input_ids.shape) == 1:
+ encoder_input_ids = encoder_input_ids.unsqueeze(0)
+ self.batch_size = encoder_input_ids.shape[0]
+ self.generated_ngrams = _get_ngrams(encoder_ngram_size, encoder_input_ids, self.batch_size)
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ # B x num_beams
+ num_hypos = scores.shape[0]
+ num_beams = num_hypos // self.batch_size
+ cur_len = input_ids.shape[-1]
+ scores_processed = scores.clone()
+ banned_batch_tokens = [
+ _get_generated_ngrams(
+ self.generated_ngrams[hypo_idx // num_beams], input_ids[hypo_idx], self.ngram_size, cur_len
+ )
+ for hypo_idx in range(num_hypos)
+ ]
+
+ for i, banned_tokens in enumerate(banned_batch_tokens):
+ scores_processed[i, banned_tokens] = -float("inf")
+
+ return scores_processed
+
+
+class SequenceBiasLogitsProcessor(LogitsProcessor):
+ """
+ [`LogitsProcessor`] that applies an additive bias on sequences. The bias is applied to the last token of a sequence
+ when the next generated token can complete it. Consequently, to take the most of biasing sequences with more than
+ one token, consider using beam methods (to gracefully work around partially completed sequences that have a
+ negative bias) and applying the bias to their prefixes (to ensure the bias is applied earlier).
+
+
+
+ At a token-level, biasing a word is different from biasing a word with a space before it. If you want to bias
+ "foo" mid-sentence, you'll likely want to add a prefix space and bias " foo" instead. Check the tokenizer section
+ of our NLP course to find out why: https://huggingface.co/learn/nlp-course/chapter2/4?fw=pt
+
+
+
+ Args:
+ sequence_bias (`List[List[Union[List[int], float]]]`):
+ List of lists that maps a sequence of tokens to its bias term (e.g. `[[[10, 45], -2.0],
+ [[64], -7.5]]`). Positive biases increase the odds of the
+ sequence being selected, while negative biases do the opposite. If a sequence has a length of 1, its bias
+ will always be applied. Otherwise, the bias will only be applied if the sequence in question is about to be
+ completed (in the token selection step after this processor is applied).
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
+
+ >>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
+ >>> inputs = tokenizer(["The full name of Donald is Donald"], return_tensors="pt")
+
+ >>> summary_ids = model.generate(inputs["input_ids"], max_new_tokens=4, do_sample=False)
+ >>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True)[0])
+ The full name of Donald is Donald John Trump Sr.
+
+ >>> def get_tokens(word):
+ ... return tokenizer([word], add_special_tokens=False).input_ids[0]
+
+ >>> # IMPORTANT: Remember our tip about adding spaces before words to bias them correctly.
+ >>> sequence_bias = [[get_tokens("Trump"), -10.0],] # will fail to apply bias
+ >>> biased_ids = model.generate(
+ ... inputs["input_ids"], max_new_tokens=4, do_sample=False, sequence_bias=sequence_bias
+ ... )
+ >>> print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0])
+ The full name of Donald is Donald John Trump Sr.
+
+ >>> sequence_bias = [[get_tokens(" Trump"), -10.0],] # will work
+ >>> biased_ids = model.generate(
+ ... inputs["input_ids"], max_new_tokens=4, do_sample=False, sequence_bias=sequence_bias
+ ... )
+ >>> print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0])
+ The full name of Donald is Donald John Harper. He
+
+ >>> # We can also add a positive bias to nudge the model towards specific tokens or continuations. This technique
+ >>> # is also more effective when paired up with beam search.
+ >>> sequence_bias = [[get_tokens(" Donald Duck"), 10.0],]
+ >>> biased_ids = model.generate(
+ ... inputs["input_ids"], max_new_tokens=4, num_beams=4, do_sample=False, sequence_bias=sequence_bias
+ ... )
+ >>> print(tokenizer.batch_decode(biased_ids, skip_special_tokens=True)[0])
+ The full name of Donald is Donald Duck. He is
+ ```
+ """
+
+ def __init__(self, sequence_bias: List[List[Union[List[int], float]]]):
+ self.sequence_bias = sequence_bias
+ self._validate_arguments()
+ self._convert_list_arguments_into_dict()
+
+ # Bias variables that will be populated on the first call (for retrocompatibility purposes, the vocabulary size
+ # is infered in the first usage, which inhibits initializing here)
+ self.length_1_bias = None
+ self.prepared_bias_variables = False
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ # 1 - Prepares the bias tensors. This is only needed the first time the logit processor is called.
+ if not self.prepared_bias_variables:
+ self._prepare_bias_variables(scores)
+
+ # 2 - prepares an empty bias to add
+ bias = torch.zeros_like(scores)
+
+ # 3 - include the bias from length = 1
+ bias += self.length_1_bias
+
+ # 4 - include the bias from length > 1, after determining which biased sequences may be completed.
+ for sequence_ids, sequence_bias in self.sequence_bias.items():
+ if len(sequence_ids) == 1: # the sequence is of length 1, already applied
+ continue
+ if len(sequence_ids) > input_ids.shape[1]: # the sequence is longer than the context, ignore
+ continue
+ prefix_length = len(sequence_ids) - 1
+ last_token = sequence_ids[-1]
+ matching_rows = torch.eq(
+ input_ids[:, -prefix_length:],
+ torch.tensor(sequence_ids[:-1], dtype=input_ids.dtype, device=input_ids.device),
+ ).prod(dim=1)
+ bias[:, last_token] += torch.where(
+ matching_rows.bool(),
+ torch.tensor(sequence_bias, device=input_ids.device),
+ torch.tensor(0.0, device=input_ids.device),
+ )
+
+ # 5 - apply the bias to the scores
+ scores_processed = scores + bias
+ return scores_processed
+
+ def _prepare_bias_variables(self, scores: torch.FloatTensor):
+ vocabulary_size = scores.shape[-1]
+
+ # Check biased tokens out of bounds
+ invalid_biases = []
+ for sequence_ids in self.sequence_bias:
+ for token_id in sequence_ids:
+ if token_id >= vocabulary_size:
+ invalid_biases.append(token_id)
+ if len(invalid_biases) > 0:
+ raise ValueError(
+ f"The model vocabulary size is {vocabulary_size}, but the following tokens were being biased: "
+ f"{invalid_biases}"
+ )
+
+ # Precompute the bias tensors to be applied. Sequences of length 1 are kept separately, as they can be applied
+ # with simpler logic.
+ self.length_1_bias = torch.zeros((vocabulary_size,), dtype=torch.float).to(scores.device)
+ for sequence_ids, bias in self.sequence_bias.items():
+ if len(sequence_ids) == 1:
+ self.length_1_bias[sequence_ids[-1]] = bias
+
+ self.prepared_bias_variables = True
+
+ def _validate_arguments(self):
+ sequence_bias = self.sequence_bias
+ if not isinstance(sequence_bias, dict) and not isinstance(sequence_bias, list) or len(sequence_bias) == 0:
+ raise ValueError(
+ f"`sequence_bias` has to be a non-empty dictionary, or non-empty list of lists but is {sequence_bias}."
+ )
+ if isinstance(sequence_bias, dict) and any(
+ not isinstance(sequence_ids, tuple) for sequence_ids in sequence_bias.keys()
+ ):
+ raise ValueError(f"`sequence_bias` has to be a dict with tuples as keys, but is {sequence_bias}.")
+ if isinstance(sequence_bias, dict) and any(
+ any((not isinstance(token_id, (int, np.integer)) or token_id < 0) for token_id in sequence_ids)
+ or len(sequence_ids) == 0
+ for sequence_ids in sequence_bias.keys()
+ ):
+ raise ValueError(
+ f"Each key in `sequence_bias` has to be a non-empty tuple of positive integers, but is "
+ f"{sequence_bias}."
+ )
+
+ def all_token_bias_pairs_are_valid(sequence):
+ return (
+ isinstance(sequence[0], list)
+ and all(isinstance(token_id, (int, np.integer)) and token_id > 0 for token_id in sequence[0])
+ and isinstance(sequence[1], float)
+ )
+
+ if isinstance(sequence_bias, list) and any(
+ (not all_token_bias_pairs_are_valid(sequence)) or len(sequence) == 0 for sequence in sequence_bias
+ ):
+ raise ValueError(
+ f"Each element in `sequence_bias` has to be a non-empty list of lists of positive integers and float, but is "
+ f"{sequence_bias}."
+ )
+ if isinstance(sequence_bias, dict) and any(not isinstance(bias, float) for bias in sequence_bias.values()):
+ raise ValueError(f"`sequence_bias` has to be a dict with floats as values, but is {sequence_bias}.")
+
+ def _convert_list_arguments_into_dict(self):
+ """BC: we used to accept `dict{tuple of tokens: float}` directly, now we expect a list"""
+ if isinstance(self.sequence_bias, list):
+ temp_sequence = self.sequence_bias
+ self.sequence_bias = {tuple(sublist[0]): sublist[1] for sublist in temp_sequence}
+
+
+class NoBadWordsLogitsProcessor(SequenceBiasLogitsProcessor):
+ """
+ [`LogitsProcessor`] that enforces that specified sequences will never be selected.
+
+
+
+ In order to get the token ids of the words that should not appear in the generated text, make sure to set
+ `add_prefix_space=True` when initializing the tokenizer, and use `tokenizer(bad_words,
+ add_special_tokens=False).input_ids`. The `add_prefix_space` argument is only supported for some slow tokenizers,
+ as fast tokenizers' prefixing behaviours come from `pre tokenizers`. Read more
+ [here](https://huggingface.co/docs/tokenizers/api/pre-tokenizers).
+
+
+
+ Args:
+ bad_words_ids (`List[List[int]]`):
+ List of list of token ids that are not allowed to be generated.
+ eos_token_id (`Union[int, List[int], torch.Tensor]`, *optional*):
+ The id(s) of the *end-of-sequence* token.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
+
+ >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
+ >>> inputs = tokenizer(["In a word, the cake is a"], return_tensors="pt")
+
+ >>> output_ids = model.generate(inputs["input_ids"], max_new_tokens=5, pad_token_id=tokenizer.eos_token_id)
+ >>> print(tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0])
+ In a word, the cake is a bit of a mess.
+
+ >>> # Now let's take the bad words out. Please note that the tokenizer is initialized differently
+ >>> tokenizer_with_prefix_space = AutoTokenizer.from_pretrained("openai-community/gpt2", add_prefix_space=True)
+
+
+ >>> def get_tokens_as_list(word_list):
+ ... "Converts a sequence of words into a list of tokens"
+ ... tokens_list = []
+ ... for word in word_list:
+ ... tokenized_word = tokenizer_with_prefix_space([word], add_special_tokens=False).input_ids[0]
+ ... tokens_list.append(tokenized_word)
+ ... return tokens_list
+
+
+ >>> bad_words_ids = get_tokens_as_list(word_list=["mess"])
+ >>> output_ids = model.generate(
+ ... inputs["input_ids"], max_new_tokens=5, bad_words_ids=bad_words_ids, pad_token_id=tokenizer.eos_token_id
+ ... )
+ >>> print(tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0])
+ In a word, the cake is a bit of a surprise.
+ ```
+ """
+
+ def __init__(
+ self, bad_words_ids: List[List[int]], eos_token_id: Optional[Union[int, List[int], torch.Tensor]] = None
+ ):
+ self.bad_word_ids = bad_words_ids
+ self._validate_arguments()
+
+ # Filter EOS token from bad_words_ids
+ if eos_token_id is not None:
+ if not isinstance(eos_token_id, torch.Tensor):
+ if isinstance(eos_token_id, int):
+ eos_token_id = [eos_token_id]
+ eos_token_id = torch.tensor(eos_token_id)
+
+ bad_words_ids = list(
+ filter(lambda bad_token_seq: all(bad_token_seq != [i] for i in eos_token_id), bad_words_ids)
+ )
+
+ # Forbidding a sequence is equivalent to setting its bias to -inf
+ sequence_bias = {tuple(sequence): float("-inf") for sequence in bad_words_ids}
+ super().__init__(sequence_bias=sequence_bias)
+
+ def _validate_arguments(self):
+ bad_words_ids = self.bad_word_ids
+ if not isinstance(bad_words_ids, list) or len(bad_words_ids) == 0:
+ raise ValueError(f"`bad_words_ids` has to be a non-empty list, but is {bad_words_ids}.")
+ if any(not isinstance(bad_word_ids, list) for bad_word_ids in bad_words_ids):
+ raise ValueError(f"`bad_words_ids` has to be a list of lists, but is {bad_words_ids}.")
+ if any(
+ any((not isinstance(token_id, (int, np.integer)) or token_id < 0) for token_id in bad_word_ids)
+ for bad_word_ids in bad_words_ids
+ ):
+ raise ValueError(
+ f"Each list in `bad_words_ids` has to be a list of positive integers, but is {bad_words_ids}."
+ )
+
+
+class PrefixConstrainedLogitsProcessor(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] that enforces constrained generation and is useful for prefix-conditioned constrained
+ generation. See [Autoregressive Entity Retrieval](https://arxiv.org/abs/2010.00904) for more information.
+
+ Args:
+ prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`):
+ This function constraints the beam search to allowed tokens only at each step. This function takes 2
+ arguments `inputs_ids` and the batch ID `batch_id`. It has to return a list with the allowed tokens for the
+ next generation step conditioned on the previously generated tokens `inputs_ids` and the batch ID
+ `batch_id`.
+
+ Examples:
+
+ ```py
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
+
+ >>> model = AutoModelForCausalLM.from_pretrained("bigscience/bloomz-560m")
+ >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloomz-560m")
+
+ >>> inputs = tokenizer("Alice and Bob", return_tensors="pt")
+
+ >>> # By default, it continues generating according to the model's logits
+ >>> outputs = model.generate(**inputs, max_new_tokens=5)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ Alice and Bob are friends
+
+ >>> # We can contrain it with `prefix_allowed_tokens_fn` to force a certain behavior based on a prefix.
+ >>> # For instance, we can force an entire entity to be generated when its beginning is detected.
+ >>> entity = tokenizer(" Bob Marley", return_tensors="pt").input_ids[0] # 3 tokens
+ >>> def prefix_allowed_tokens_fn(batch_id, input_ids):
+ ... '''
+ ... Attempts to generate 'Bob Marley' when 'Bob' is detected.
+ ... In this case, `batch_id` is not used, but you can set rules for each batch member.
+ ... '''
+ ... if input_ids[-1] == entity[0]:
+ ... return [entity[1].item()]
+ ... elif input_ids[-2] == entity[0] and input_ids[-1] == entity[1]:
+ ... return [entity[2].item()]
+ ... return list(range(tokenizer.vocab_size)) # If no match, allow all tokens
+
+ >>> outputs = model.generate(**inputs, max_new_tokens=5, prefix_allowed_tokens_fn=prefix_allowed_tokens_fn)
+ >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
+ Alice and Bob Marley
+ ```
+ """
+
+ def __init__(self, prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], List[int]], num_beams: int):
+ self._prefix_allowed_tokens_fn = prefix_allowed_tokens_fn
+ self._num_beams = num_beams
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ mask = torch.full_like(scores, -math.inf)
+ batch_size = input_ids.shape[0] // self._num_beams
+
+ for batch_id in range(batch_size):
+ for beam_id in range(self._num_beams):
+ sent = input_ids[batch_id * self._num_beams + beam_id]
+ prefix_allowed_tokens = self._prefix_allowed_tokens_fn(batch_id, sent)
+ if len(prefix_allowed_tokens) == 0:
+ raise ValueError(
+ f"`prefix_allowed_tokens_fn` returned an empty list for batch ID {batch_id}."
+ f"This means that the constraint is unsatisfiable. Please check your implementation"
+ f"of `prefix_allowed_tokens_fn` "
+ )
+ mask[batch_id * self._num_beams + beam_id, prefix_allowed_tokens] = 0
+
+ scores_processed = scores + mask
+ return scores_processed
+
+
+class HammingDiversityLogitsProcessor(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] that enforces diverse beam search.
+
+ Note that this logits processor is only effective for [`PreTrainedModel.group_beam_search`]. See [Diverse Beam
+ Search: Decoding Diverse Solutions from Neural Sequence Models](https://arxiv.org/pdf/1610.02424.pdf) for more
+ details.
+
+ Traditional beam search often generates very similar sequences across different beams.
+ `HammingDiversityLogitsProcessor` addresses this by penalizing beams that generate tokens already chosen by other
+ beams in the same time step.
+
+ Args:
+ diversity_penalty (`float`):
+ This value is subtracted from a beam's score if it generates a token same as any beam from other group at a
+ particular time. A higher `diversity_penalty` will enforce greater diversity among the beams. Adjusting
+ this value can help strike a balance between diversity and natural likelihood.
+ num_beams (`int`):
+ Number of beams for beam search. 1 means no beam search.
+ num_beam_groups (`int`):
+ Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams.
+ [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
+ >>> import torch
+
+ >>> # Initialize the model and tokenizer
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-base")
+ >>> model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-base")
+
+ >>> # A long text about the solar system
+ >>> text = (
+ ... "The Solar System is a gravitationally bound system comprising the Sun and the objects that orbit it, "
+ ... "either directly or indirectly. Of the objects that orbit the Sun directly, the largest are the eight "
+ ... "planets, with the remainder being smaller objects, such as the five dwarf planets and small Solar System "
+ ... "bodies. The Solar System formed 4.6 billion years ago from the gravitational collapse of a giant "
+ ... "interstellar molecular cloud."
+ ... )
+ >>> inputs = tokenizer("summarize: " + text, return_tensors="pt")
+
+ >>> # Generate diverse summary
+ >>> outputs_diverse = model.generate(
+ ... **inputs,
+ ... num_beam_groups=2,
+ ... diversity_penalty=10.0,
+ ... max_length=100,
+ ... num_beams=4,
+ ... num_return_sequences=2,
+ ... )
+ >>> summaries_diverse = tokenizer.batch_decode(outputs_diverse, skip_special_tokens=True)
+
+ >>> # Generate non-diverse summary
+ >>> outputs_non_diverse = model.generate(
+ ... **inputs,
+ ... max_length=100,
+ ... num_beams=4,
+ ... num_return_sequences=2,
+ ... )
+ >>> summary_non_diverse = tokenizer.batch_decode(outputs_non_diverse, skip_special_tokens=True)
+
+ >>> # With `diversity_penalty`, the resulting beams are much more diverse
+ >>> print(summary_non_diverse)
+ ['the solar system formed 4.6 billion years ago from the collapse of a giant interstellar molecular cloud. of the objects that orbit the Sun directly, the largest are the eight planets.',
+ 'the Solar System formed 4.6 billion years ago from the collapse of a giant interstellar molecular cloud. of the objects that orbit the Sun directly, the largest are the eight planets.']
+
+ >>> print(summaries_diverse)
+ ['the solar system formed 4.6 billion years ago from the collapse of a giant interstellar molecular cloud. of the objects that orbit the Sun directly, the largest are the eight planets.',
+ 'the solar system formed 4.6 billion years ago from the collapse of a giant interstellar molecular cloud. of the objects that orbit the Sun directly, the largest are the eight planets. the rest of the objects are smaller objects, such as the five dwarf planets and small solar system bodies.']
+ ```
+ """
+
+ def __init__(self, diversity_penalty: float, num_beams: int, num_beam_groups: int):
+ if not isinstance(diversity_penalty, float) or (not diversity_penalty > 0.0):
+ raise ValueError("`diversity_penalty` should be a float strictly larger than 0.")
+ self._diversity_penalty = diversity_penalty
+ if not isinstance(num_beams, int) or num_beams < 2:
+ raise ValueError("`num_beams` should be an integer strictly larger than 1.")
+ self._num_beams = num_beams
+ if not isinstance(num_beam_groups, int) or num_beam_groups < 2:
+ raise ValueError("`num_beam_groups` should be an integer strictly larger than 1.")
+ if num_beam_groups > num_beams:
+ raise ValueError("`beam_groups` has to be smaller or equal to `num_beams`.")
+ self._num_sub_beams = num_beams // num_beam_groups
+
+ def __call__(
+ self,
+ input_ids: torch.LongTensor,
+ scores: torch.FloatTensor,
+ current_tokens: torch.LongTensor,
+ beam_group_idx: int,
+ ) -> torch.FloatTensor:
+ r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids)
+ scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
+ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using
+ beam search or log softmax for each vocabulary token when using beam search
+ current_tokens (`torch.LongTensor` of shape `(batch_size)`):
+ Indices of input sequence tokens in the vocabulary, corresponding to the tokens selected by the other
+ beam groups in the current generation step.
+ beam_group_idx (`int`):
+ The index of the beam group currently being processed.
+
+ Return:
+ `torch.FloatTensor` of shape `(batch_size, config.vocab_size)`:
+ The processed prediction scores.
+ """
+ # hamming diversity: penalise using same token in current group which was used in previous groups at
+ # the same time step
+ batch_size = current_tokens.shape[0] // self._num_beams
+ group_start_idx = beam_group_idx * self._num_sub_beams
+ group_end_idx = min(group_start_idx + self._num_sub_beams, self._num_beams)
+ group_size = group_end_idx - group_start_idx
+ vocab_size = scores.shape[-1]
+
+ if group_start_idx == 0:
+ return scores
+
+ scores_processed = scores.clone()
+ for batch_idx in range(batch_size):
+ # predicted tokens of last time step of previous groups
+ previous_group_tokens = current_tokens[
+ batch_idx * self._num_beams : batch_idx * self._num_beams + group_start_idx
+ ]
+ token_frequency = torch.bincount(previous_group_tokens, minlength=vocab_size).to(scores.device)
+ scores_processed[batch_idx * group_size : (batch_idx + 1) * group_size] -= (
+ self._diversity_penalty * token_frequency
+ )
+
+ return scores_processed
+
+
+class ForcedBOSTokenLogitsProcessor(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] that enforces the specified token as the first generated token. Used with encoder-decoder
+ models.
+
+ Args:
+ bos_token_id (`int`):
+ The id of the token to force as the first generated token.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
+
+ >>> model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-small")
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-small")
+
+ >>> inputs = tokenizer("Translate from English to German: I love cats.", return_tensors="pt")
+
+ >>> # By default, it continues generating according to the model's logits
+ >>> outputs = model.generate(**inputs, max_new_tokens=10)
+ >>> print(tokenizer.batch_decode(outputs)[0])
+ Ich liebe Kitty.
+
+ >>> # We can use `forced_bos_token_id` to force the start of generation with an encoder-decoder model
+ >>> # (including forcing it to end straight away with an EOS token)
+ >>> outputs = model.generate(**inputs, max_new_tokens=10, forced_bos_token_id=tokenizer.eos_token_id)
+ >>> print(tokenizer.batch_decode(outputs)[0])
+
+ ```
+ """
+
+ def __init__(self, bos_token_id: int):
+ self.bos_token_id = bos_token_id
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ cur_len = input_ids.shape[-1]
+ scores_processed = scores
+ if cur_len == 1:
+ scores_processed = torch.full_like(scores, -math.inf)
+ scores_processed[:, self.bos_token_id] = 0
+ return scores_processed
+
+
+class ForcedEOSTokenLogitsProcessor(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] that enforces the specified token as the last generated token when `max_length` is reached.
+
+ Args:
+ max_length (`int`):
+ The maximum length of the sequence to be generated.
+ eos_token_id (`Union[int, List[int], torch.Tensor]`):
+ The id(s) of the *end-of-sequence* token.
+ device (`str`, *optional*, defaults to `"cpu"`):
+ The device to allocate the tensors.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
+
+ >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
+
+ >>> inputs = tokenizer("A sequence: 1, 2, 3", return_tensors="pt")
+
+ >>> # By default, it continues generating according to the model's logits
+ >>> outputs = model.generate(**inputs, max_new_tokens=10)
+ >>> print(tokenizer.batch_decode(outputs)[0])
+ A sequence: 1, 2, 3, 4, 5, 6, 7, 8
+
+ >>> # `forced_eos_token_id` ensures the generation ends with a EOS token
+ >>> outputs = model.generate(**inputs, max_new_tokens=10, forced_eos_token_id=tokenizer.eos_token_id)
+ >>> print(tokenizer.batch_decode(outputs)[0])
+ A sequence: 1, 2, 3, 4, 5, 6, 7,<|endoftext|>
+ ```
+ """
+
+ def __init__(self, max_length: int, eos_token_id: Union[int, List[int], torch.Tensor], device: str = "cpu"):
+ self.max_length = max_length
+
+ if not isinstance(eos_token_id, torch.Tensor):
+ if isinstance(eos_token_id, int):
+ eos_token_id = [eos_token_id]
+ eos_token_id = torch.tensor(eos_token_id, device=device)
+ self.eos_token_id = eos_token_id
+
+ if torch.is_floating_point(eos_token_id) or (eos_token_id < 0).any():
+ raise ValueError(f"`eos_token_id` has to be a list of positive integers, but is {eos_token_id}")
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ cur_len = input_ids.shape[-1]
+ scores_processed = scores
+ if cur_len == self.max_length - 1:
+ scores_processed = torch.full_like(scores, -math.inf)
+ scores_processed[:, self.eos_token_id] = 0
+ return scores_processed
+
+
+class InfNanRemoveLogitsProcessor(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] that removes all `nan` and `inf` values to avoid the generation method to fail. Note that using
+ the logits processor should only be used if necessary since it can slow down the generation method.
+
+ This logits processor has no `generate` example, as there shouldn't be a correct combination of flags that warrants
+ its use.
+ """
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ # set all nan values to 0.0
+ scores_processed = torch.where(scores != scores, 0.0, scores)
+
+ # set all +/-inf values to max/min possible value
+ scores_processed = torch.where(scores == float("inf"), torch.finfo(scores.dtype).max, scores_processed)
+ scores_processed = torch.where(scores == -float("inf"), torch.finfo(scores.dtype).min, scores_processed)
+
+ return scores_processed
+
+
+class ExponentialDecayLengthPenalty(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] that exponentially increases the score of the `eos_token_id` after `start_index` has been
+ reached. This allows generating shorter sequences without having a hard cutoff, allowing the `eos_token` to be
+ predicted in a meaningful position.
+
+ Args:
+ exponential_decay_length_penalty (`tuple(int, float)`):
+ This tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty
+ starts and `decay_factor` represents the factor of exponential decay
+ eos_token_id (`Union[int, List[int], torch.Tensor]`):
+ The id(s) of the *end-of-sequence* token.
+ input_ids_seq_length (`int`):
+ The length of the input sequence.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
+
+ >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
+
+ >>> text = "Just wanted to let you know, I"
+ >>> inputs = tokenizer(text, return_tensors="pt")
+
+ >>> # Let's consider that we want short sentences, so we limit `max_length=30`. However, we observe that the answer
+ >>> # tends to end abruptly.
+ >>> set_seed(1)
+ >>> outputs = model.generate(**inputs, do_sample=True, temperature=0.9, max_length=30, pad_token_id=50256)
+ >>> print(tokenizer.batch_decode(outputs)[0])
+ Just wanted to let you know, I received a link to an ebook, the book How To Start A Social Network which was
+ published in 2010. Although
+
+ >>> # To promote the appearance of the EOS token at the right time, we add the `exponential_decay_length_penalty =
+ >>> # (start_index, decay_factor)`. Instead of cutting at max_tokens, the output comes to an end before and usually
+ >>> # with more meaning. What happens is that starting from `start_index` the EOS token score will be increased
+ >>> # by `decay_factor` exponentially. However, if you set a high decay factor, you may also end up with abruptly
+ >>> # ending sequences.
+ >>> set_seed(1)
+ >>> outputs = model.generate(
+ ... **inputs,
+ ... do_sample=True,
+ ... temperature=0.9,
+ ... max_length=30,
+ ... pad_token_id=50256,
+ ... exponential_decay_length_penalty=(15, 1.6),
+ ... )
+ >>> print(tokenizer.batch_decode(outputs)[0])
+ Just wanted to let you know, I received a link to an ebook, the book How To Start A Social Network
+ which<|endoftext|>
+
+ >>> # With a small decay factor, you will have a higher chance of getting a meaningful sequence.
+ >>> set_seed(1)
+ >>> outputs = model.generate(
+ ... **inputs,
+ ... do_sample=True,
+ ... temperature=0.9,
+ ... max_length=30,
+ ... pad_token_id=50256,
+ ... exponential_decay_length_penalty=(15, 1.01),
+ ... )
+ >>> print(tokenizer.batch_decode(outputs)[0])
+ Just wanted to let you know, I received a link to an ebook, the book How To Start A Social Network which was
+ published in 2010.<|endoftext|>
+ ```
+ """
+
+ def __init__(
+ self,
+ exponential_decay_length_penalty: Tuple[int, float],
+ eos_token_id: Union[int, List[int], torch.Tensor],
+ input_ids_seq_length: int,
+ ):
+ self.regulation_start = exponential_decay_length_penalty[0] + input_ids_seq_length
+ self.regulation_factor = exponential_decay_length_penalty[1]
+
+ if not isinstance(eos_token_id, torch.Tensor):
+ if isinstance(eos_token_id, int):
+ eos_token_id = [eos_token_id]
+ eos_token_id = torch.tensor(eos_token_id)
+ self.eos_token_id = eos_token_id
+
+ if torch.is_floating_point(eos_token_id) or (eos_token_id < 0).any():
+ raise ValueError(f"`eos_token_id` has to be a list of positive integers, but is {eos_token_id}")
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ cur_len = input_ids.shape[-1]
+ self.eos_token_id = self.eos_token_id.to(scores.device)
+ penalties = torch.zeros_like(scores)
+ scores_processed = scores
+ if cur_len > self.regulation_start:
+ penalty_idx = cur_len - self.regulation_start
+ # To support negative logits we compute the penalty of the absolute value and add to the original logit
+ penalty = torch.abs(scores[:, self.eos_token_id]) * (pow(self.regulation_factor, penalty_idx) - 1)
+ penalties[:, self.eos_token_id] = penalty
+ scores_processed = scores + penalties
+ return scores_processed
+
+
+class LogitNormalization(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] for normalizing the scores using log-softmax. It's important to normalize
+ the scores during beam search, after applying the logits processors or warpers, since the search algorithm used in
+ this library doesn't do it (it only does it before, but they may need re-normalization) but it still supposes that
+ the scores are normalized when comparing the hypotheses.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
+ >>> import torch
+
+ >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
+
+ >>> inputs = tokenizer("A sequence: 1, 2, 3", return_tensors="pt")
+
+ >>> # By default, the scores are not normalized -- the sum of their exponentials is NOT a normalized probability
+ >>> # distribution, summing to 1
+ >>> outputs = model.generate(**inputs, return_dict_in_generate=True, output_scores=True)
+ >>> print(torch.allclose(torch.sum(torch.exp(outputs.scores[-1])), torch.Tensor((1.000,)), rtol=1e-4))
+ False
+
+ >>> # Normalizing them may have a positive impact on beam methods, or when using the scores on your application
+ >>> outputs = model.generate(**inputs, renormalize_logits=True, return_dict_in_generate=True, output_scores=True)
+ >>> print(torch.allclose(torch.sum(torch.exp(outputs.scores[-1])), torch.Tensor((1.000,)), rtol=1e-4))
+ True
+ ```
+ """
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ scores_processed = scores.log_softmax(dim=-1)
+ return scores_processed
+
+
+class SuppressTokensAtBeginLogitsProcessor(LogitsProcessor):
+ r"""
+ [`SuppressTokensAtBeginLogitsProcessor`] supresses a list of tokens as soon as the `generate` function starts
+ generating using `begin_index` tokens. This should ensure that the tokens defined by `begin_suppress_tokens` are
+ not generated at the beginning. Originally created for
+ [Whisper](https://huggingface.co/docs/transformers/model_doc/whisper).
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoProcessor, WhisperForConditionalGeneration
+ >>> from datasets import load_dataset
+
+ >>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
+ >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
+ >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
+
+ >>> # Whisper has `begin_suppress_tokens` set by default (= `[220, 50256]`). 50256 is the EOS token, so this means
+ >>> # it can't generate and EOS token in the first iteration, but it can in the others.
+ >>> outputs = model.generate(**inputs, return_dict_in_generate=True, output_scores=True)
+ >>> print(outputs.scores[0][0, 50256])
+ tensor(-inf)
+ >>> print(outputs.scores[-1][0, 50256]) # in other places we can see some probability mass for EOS
+ tensor(29.9010)
+
+ >>> # If we disable `begin_suppress_tokens`, we can generate EOS in the first iteration.
+ >>> outputs = model.generate(
+ ... **inputs, return_dict_in_generate=True, output_scores=True, begin_suppress_tokens=None
+ ... )
+ >>> print(outputs.scores[0][0, 50256])
+ tensor(11.2027)
+ ```
+ """
+
+ def __init__(self, begin_suppress_tokens, begin_index, device: str = "cpu"):
+ self.begin_suppress_tokens = torch.tensor(list(begin_suppress_tokens), device=device)
+ self.begin_index = begin_index
+
+ def set_begin_index(self, begin_index):
+ self.begin_index = begin_index
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ vocab_tensor = torch.arange(scores.shape[-1], device=scores.device)
+ suppress_token_mask = isin_mps_friendly(vocab_tensor, self.begin_suppress_tokens)
+ scores_processed = scores
+ if input_ids.shape[-1] == self.begin_index:
+ scores_processed = torch.where(suppress_token_mask, -float("inf"), scores)
+
+ return scores_processed
+
+
+class SuppressTokensLogitsProcessor(LogitsProcessor):
+ r"""
+ This processor can be used to suppress a list of tokens. The processor will set their log probs to `-inf` so
+ that they are not generated. Originally created for
+ [Whisper](https://huggingface.co/docs/transformers/model_doc/whisper).
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoProcessor, WhisperForConditionalGeneration
+ >>> from datasets import load_dataset
+
+ >>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
+ >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
+ >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
+
+ >>> # Whisper has a long list of suppressed tokens. For instance, in this case, the token 1 is suppressed by default.
+ >>> outputs = model.generate(**inputs, return_dict_in_generate=True, output_scores=True)
+ >>> print(outputs.scores[1][0, 1]) # 1 (and not 0) is the first freely generated token
+ tensor(-inf)
+
+ >>> # If we disable `suppress_tokens`, we can generate it.
+ >>> outputs = model.generate(**inputs, return_dict_in_generate=True, output_scores=True, suppress_tokens=None)
+ >>> print(outputs.scores[1][0, 1])
+ tensor(6.0678)
+ ```
+ """
+
+ def __init__(self, suppress_tokens, device: str = "cpu"):
+ self.suppress_tokens = torch.tensor(list(suppress_tokens), device=device)
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ vocab_tensor = torch.arange(scores.shape[-1], device=scores.device)
+ suppress_token_mask = isin_mps_friendly(vocab_tensor, self.suppress_tokens)
+ scores = torch.where(suppress_token_mask, -float("inf"), scores)
+ return scores
+
+
+class WhisperTimeStampLogitsProcessor(LogitsProcessor):
+ r"""
+
+ [`LogitsProcessor`] that modifies the logits for the generation of timestamps in the transcription. When the input
+ tokens are at a specific threshold, the processor sets the scores to negative infinity. The processor makes sure
+ that timestamp tokens appear in pairs, by masking out the logits that would break this pairing pattern. This is
+ done to maintain the consistency and structure of generated timestamps. It also ensures that when the predicted
+ probability of sampling any of the timestamp token is greater than any individual non-timestamp token, those
+ non-timestamp logits are set to negative infinity. This is done to ensure the generation of timestamps over other
+ potential tokens.
+
+
+ See [the paper](https://arxiv.org/abs/2212.04356) for more information.
+
+ Args:
+ generate_config (`GenerateConfig`):
+ The generate config used to generate the output. The following parameters are required:
+ eos_token_id (`int`, *optional*, defaults to 50257):
+ The id of the *end-of-sequence* token.
+ no_timestamps_token_id (`int`, *optional*, defaults to 50363):
+ The id of the `"<|notimestamps|>"` token.
+ max_initial_timestamp_index (`int`, *optional*, defaults to 1):
+ Used to set the maximum value of the initial timestamp. This is used to prevent the model from
+ predicting timestamps that are too far in the future.
+ begin_index (`Optional`, *optional*): Token index of the first token that is generated by the model.
+ _detect_timestamp_from_logprob (`bool`, *optional*): Whether timestamps can be predicted from logprobs over all timestamps.
+
+ Examples:
+ ``` python
+ >>> import torch
+ >>> from transformers import AutoProcessor, WhisperForConditionalGeneration, GenerationConfig
+ >>> from datasets import load_dataset
+
+ >>> processor = AutoProcessor.from_pretrained("openai/whisper-tiny.en")
+ >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
+ >>> inputs = processor(ds[3]["audio"]["array"], return_tensors="pt")
+ >>> input_features = inputs.input_features
+
+ >>> #Displaying timestamps
+ >>> generated_ids = model.generate(inputs=input_features, return_timestamps=True)
+ >>> transcription = processor.batch_decode(generated_ids, decode_with_timestamps=True)[0]
+ >>> print("Transcription:", transcription)
+ Transcription: <|startoftranscript|><|0.00|> He has grave doubts whether Sir Frederick Layton's work is really Greek after all, and can<|6.44|><|6.44|> discover in it but little of rocky Ithaca.<|9.44|><|endoftext|>
+
+
+ >>> #No timestamps & change EOS:
+ >>> #This allows the user to select a specific token to terminate the sequence on, in this case it's the word "can"(460)
+ >>> model.generation_config.eos_token_id = 460
+ >>> generated_ids = model.generate(inputs=input_features,return_timestamps=False)
+ >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
+ >>> print("Transcription:", transcription)
+ Transcription: He has grave doubts whether Sir Frederick Layton's work is really Greek after all and can
+ ```
+ """
+
+ def __init__(
+ self,
+ generate_config,
+ begin_index: Optional[int] = None,
+ _detect_timestamp_from_logprob: Optional[bool] = None,
+ ): # support for the kwargs
+ self.no_timestamps_token_id = generate_config.no_timestamps_token_id
+ self.timestamp_begin = generate_config.no_timestamps_token_id + 1
+ self.eos_token_id = generate_config.eos_token_id or generate_config.bos_token_id
+
+ # this variable is mostly just used for testing
+ self._detect_timestamp_from_logprob = (
+ _detect_timestamp_from_logprob
+ if _detect_timestamp_from_logprob is not None
+ else getattr(generate_config, "_detect_timestamp_from_logprob", True)
+ )
+
+ num_forced_ids = (
+ len(generate_config.forced_decoder_ids) if generate_config.forced_decoder_ids is not None else 0
+ )
+ self.begin_index = begin_index or (num_forced_ids + 1)
+
+ self.max_initial_timestamp_index = getattr(generate_config, "max_initial_timestamp_index", None)
+ # TODO(Patrick): Make sure that official models have max_initial_timestamp_index set to 50
+ # self.max_initial_timestamp_index = 50
+
+ def set_begin_index(self, begin_index):
+ self.begin_index = begin_index
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ # suppress <|notimestamps|> which is handled by without_timestamps
+ scores_processed = scores.clone()
+ scores_processed[:, self.no_timestamps_token_id] = -float("inf")
+
+ # timestamps have to appear in pairs, except directly before eos_token; mask logits accordingly
+ for k in range(input_ids.shape[0]):
+ sampled_tokens = input_ids[k, self.begin_index :]
+ seq = list(sampled_tokens.tolist())
+
+ last_was_timestamp = len(seq) >= 1 and seq[-1] >= self.timestamp_begin
+ penultimate_was_timestamp = len(seq) < 2 or seq[-2] >= self.timestamp_begin
+
+ if last_was_timestamp:
+ if penultimate_was_timestamp: # has to be non-timestamp
+ scores_processed[k, self.timestamp_begin :] = -float("inf")
+ else: # cannot be normal text tokens
+ scores_processed[k, : self.eos_token_id] = -float("inf")
+
+ timestamps = sampled_tokens[sampled_tokens.ge(self.timestamp_begin)]
+ if timestamps.numel() > 0:
+ # `timestamps` shouldn't decrease; forbid timestamp tokens smaller than the last
+ # The following lines of code are copied from: https://github.com/openai/whisper/pull/914/files#r1137085090
+ if last_was_timestamp and not penultimate_was_timestamp:
+ timestamp_last = timestamps[-1]
+ else:
+ # Avoid to emit <|0.00|> again
+ timestamp_last = timestamps[-1] + 1
+
+ scores_processed[k, self.timestamp_begin : timestamp_last] = -float("inf")
+
+ # apply the `max_initial_timestamp` option
+ if input_ids.shape[1] == self.begin_index:
+ scores_processed[:, : self.timestamp_begin] = -float("inf")
+
+ if self.max_initial_timestamp_index is not None:
+ last_allowed = self.timestamp_begin + self.max_initial_timestamp_index
+ scores_processed[:, last_allowed + 1 :] = -float("inf")
+
+ # if sum of probability over timestamps is above any other token, sample timestamp
+ logprobs = torch.nn.functional.log_softmax(scores_processed.float(), dim=-1)
+ for k in range(input_ids.shape[0]):
+ timestamp_logprob = logprobs[k, self.timestamp_begin :].logsumexp(dim=-1)
+ max_text_token_logprob = logprobs[k, : self.timestamp_begin].max()
+ if timestamp_logprob > max_text_token_logprob and self._detect_timestamp_from_logprob:
+ scores_processed[k, : self.timestamp_begin] = -float("inf")
+
+ return scores_processed
+
+
+class WhisperNoSpeechDetection(LogitsProcessor):
+ r"""This processor can be used to detect silence when using Whisper. It should take as input unprocessed logits to follow the original implementation"""
+
+ def __init__(self, no_speech_token: int, begin_index: int, scores_is_logprobs: bool = False):
+ self.no_speech_token = no_speech_token
+ # offset between token, , in paper and first generated token
+ # is equal to the position of the first generated token index
+ self.start_of_trans_offset = begin_index
+
+ # `self.begin_index` is a running value that is changed on the fly
+ self.begin_index = begin_index
+ self._no_speech_prob = [0.0]
+ self.is_scores_logprobs = scores_is_logprobs
+
+ # overwritten dynamically
+ self.model = None
+ self.inputs = None
+
+ def set_model(self, model):
+ self.model = model
+
+ def set_inputs(self, inputs):
+ self.inputs = {**self.model.prepare_inputs_for_generation(**inputs), **inputs}
+ self.inputs["input_features"] = self.inputs.pop("inputs")
+
+ @property
+ def no_speech_prob(self):
+ return self._no_speech_prob
+
+ def set_begin_index(self, begin_index):
+ self.begin_index = begin_index
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ is_scores_logprobs = self.is_scores_logprobs
+
+ if input_ids.shape[1] == self.begin_index:
+ if self.start_of_trans_offset > 1:
+ with torch.no_grad():
+ logits = self.model(**self.inputs).logits
+
+ no_speech_index = self.begin_index - self.start_of_trans_offset
+ no_speech_scores = logits[:, no_speech_index]
+ is_scores_logprobs = False
+ else:
+ no_speech_scores = scores
+
+ if is_scores_logprobs:
+ probs = no_speech_scores.exp()
+ else:
+ probs = no_speech_scores.float().softmax(dim=-1)
+
+ self._no_speech_prob = probs[:, self.no_speech_token]
+
+ return scores
+
+
+class ClassifierFreeGuidanceLogitsProcessor(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] for classifier free guidance (CFG). The scores are split over the batch dimension,
+ where the first half correspond to the conditional logits (predicted from the input prompt) and the second half
+ correspond to the unconditional logits (predicted from an empty or 'null' prompt). The processor computes a
+ weighted average across the conditional and unconditional logits, parameterised by the `guidance_scale`.
+
+ See [the paper](https://arxiv.org/abs/2306.05284) for more information.
+
+
+
+ This logits processor is exclusively compatible with
+ [MusicGen](https://huggingface.co/docs/transformers/main/en/model_doc/musicgen)
+
+
+
+ Args:
+ guidance_scale (float):
+ The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.
+ Higher guidance scale encourages the model to generate samples that are more closely linked to the input
+ prompt, usually at the expense of poorer quality.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoProcessor, MusicgenForConditionalGeneration
+
+ >>> processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
+ >>> model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")
+
+ >>> inputs = processor(
+ ... text=["80s pop track with bassy drums and synth", "90s rock song with loud guitars and heavy drums"],
+ ... padding=True,
+ ... return_tensors="pt",
+ ... )
+ >>> audio_values = model.generate(**inputs, do_sample=True, guidance_scale=3, max_new_tokens=256)
+ ```
+ """
+
+ def __init__(self, guidance_scale):
+ if guidance_scale > 1:
+ self.guidance_scale = guidance_scale
+ else:
+ raise ValueError(
+ "Require guidance scale >1 to use the classifier free guidance processor, got guidance scale "
+ f"{guidance_scale}."
+ )
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ # simple check to make sure we have compatible batch sizes between our
+ # logits scores (cond + uncond) and input ids (cond only)
+ if scores.shape[0] != 2 * input_ids.shape[0]:
+ raise ValueError(
+ f"Logits should have twice the batch size of the input ids, the first half of batches corresponding to "
+ f"the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got "
+ f"batch size {scores.shape[0]} for the logits and {input_ids.shape[0]} for the input ids."
+ )
+ unguided_bsz = scores.shape[0] // 2
+ cond_logits, uncond_logits = scores.split(unguided_bsz, dim=0)
+ scores_processed = uncond_logits + (cond_logits - uncond_logits) * self.guidance_scale
+ return scores_processed
+
+
+class AlternatingCodebooksLogitsProcessor(LogitsProcessor):
+ r"""
+ [`LogitsProcessor`] enforcing alternated generation between the two codebooks of Bark.
+
+
+
+ This logits processor is exclusively compatible with
+ [Bark](https://huggingface.co/docs/transformers/en/model_doc/bark)'s fine submodel. See the model documentation
+ for examples.
+
+
+
+ Args:
+ input_start_len (`int`):
+ The length of the initial input sequence.
+ semantic_vocab_size (`int`):
+ Vocabulary size of the semantic part, i.e number of tokens associated to the semantic vocabulary.
+ codebook_size (`int`):
+ Number of tokens associated to the codebook.
+ """
+
+ def __init__(self, input_start_len: int, semantic_vocab_size: int, codebook_size: int):
+ if not isinstance(input_start_len, int) or input_start_len < 0:
+ raise ValueError(f"`input_starting_length` has to be a non-negative integer, but is {input_start_len}")
+
+ self.input_start_len = input_start_len
+ self.semantic_vocab_size = semantic_vocab_size
+ self.codebook_size = codebook_size
+
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ curr_len = input_ids.shape[-1]
+
+ # even -> first codebook, odd -> second codebook
+ is_first_codebook = ((curr_len - self.input_start_len) % 2) == 0
+
+ scores_processed = scores.clone()
+ if is_first_codebook:
+ scores_processed[:, : self.semantic_vocab_size] = -float("inf")
+ scores_processed[:, self.semantic_vocab_size + self.codebook_size :] = -float("inf")
+ else:
+ scores_processed[:, : self.semantic_vocab_size + self.codebook_size] = -float("inf")
+
+ return scores_processed
+
+
+class UnbatchedClassifierFreeGuidanceLogitsProcessor(LogitsProcessor):
+ r"""
+ Logits processor for Classifier-Free Guidance (CFG). The processors computes a weighted average across scores
+ from prompt conditional and prompt unconditional (or negative) logits, parameterized by the `guidance_scale`.
+ The unconditional scores are computed internally by prompting `model` with the `unconditional_ids` branch.
+
+ See [the paper](https://arxiv.org/abs/2306.17806) for more information.
+
+ Args:
+ guidance_scale (`float`):
+ The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale != 1`.
+ Higher guidance scale encourages the model to generate samples that are more closely linked to the input
+ prompt, usually at the expense of poorer quality. A value smaller than 1 has the opposite effect, while
+ making the negative prompt provided with negative_prompt_ids (if any) act as a positive prompt.
+ model (`PreTrainedModel`):
+ The model computing the unconditional scores. Supposedly the same as the one computing the conditional
+ scores. Both models must use the same tokenizer.
+ unconditional_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of input sequence tokens in the vocabulary for the unconditional branch. If unset, will default to
+ the last token of the prompt.
+ unconditional_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Attention mask for unconditional_ids.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ Whether to cache key/values during the negative prompt forward pass.
+
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
+
+ >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
+ >>> inputs = tokenizer(["Today, a dragon flew over Paris, France,"], return_tensors="pt")
+ >>> out = model.generate(inputs["input_ids"], guidance_scale=1.5)
+ >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0]
+ 'Today, a dragon flew over Paris, France, killing at least 50 people and injuring more than 100'
+
+ >>> # with a negative prompt
+ >>> neg_inputs = tokenizer(["A very happy event happened,"], return_tensors="pt")
+ >>> out = model.generate(inputs["input_ids"], guidance_scale=2, negative_prompt_ids=neg_inputs["input_ids"])
+ >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0]
+ 'Today, a dragon flew over Paris, France, killing at least 130 people. French media reported that'
+
+ >>> # with a positive prompt
+ >>> neg_inputs = tokenizer(["A very happy event happened,"], return_tensors="pt")
+ >>> out = model.generate(inputs["input_ids"], guidance_scale=0, negative_prompt_ids=neg_inputs["input_ids"])
+ >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0]
+ "Today, a dragon flew over Paris, France, and I'm very happy to be here. I"
+ ```
+ """
+
+ def __init__(
+ self,
+ guidance_scale: float,
+ model,
+ unconditional_ids: Optional[torch.LongTensor] = None,
+ unconditional_attention_mask: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = True,
+ ):
+ self.guidance_scale = guidance_scale
+ self.model = model
+ self.unconditional_context = {
+ "input_ids": unconditional_ids,
+ "attention_mask": unconditional_attention_mask,
+ "use_cache": use_cache,
+ "past_key_values": None,
+ "first_pass": True,
+ }
+
+ def get_unconditional_logits(self, input_ids):
+ if self.unconditional_context["first_pass"]:
+ if self.unconditional_context["input_ids"] is None:
+ self.unconditional_context["input_ids"] = input_ids[:, -1:]
+ if self.unconditional_context["attention_mask"] is None:
+ self.unconditional_context["attention_mask"] = torch.ones_like(
+ self.unconditional_context["input_ids"], dtype=torch.long
+ )
+ input_ids = self.unconditional_context["input_ids"]
+ attention_mask = self.unconditional_context["attention_mask"]
+ self.unconditional_context["first_pass"] = False
+ else:
+ attention_mask = torch.cat(
+ [
+ self.unconditional_context["attention_mask"],
+ torch.ones_like(input_ids[:, -1:], dtype=torch.long),
+ ],
+ dim=1,
+ )
+ if not self.unconditional_context["use_cache"]:
+ input_ids = torch.cat([self.unconditional_context["input_ids"], input_ids[:, -1:]], dim=1)
+ else:
+ input_ids = input_ids[:, -1:]
+ self.unconditional_context["input_ids"] = input_ids
+ self.unconditional_context["attention_mask"] = attention_mask
+
+ out = self.model(
+ input_ids,
+ attention_mask=attention_mask,
+ use_cache=self.unconditional_context["use_cache"],
+ past_key_values=self.unconditional_context["past_key_values"],
+ )
+ self.unconditional_context["past_key_values"] = out.get("past_key_values", None)
+
+ return out.logits
+
+ def __call__(self, input_ids, scores):
+ scores = torch.nn.functional.log_softmax(scores, dim=-1)
+ if self.guidance_scale == 1:
+ return scores
+
+ logits = self.get_unconditional_logits(input_ids)
+
+ unconditional_logits = torch.nn.functional.log_softmax(logits[:, -1], dim=-1)
+ scores_processed = self.guidance_scale * (scores - unconditional_logits) + unconditional_logits
+ return scores_processed
+
+
+class BarkEosPrioritizerLogitsProcessor(LogitsProcessor):
+ r"""This processor ensures that the EOS token is selected if its probability is greater than the `min_eos_p`.
+
+
+
+ This logits processor is exclusively compatible with
+ [Bark](https://huggingface.co/docs/transformers/en/model_doc/bark). See the model documentation for examples.
+
+
+
+ Args:
+ eos_token_id (`Union[int, List[int], torch.Tensor]`):
+ The id(s) of the *end-of-sequence* token.
+ min_eos_p (`float`, *optional*):
+ Minimum end of speech threshold.
+ """
+
+ def __init__(self, eos_token_id: Union[int, List[int], torch.Tensor], min_eos_p: float, device: str = "cpu"):
+ if not isinstance(eos_token_id, torch.Tensor):
+ if isinstance(eos_token_id, int):
+ eos_token_id = [eos_token_id]
+ eos_token_id = torch.tensor(eos_token_id, device=device)
+ self.eos_token_id = eos_token_id
+
+ if torch.is_floating_point(eos_token_id) or (eos_token_id < 0).any():
+ raise ValueError(f"`eos_token_id` has to be a list of positive integers, but is {eos_token_id}")
+
+ if min_eos_p is not None and min_eos_p <= 0:
+ raise ValueError(f"`min_eos_p` has to be a positive float, but is {min_eos_p}")
+ self.min_eos_p = min_eos_p
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ scores_processed = scores
+ if self.min_eos_p:
+ probs = torch.nn.functional.softmax(scores.float(), dim=-1)
+ # create scores full of -inf except for the eos_token_id
+ early_stop_scores = torch.ones_like(scores) * -float("inf")
+ early_stop_scores[:, self.eos_token_id] = scores[:, self.eos_token_id]
+
+ do_early_stop = probs[:, self.eos_token_id] > self.min_eos_p
+ do_early_stop = torch.any(do_early_stop, dim=1, keepdim=True)
+ scores_processed = torch.where(do_early_stop, early_stop_scores, scores)
+
+ return scores_processed
+
+
+class WatermarkLogitsProcessor(LogitsProcessor):
+ r"""
+ Logits processor for watermarking generated text. The processor modifies model output scores by adding a small bias to
+ randomized set of "green" tokens before generating the next token. "Green" tokens selection process depends on the
+ `seeding_scheme` used. The code was based on the [original repo](https://github.com/jwkirchenbauer/lm-watermarking/tree/main).
+
+ The text generated by this `LogitsProcessor` can be detected using `WatermarkDetector`. See [`~WatermarkDetector.__call__`] for details,
+
+ See [the paper](https://arxiv.org/abs/2306.04634) for more information.
+
+ Args:
+ vocab_size (`int`):
+ The model tokenizer's vocab_size. Used to calculate "green" tokens ratio.
+ device (`str`):
+ The device where model is allocated.
+ greenlist_ratio (`float`, optional, *optional*, defaults to 0.25):
+ The ratio of "green" tokens used to the vocabulary size. Defaults to 0.25.
+ bias (`float`, optional, *optional*, defaults to 2.0):
+ The bias added to the selected "green" tokens' logits. Consider lowering the
+ `bias` if the text generation quality degrades. Recommended values are in the
+ range of [0.5, 2.0]. Defaults to 2.0.
+ hashing_key (`int`, optional, *optional*, defaults to 15485863):
+ Key used for hashing. If you deploy this watermark, we advise using another private key.
+ Defaults to 15485863 (the millionth prime).
+ seeding_scheme (`str`, optional, *optional*, defaults to `"lefthash"`):
+ The seeding scheme used for selecting "green" tokens. Accepts values:
+ - "lefthash" (default): "green" tokens selection depend on the last token (Algorithm 2 from paper)
+ - "selfhash": "green" tokens selection depends on the current token itself (Algorithm 3 from paper)
+ The downside of this scheme is that it considers all possible next tokens and can be slower than "lefthash".
+ The context length of previous tokens to use in seeding. Higher context length makes watermarking more robust.
+ context_width (`int`, *optional*, defaults to 1):
+ The number of previous tokens to use when setting the seed.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, WatermarkingConfig
+
+ >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
+ >>> inputs = tokenizer(["Alice and Bob are"], return_tensors="pt")
+
+ >>> # normal generation
+ >>> out = model.generate(inputs["input_ids"], max_length=20, do_sample=False)
+ >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0]
+ 'Alice and Bob are both in the same room.\n\n"I\'m not sure if you\'re'
+
+ >>> # watermarked generation
+ >>> watermarking_config = WatermarkingConfig(bias=2.5, context_width=2, seeding_scheme="selfhash")
+ >>> out = model.generate(inputs["input_ids"], watermarking_config=watermarking_config, max_length=20, do_sample=False)
+ >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0]
+ 'Alice and Bob are both still alive and well and the story is pretty much a one-hour adventure'
+
+ >>> # to detect watermarked text use the WatermarkDetector class
+ >>> from transformers import WatermarkDetector
+ >>> detector = WatermarkDetector(model_config=model.config, device="cpu", watermarking_config= watermarking_config)
+ >>> detection_preds = detector(out)
+ >>> detection_preds
+ array([ True])
+ ```
+ """
+
+ def __init__(
+ self,
+ vocab_size,
+ device,
+ greenlist_ratio: float = 0.25,
+ bias: float = 2.0,
+ hashing_key: int = 15485863,
+ seeding_scheme: str = "lefthash",
+ context_width: int = 1,
+ ):
+ if seeding_scheme not in ["selfhash", "lefthash"]:
+ raise ValueError(f"seeding_scheme has to be one of [`selfhash`, `lefthash`], but found {seeding_scheme}")
+ if greenlist_ratio >= 1.0 or greenlist_ratio <= 0.0:
+ raise ValueError(
+ f"greenlist_ratio has be in range between 0.0 and 1.0, exclusively. but found {greenlist_ratio}"
+ )
+
+ self.vocab_size = vocab_size
+ self.greenlist_size = int(self.vocab_size * greenlist_ratio)
+ self.bias = bias
+ self.seeding_scheme = seeding_scheme
+ self.rng = torch.Generator(device=device)
+ self.hash_key = hashing_key
+ self.context_width = context_width
+
+ self.rng.manual_seed(hashing_key)
+ self.table_size = 1_000_003
+ self.fixed_table = torch.randperm(self.table_size, generator=self.rng, device=device)
+
+ def set_seed(self, input_seq: torch.LongTensor):
+ input_seq = input_seq[-self.context_width :]
+ if self.seeding_scheme == "selfhash":
+ a = self.fixed_table[input_seq % self.table_size] + 1
+ b = self.fixed_table[input_seq[-1] % self.table_size] + 1
+ seed = (self.hash_key * a * b).min().item()
+ else:
+ seed = self.hash_key * input_seq[-1].item()
+ self.rng.manual_seed(seed % (2**64 - 1))
+
+ def _get_greenlist_ids(self, input_seq: torch.LongTensor) -> torch.LongTensor:
+ self.set_seed(input_seq)
+ vocab_permutation = torch.randperm(self.vocab_size, device=input_seq.device, generator=self.rng)
+ greenlist_ids = vocab_permutation[: self.greenlist_size]
+ return greenlist_ids
+
+ def _score_rejection_sampling(self, input_seq: torch.LongTensor, scores: torch.FloatTensor) -> torch.LongTensor:
+ """
+ Generate greenlist based on current candidate next token. Reject and move on if necessary.
+ Runs for a fixed number of steps only for efficiency, since the methods is not batched.
+ """
+ final_greenlist = []
+ _, greedy_predictions = scores.sort(dim=-1, descending=True)
+
+ # 40 is an arbitrary number chosen to save compute and not run for long (taken from orig repo)
+ for i in range(40):
+ greenlist_ids = self._get_greenlist_ids(torch.cat([input_seq, greedy_predictions[i, None]], dim=-1))
+ if greedy_predictions[i] in greenlist_ids:
+ final_greenlist.append(greedy_predictions[i])
+ return torch.tensor(final_greenlist, device=input_seq.device)
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ if input_ids.shape[-1] < self.context_width:
+ logger.warning(
+ f"`input_ids` should have at least `{self.context_width}` tokens but has {input_ids.shape[-1]}. "
+ "The seeding will be skipped for this generation step!"
+ )
+ return scores
+
+ scores_processed = scores.clone()
+ for b_idx, input_seq in enumerate(input_ids):
+ if self.seeding_scheme == "selfhash":
+ greenlist_ids = self._score_rejection_sampling(input_seq, scores[b_idx])
+ else:
+ greenlist_ids = self._get_greenlist_ids(input_seq)
+ scores_processed[b_idx, greenlist_ids] = scores_processed[b_idx, greenlist_ids] + self.bias
+
+ return scores_processed
+
+
+class SynthIDTextWatermarkState:
+ """SynthID watermarking state."""
+
+ def __init__(
+ self,
+ batch_size: int,
+ ngram_len: int,
+ context_history_size: int,
+ device: torch.device,
+ ):
+ """Initializes the state.
+
+ Args:
+ batch_size (`int`): Batch size.
+ ngram_len (`int`): Ngram length.
+ context_history_size (`int`): Size of the tensor to keep track of seen contexts.
+ device (`int`): Device to use.
+ """
+ self.context = torch.zeros(
+ (batch_size, ngram_len - 1),
+ dtype=torch.int64,
+ device=device,
+ )
+ self.context_history = torch.zeros(
+ (batch_size, context_history_size),
+ dtype=torch.int64,
+ device=device,
+ )
+ self.num_calls = 0
+
+
+class SynthIDTextWatermarkLogitsProcessor(LogitsProcessor):
+ r"""
+ Logits processor that implements watermarking techniques for text generation models.
+ This class facilitates the application of SynthID text watermarking, a method for embedding imperceptible signals
+ into generated text to aid in detecting synthetic content. It operates by subtly manipulating the probabilities of
+ token selection during text generation in a manner that can be reliably recovered later for verification.
+
+ Key Features:
+ * **State Management:** Maintains internal state to track token sequences and generate watermarking keys
+ dynamically.
+
+ * **Key Generation:** Computes hashes based on token sequences and watermarking parameters to create unique keys
+ for each position.
+
+ * **G-Value Sampling:** Employs a pre-computed sampling table to sample watermarking values (g-values) based on
+ the generated keys.
+
+ * **Score Adjustment:** Applies calculated g-values to modify token probabilities during generation, embedding the
+ watermark.
+
+ * **Context Repetition Handling:** Incorporates logic to avoid watermarking tokens in repeated contexts,
+ preserving naturalness.
+
+ * **EOS Token Masking:** Supports masking end-of-sentence tokens to prevent their inclusion in watermarking
+ calculations.
+
+ * **Utility Functions:** Provides functions to compute g-values directly, check for context repetition, create
+ EOS token masks, and estimate expected mean g-values.
+
+ Refer to paper url: https://www.nature.com/articles/s41586-024-08025-4 for more details around this.
+
+ Args:
+ ngram_len (`int`):
+ Ngram length.
+ keys (`List[int]`):
+ A sequence of watermarking keys, one for each depth.
+ sampling_table_size (`int`):
+ Size of the sampling table.
+ sampling_table_seed (`int`):
+ Random seed to generate the sampling table.
+ context_history_size (`int`):
+ Size of the tensor to keep track of seen contexts.
+ device (`torch.device`):
+ Device to use.
+ skip_first_ngram_calls (`bool`, *optional*, defaults to `False`):
+ Whether to skip first ngram calls.
+ debug_mode (`bool`, optional, *optional*, defaults to `False`):
+ Logits are modified to uniform one got before watermarking modification is applied. This is to test the
+ implementation.
+
+ Examples:
+ ```python
+ >>> from transformers import AutoModelForCausalLM, AutoTokenizer, SynthIDTextWatermarkingConfig
+
+ >>> tokenizer = AutoTokenizer.from_pretrained('google/gemma-2-2b', padding_side="left")
+ >>> model = AutoModelForCausalLM.from_pretrained('google/gemma-2-2b')
+
+ >>> # SynthID Text configuration
+ >>> watermarking_config = SynthIDTextWatermarkingConfig(
+ ... keys=[654, 400, 836, 123, 340, 443, 597, 160, 57],
+ ... ngram_len=5,
+ ... )
+
+ >>> # Generation with watermarking
+ >>> tokenized_prompts = tokenizer(["Once upon a time, "], return_tensors="pt", padding=True)
+ >>> output_sequences = model.generate(
+ ... **tokenized_prompts, watermarking_config=watermarking_config, do_sample=True, max_new_tokens=10
+ ... )
+ >>> watermarked_text = tokenizer.batch_decode(output_sequences, skip_special_tokens=True)
+ ```
+ """
+
+ def __init__(
+ self,
+ ngram_len: int,
+ keys: List[int],
+ sampling_table_size: int,
+ sampling_table_seed: int,
+ context_history_size: int,
+ device: torch.device,
+ skip_first_ngram_calls: bool = False,
+ debug_mode: bool = False,
+ ):
+ self.ngram_len = ngram_len
+ self.keys = torch.tensor(keys, device=device)
+
+ generator = torch.Generator(device=device).manual_seed(sampling_table_seed)
+ # A random sampling table is pre-computed and modulo table size is applied to map from a hash of ngram keys to
+ # g values, this is similar to the hashtable implementation used in
+ # https://github.com/facebookresearch/three_bricks. We note that the hashing employed in this repository is
+ # different from that used to watermark the Gemini App, and hence the detectors trained based on the
+ # hashing in this repository will not transfer to text generated by the Gemini App.
+ self.sampling_table = torch.randint(
+ low=0,
+ high=2,
+ size=(sampling_table_size,),
+ generator=generator,
+ device=device,
+ )
+ self.context_history_size = context_history_size
+ self.device = device
+ self.state = None
+ self.skip_first_ngram_calls = skip_first_ngram_calls
+ self.debug_mode = debug_mode
+
+ def _init_state(self, batch_size: int):
+ """Initializes the state."""
+ self.state = SynthIDTextWatermarkState(
+ batch_size=batch_size,
+ ngram_len=self.ngram_len,
+ context_history_size=self.context_history_size,
+ device=self.device,
+ )
+
+ def update_scores(self, scores: torch.FloatTensor, g_values: torch.FloatTensor) -> torch.FloatTensor:
+ """Updates scores using the g values.
+
+ We assume that the scores are in the log space.
+ Args:
+ scores (`torch.FloatTensor`): Scores (batch_size, vocab_size).
+ g_values (`torch.FloatTensor`): G valus (batch_size, vocab_size, depth).
+
+ Returns:
+ Updated scores (batch_size, vocab_size).
+ """
+ _, _, depth = g_values.shape
+
+ probs = torch.softmax(scores, dim=1)
+
+ for i in range(depth):
+ g_values_at_depth = g_values[:, :, i]
+ g_mass_at_depth = (g_values_at_depth * probs).sum(axis=1, keepdims=True)
+ probs = probs * (1 + g_values_at_depth - g_mass_at_depth)
+
+ log_probs = torch.log(probs)
+ log_probs = torch.where(torch.isfinite(log_probs), log_probs, torch.finfo(log_probs.dtype).min)
+ return log_probs
+
+ @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ self._check_input_ids_shape(input_ids)
+ batch_size, vocab_size = scores.shape
+
+ if self.debug_mode:
+ scores = torch.ones_like(scores)
+
+ # Currently indices is just a arange to compute watermarking on the desnse logits.
+ all_indices = torch.stack([torch.arange(vocab_size, device=self.device) for _ in range(batch_size)])
+
+ if self.state is None:
+ # Initialize watermarking state if it does not exist.
+ self._init_state(batch_size)
+ else:
+ # Append last input id (which is the input id added in last call) to the
+ # previous context so we have the context to be used for current
+ # watermarking.
+ self.state.context = torch.concat(
+ (self.state.context, input_ids[:, -1:]),
+ dim=1,
+ )
+ self.state.context = self.state.context[:, 1:]
+
+ if self.state is None:
+ raise ValueError("self.state can't be None! Call `self._init_state` to initialize the state.")
+
+ self.state.num_calls += 1
+
+ # Don't watermark the first ngram_len - 1 tokens if set.
+ if self.skip_first_ngram_calls and self.state.num_calls < self.ngram_len:
+ return scores
+
+ # 2. Generate random keys for each ngram key combination.
+ ngram_keys, hash_result_with_just_context = self._compute_keys(self.state.context, all_indices)
+ # ngram_keys shape [batch_size, top_k, depth]
+
+ # 3. Sample g values.
+ g_values = self.sample_g_values(ngram_keys)
+ # g_values shape [batch_size, top_k, depth]
+
+ # 4. Modify scores.
+ updated_scores = self.update_scores(scores, g_values)
+ # updated scores shape [batch_size, top_k]
+
+ # 5. Check if the current watermarking context was previously used, if yes skip watermarking.
+ hash_result_with_just_context = hash_result_with_just_context[:, None]
+ is_repeated_context = (self.state.context_history == hash_result_with_just_context).any(
+ dim=1,
+ keepdim=True,
+ )
+ self.state.context_history = torch.concat(
+ (hash_result_with_just_context, self.state.context_history),
+ dim=1,
+ )[:, :-1]
+
+ updated_watermarked_scores = torch.where(
+ is_repeated_context,
+ input=scores,
+ other=updated_scores,
+ )
+ return updated_watermarked_scores
+
+ def accumulate_hash(
+ self,
+ current_hash: torch.LongTensor,
+ data: torch.LongTensor,
+ multiplier: int = 6364136223846793005,
+ increment: int = 1,
+ ) -> torch.LongTensor:
+ """
+ Accumulate hash of data on current hash.
+
+ Method uses adapted linear congruential generator with newlib/musl parameters.
+
+ This function has following property -
+ f(x, data[T]) = f(f(x, data[:T - 1]), data[T])
+
+ This function expects current_hash.shape and data.shape[:-1] to
+ match/broadcastable.
+
+ Args:
+ current_hash (`torch.LongTensor`):
+ (shape,)
+ data (`torch.LongTensor`):
+ (shape, tensor_len)
+ multiplier (`int`, optional, *optional*, defaults to 6364136223846793005):
+ multiplier of linear congruential generator
+ increment (`int`, optional, *optional*, defaults to 1):
+ increment of linear congruential generator
+
+ Returns:
+ updated hash (shape,)
+ """
+ for i in range(data.shape[-1]):
+ current_hash = torch.add(current_hash, data[..., i])
+ current_hash = torch.mul(current_hash, multiplier)
+ current_hash = torch.add(current_hash, increment)
+ return current_hash
+
+ def compute_ngram_keys(self, ngrams: torch.LongTensor) -> torch.LongTensor:
+ """Computes random keys for each ngram and depth.
+
+ Args:
+ ngrams (`torch.LongTensor`):
+ Ngrams (batch_size, num_ngrams, ngram_len).
+
+ Returns:
+ ngram keys (batch_size, num_ngrams, depth).
+ """
+ if len(ngrams.shape) != 3:
+ raise ValueError(
+ "Ngrams should be of shape (batch_size, num_ngrams, ngram_len), but" f" is {ngrams.shape}"
+ )
+ if ngrams.shape[2] != self.ngram_len:
+ raise ValueError(
+ "Ngrams should be of shape (batch_size, num_ngrams, ngram_len),"
+ f" where ngram_len is {self.ngram_len}, but is {ngrams.shape}"
+ )
+ batch_size, _, _ = ngrams.shape
+
+ hash_result = torch.ones(batch_size, device=self.device, dtype=torch.long)
+ # hash_result shape [batch_size,]
+ # ngrams shape [batch_size, num_ngrams, ngram_len]
+ hash_result = torch.vmap(self.accumulate_hash, in_dims=(None, 1), out_dims=1)(hash_result, ngrams)
+ # hash_result shape [batch_size, num_ngrams]
+
+ keys = self.keys[None, None, :, None]
+ # hash_result shape [batch_size, num_ngrams]
+ # keys shape [1, 1, depth, 1]
+ hash_result = torch.vmap(self.accumulate_hash, in_dims=(None, 2), out_dims=2)(hash_result, keys)
+ # hash_result shape [batch_size, num_ngrams, depth]
+
+ return hash_result
+
+ def _compute_keys(
+ self, n_minus_1_grams: torch.LongTensor, indices: torch.LongTensor
+ ) -> Tuple[torch.LongTensor, torch.LongTensor]:
+ """Computes random keys for each ngram and depth.
+
+ Args:
+ n_minus_1_grams (`torch.LongTensor`):
+ Ngrams (batch_size, ngram_len - 1).
+ indices (`torch.LongTensor`):
+ indices of the continuations (batch_size, num_indices)
+
+ Returns:
+ Ngram keys (batch_size, num_indices, depth).
+ """
+ batch_size, _ = n_minus_1_grams.shape
+
+ hash_result = torch.ones(batch_size, device=self.device, dtype=torch.long)
+ # First hash n_minus_1 gram, for each batch entry we have a single
+ # n_minus_1 gram context.
+ # hash_result shape [batch_size]
+ # n_minus_1_gram shape [batch_size, ngram_len - 1]
+ hash_result_with_just_context = self.accumulate_hash(hash_result, n_minus_1_grams)
+ # hash_result shape [batch_size,]
+ # Indices is of shape [batch_size, num_indices], so we make it
+ # [batch_size, num_indices, 1] so we can vmap over num_indices dim.
+ hash_result = torch.vmap(self.accumulate_hash, in_dims=(None, 1), out_dims=1)(
+ hash_result_with_just_context, indices[:, :, None]
+ )
+ # hash_result shape [batch_size, num_indices]
+ # Basically we have a hash for each batch entry and each indices
+ # Now we add watermarking keys to this hash.
+ # keys are of shape [depth,]
+ # We add batch, num_indices and data dimension to this making it
+ # [1, 1, depth, 1].
+ # So we can vmap over the depth dimension for compute_hash
+ keys = self.keys[None, None, :, None]
+ hash_result = torch.vmap(self.accumulate_hash, in_dims=(None, 2), out_dims=2)(hash_result, keys)
+ # hash_result shape should be [batch_size, num_indices, depth]
+ return hash_result, hash_result_with_just_context
+
+ def sample_g_values(self, ngram_keys: torch.LongTensor) -> torch.LongTensor:
+ """
+ Samples g values from Bernoulli distribution.
+
+ It is not possible to pass random keys in a vectorized way in torch. Instead
+ we pre-compute a random sampling table, and use apply modulo table size to
+ map from ngram keys (int64) to g values.
+
+ Args:
+ ngram_keys (`torch.LongTensor`):
+ Random keys (batch_size, num_ngrams, depth).
+
+ Returns:
+ G values (batch_size, num_ngrams, depth).
+ """
+ (sampling_table_size,) = self.sampling_table.shape
+ sampling_table = self.sampling_table.reshape((1, 1, sampling_table_size))
+ ngram_keys = ngram_keys % sampling_table_size
+ return torch.take_along_dim(sampling_table, indices=ngram_keys, dim=2)
+
+ def _check_input_ids_shape(self, input_ids: torch.LongTensor):
+ """Checks the shape of input ids."""
+ if len(input_ids.shape) != 2:
+ raise ValueError("Input ids should be of shape (batch_size, input_len), but is" f" {input_ids.shape}")
+
+ def compute_g_values(self, input_ids: torch.LongTensor) -> torch.LongTensor:
+ """
+ Computes g values for each ngram from the given sequence of tokens.
+
+ Args:
+ input_ids (`torch.LongTensor`):
+ Input token ids (batch_size, input_len).
+
+ Returns:
+ G values (batch_size, input_len - (ngram_len - 1), depth).
+ """
+ self._check_input_ids_shape(input_ids)
+ ngrams = input_ids.unfold(dimension=1, size=self.ngram_len, step=1)
+ ngram_keys = self.compute_ngram_keys(ngrams)
+ return self.sample_g_values(ngram_keys)
+
+ def compute_context_repetition_mask(self, input_ids: torch.LongTensor) -> torch.LongTensor:
+ """
+ Computes repetition mask.
+
+ 0 and 1 stand for repeated and not repeated context n-1 grams respectively.
+
+ Args:
+ input_ids (`torch.LongTensor`):
+ Input token ids (batch_size, input_len).
+
+ Returns:
+ Repetitions mask (batch_size, input_len - (ngram_len - 1)).
+ """
+ self._check_input_ids_shape(input_ids)
+ batch_size, _ = input_ids.shape
+ state = SynthIDTextWatermarkState(
+ batch_size=batch_size,
+ ngram_len=self.ngram_len,
+ context_history_size=self.context_history_size,
+ device=self.device,
+ )
+ contexts = input_ids[:, :-1].unfold(
+ dimension=1,
+ size=self.ngram_len - 1,
+ step=1,
+ )
+ _, num_contexts, _ = contexts.shape
+
+ are_repeated_contexts = []
+ for i in range(num_contexts):
+ context = contexts[:, i, :]
+ hash_result = torch.ones(batch_size, device=self.device, dtype=torch.long)
+ context_hash = self.accumulate_hash(hash_result, context)[:, None]
+ is_repeated_context = (state.context_history == context_hash).any(
+ dim=1,
+ keepdim=True,
+ )
+ are_repeated_contexts.append(is_repeated_context)
+ state.context_history = torch.concat(
+ (context_hash, state.context_history),
+ dim=1,
+ )[:, :-1]
+ are_repeated_contexts = torch.concat(are_repeated_contexts, dim=1)
+
+ return torch.logical_not(are_repeated_contexts)
+
+ def compute_eos_token_mask(self, input_ids: torch.LongTensor, eos_token_id: int) -> torch.LongTensor:
+ """
+ Computes repetitions mask.
+
+ 1 stands for ngrams that don't contain EOS tokens and vice versa.
+
+ Args:
+ input_ids (`torch.LongTensor`):
+ Input token ids (batch_size, input_len).
+ eos_token_id (`int`):
+ EOS token ID.
+
+ Returns:
+ EOS token mask (batch_size, input_len).
+ """
+ self._check_input_ids_shape(input_ids)
+ noneos_masks = []
+ all_eos_equated = input_ids == eos_token_id
+ for eos_equated in all_eos_equated:
+ nonzero_idx = torch.nonzero(eos_equated)
+ noneos_mask = torch.ones_like(eos_equated)
+ if nonzero_idx.shape[0] != 0:
+ noneos_mask[nonzero_idx[0][0] :] = 0
+ noneos_masks.append(noneos_mask)
+ return torch.stack(noneos_masks, dim=0)
+
+ def expected_mean_g_value(self, vocab_size: int, coinflip_prob: float = 0.5) -> float:
+ """
+ Compute expected mean g-value after watermarking, assuming uniform LM dist.
+
+ This is the theoretical expected value for single-layer watermarking.
+
+ Args:
+ vocab_size (`int`):
+ The size of the vocabulary.
+ coinflip_prob arg_name (`float`, *optional*, defaults to 0.5):
+ Probability of 1 in boolean prf.
+
+ Returns:
+ The expected mean g-value for watermarked text.
+ """
+ return coinflip_prob + coinflip_prob * (1 - coinflip_prob) * (1 - (1 / vocab_size))
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/stopping_criteria.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/stopping_criteria.py
new file mode 100644
index 0000000000000000000000000000000000000000..4627aeb9702707602d1f09e2f2121ee47338fe39
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/stopping_criteria.py
@@ -0,0 +1,519 @@
+import time
+import warnings
+from abc import ABC
+from collections import OrderedDict
+from copy import deepcopy
+from typing import Dict, List, Optional, Tuple, Union
+
+import numpy as np
+import torch
+from torch.nn import functional as F
+
+from ..pytorch_utils import isin_mps_friendly
+from ..tokenization_utils_base import PreTrainedTokenizerBase
+from ..utils import add_start_docstrings, logging
+
+
+logger = logging.get_logger(__name__)
+# We maintain a module-level cache of the embedding vectors for the stop string criterion
+# because they are slow to compute
+STOP_STRING_EMBEDDING_CACHE = OrderedDict()
+
+
+STOPPING_CRITERIA_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
+ Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
+ or scores for each vocabulary token after SoftMax. If this stopping criteria depends on the `scores` input,
+ make sure you pass `return_dict_in_generate=True, output_scores=True` to `generate`.
+ kwargs (`Dict[str, Any]`, *optional*):
+ Additional stopping criteria specific kwargs.
+
+ Return:
+ `torch.BoolTensor`. (`torch.BoolTensor` of shape `(batch_size, 1)`), where `True` indicates we stop generation
+ for a particular row, `True` indicates we should continue.
+
+"""
+
+
+class StoppingCriteria(ABC):
+ """Abstract base class for all stopping criteria that can be applied during generation.
+
+ If your stopping criteria depends on the `scores` input, make sure you pass `return_dict_in_generate=True,
+ output_scores=True` to `generate`.
+ """
+
+ @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.BoolTensor:
+ raise NotImplementedError("StoppingCriteria needs to be subclassed")
+
+
+class MaxLengthCriteria(StoppingCriteria):
+ """
+ This class can be used to stop generation whenever the full generated number of tokens exceeds `max_length`. Keep
+ in mind for decoder-only type of transformers, this will include the initial prompted tokens.
+
+ Args:
+ max_length (`int`):
+ The maximum length that the output sequence can have in number of tokens.
+ max_position_embeddings (`int`, *optional*):
+ The maximum model length, as defined by the model's `config.max_position_embeddings` attribute.
+ """
+
+ def __init__(self, max_length: int, max_position_embeddings: Optional[int] = None):
+ self.max_length = max_length
+ self.max_position_embeddings = max_position_embeddings
+
+ @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.BoolTensor:
+ cur_len = input_ids.shape[-1]
+ is_done = cur_len >= self.max_length
+ if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings:
+ logger.warning_once(
+ "This is a friendly reminder - the current text generation call will exceed the model's predefined "
+ f"maximum length ({self.max_position_embeddings}). Depending on the model, you may observe "
+ "exceptions, performance degradation, or nothing at all."
+ )
+ return torch.full((input_ids.shape[0],), is_done, device=input_ids.device, dtype=torch.bool)
+
+
+class MaxTimeCriteria(StoppingCriteria):
+ """
+ This class can be used to stop generation whenever the full generation exceeds some amount of time. By default, the
+ time will start being counted when you initialize this function. You can override this by passing an
+ `initial_time`.
+
+ Args:
+ max_time (`float`):
+ The maximum allowed time in seconds for the generation.
+ initial_time (`float`, *optional*, defaults to `time.time()`):
+ The start of the generation allowed time.
+ """
+
+ def __init__(self, max_time: float, initial_timestamp: Optional[float] = None):
+ self.max_time = max_time
+ self.initial_timestamp = time.time() if initial_timestamp is None else initial_timestamp
+
+ @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.BoolTensor:
+ is_done = time.time() - self.initial_timestamp > self.max_time
+ return torch.full((input_ids.shape[0],), is_done, device=input_ids.device, dtype=torch.bool)
+
+
+class StopStringCriteria(StoppingCriteria):
+ """
+ This class can be used to stop generation whenever specific string sequences are generated. It preprocesses
+ the strings together with the tokenizer vocab to find positions where tokens can validly complete the stop strings.
+
+ Generation is stopped as soon as a token is generated that completes any of the stop strings.
+ We want to catch any instance in which the stop string would be present in the decoded output, which means
+ we must also catch cases with "overhangs" off one or both ends. To make this more concrete, for the stop string
+ "stop", any of the following token sequences would trigger the match:
+
+ - ["st", "op"]
+ - ["stop"]
+ - ["st", "opera"]
+ - ["sto", "pper"]
+ - ["las", "topper"]
+ - ["s", "to", "pped"]
+
+ Note that a match will only be triggered if the stop string is at the end of the generated sequence. In other
+ words, these sequences will not trigger a match:
+
+ - ["stop", "at"]
+ - ["st", "op", "at"]
+ - ["st", "opera", "tion"]
+
+ The reason these are not a match is that the stop string does not overlap with the final token. If you can remove
+ one or more tokens from the end of the sequence without destroying the stop string, then this criterion will not
+ match that stop string. This is by design; because this check is run after each token is generated, we can't miss a
+ valid stop string if one is generated, but we don't want to halt generation just because the stop string exists
+ somewhere in the past input_ids.
+
+ How is the match actually performed, though? We do it in quite a confusing way, because we want the entire match
+ process to be compilable with Torch or XLA, which means we cannot use standard string methods. However, it is possible,
+ with some work, to do string matching with pure tensor operations. We'll begin by describing the algorithm we use
+ with standard string operations, and then at the end we'll explain how this is converted to pure tensor operations.
+
+ The key to the algorithm is an observation: Because the stop string must overlap with the end of the token sequence, we can start at
+ the end of the sequence and work backwards. Specifically, we check that there is an overlap between the start of
+ the final token and the end of the stop_string, or to put it another way, stop_string[-i:] == token[:i] for
+ some i > 0. If you look at the positive examples above, you'll see the last token in all of them fulfills this
+ property:
+
+ - ["st", "op"] (overlap is "op", overlap length == 2)
+ - ["stop"] (overlap is "stop", overlap length == 4)
+ - ["st", "opera"] (overlap is "op", overlap length == 2)
+ - ["sto", "pper"] (overlap is "p", overlap length == 1)
+ - ["las", "topper"] (overlap is "top", overlap length == 3)
+ - ["s", "to", "pped"] (overlap is "p", overlap length == 1)
+
+ It's impossible to construct a matching sequence that does not have this property (feel free to verify this
+ yourself). However, although this overlap between the start of the final token and the end of the stop string is
+ necessary for a match, it is not sufficient. We also need to check that the rest of the token sequence is
+ consistent with the stop string.
+
+ How do we do that? Let's use ["s", "to", "pped"] as an example. We know that the final token, "pped", has an
+ overlap of 1 with the stop string, "stop". We then go back to the previous token, "to". Since we have already
+ matched 1 character from the stop string, the remainder to check is "sto". We check that the next token "to"
+ matches the end of the remainder, which it does. We have now matched 3 characters from the stop string, and the
+ remainder to match is "s". We go back to the previous token again, which is also "s". This is a match, and so
+ we have matched the entire stop string.
+
+ How does it work when the tokens run off the start of the stop string, though? Let's consider the example of
+ ["las", "topper"]. The final token, "topper", has an overlap of 3 with the stop string, "stop". Therefore,
+ the remaining stop string to match is "s". We go back to the previous token, "las". Because the remainder to
+ match is just "s", with length 1, we consider only the final 1 character from the token, which is "s". This
+ matches the stop string, and so the entire string is matched.
+
+ How do we compute these matches with tensor operations, though? Simply: we efficiently precompute the necessary
+ information for all tokens! For every token, we compute:
+ - Its overlap with the end of the stop string, if any
+ - The positions inside the stop string where the token matches, including matches that run off the start.
+ - The total length of the token
+
+ For example, for the token "pped", we would compute an end overlap of 1, no internal matching positions,
+ and a length of 4. For the token "to", we would compute no end overlap, a single internal matching position
+ of 1 (counting from the end), and a length of 2. For the token "s", we would compute no end overlap,
+ a single internal matching position of 3 (again counting from the end) and a length of 1.
+
+ As long as we have this information, we can execute the algorithm above without any string comparison
+ operations. We simply perform the following steps:
+ - Check if the final token has an end-overlap with the start string
+ - Continue backwards, keeping track of how much of the stop string we've matched so far
+ - At each point, check if the next token has the current position as one of its valid positions
+ - Continue until either a match fails, or we completely match the whole stop string
+
+ Again, consider ["s", "to", "pped"] as an example. "pped" has an end overlap of 1, so we can begin a match.
+ We have matched 1 character so far, so we check that the next token "to", has 1 as a valid position (again,
+ counting from the end). It does, so we add the length of "to" to our position tracker. We have now matched
+ 3 characters, so we check that the next token "s" has 3 as a valid position. It does, so we add its length
+ to the position tracker. The position tracker is now 4, which is the length of the stop string. We have matched the
+ entire stop string.
+
+ In the second case, ["las", "topper"], "topper" has an end overlap of 3, so we can begin a match. We have
+ matched 3 characters so far, so we check that the next token "las" has 3 as a valid position. It does, because we
+ allow tokens to match positions that run off the start of the stop string. We add its length to the position
+ tracker. The position tracker is now 6, which is greater than the length of the stop string! Don't panic, though -
+ this also counts as a match of the stop string. We have matched the entire stop string.
+
+
+ Args:
+ tokenizer (`PreTrainedTokenizer`):
+ The model's associated tokenizer (necessary to extract vocab and tokenize the termination sequences)
+ stop_strings (`Union[str, List[str]]`):
+ A list of strings that should end generation. If a string is passed, it will be treated like a
+ list with a single element.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoModelForCausalLM, AutoTokenizer
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-2")
+ >>> model = AutoModelForCausalLM.from_pretrained("microsoft/phi-2")
+ >>> inputs = tokenizer("The biggest states in the USA by land area:", return_tensors="pt")
+
+ >>> gen_out = model.generate(**inputs)
+ >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])
+ The biggest states in the USA by land area:
+ - Alaska
+ - Texas
+ - California
+
+ >>> # Passing one or more stop strings will halt generation after those strings are emitted
+ >>> # Note that generating with stop strings requires you to pass the tokenizer too
+ >>> gen_out = model.generate(**inputs, stop_strings=["Texas"], tokenizer=tokenizer)
+ >>> print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])
+ The biggest states in the USA by land area:
+ - Alaska
+ - Texas
+ ```
+ """
+
+ def __init__(self, tokenizer: PreTrainedTokenizerBase, stop_strings: Union[str, List[str]]):
+ if isinstance(stop_strings, str):
+ stop_strings = [stop_strings]
+ self.stop_strings: Tuple[str, ...] = tuple(stop_strings)
+ vocab = tokenizer.get_vocab()
+ token_list, token_indices = tuple(vocab.keys()), tuple(vocab.values())
+ self.embedding_vec, self.max_valid_positions, self.max_valid_end_lens = self.clean_and_embed_tokens_with_cache(
+ token_list, token_indices, tokenizer
+ )
+
+ self.maximum_token_len = max([len(stop_string) for stop_string in self.stop_strings])
+ self.num_stop_strings = len(self.stop_strings)
+ self.target_lens = torch.tensor([len(stop_string) for stop_string in stop_strings], dtype=torch.int32)
+
+ def clean_and_embed_tokens_with_cache(self, token_list, token_indices, tokenizer):
+ # We don't use the tokenizer in the cache key, because I don't trust it to have well-behaved equality
+ if (token_list, token_indices, self.stop_strings) in STOP_STRING_EMBEDDING_CACHE:
+ embedding_vec, max_valid_positions, max_valid_end_lens = STOP_STRING_EMBEDDING_CACHE[
+ (token_list, token_indices, self.stop_strings)
+ ]
+ STOP_STRING_EMBEDDING_CACHE.move_to_end((token_list, token_indices, self.stop_strings))
+ else:
+ clean_token_list, clean_token_indices = self.clean_tokenizer_vocab(tokenizer)
+ embedding_vec, max_valid_positions, max_valid_end_lens = self._stop_string_create_embedding_vec(
+ clean_token_list, clean_token_indices, self.stop_strings
+ )
+ STOP_STRING_EMBEDDING_CACHE[(token_list, token_indices, self.stop_strings)] = (
+ embedding_vec,
+ max_valid_positions,
+ max_valid_end_lens,
+ )
+ if len(STOP_STRING_EMBEDDING_CACHE) > 8:
+ STOP_STRING_EMBEDDING_CACHE.popitem(last=False) # Pop from the start, the least recently used item
+ return embedding_vec, max_valid_positions, max_valid_end_lens
+
+ @staticmethod
+ def clean_tokenizer_vocab(tokenizer, static_prefix="abcdef"):
+ """
+ This method turns a tokenizer vocab into a "clean" vocab where each token represents the actual string
+ it will yield, without any special prefixes like "##" or "Ġ". This is trickier than it looks - the method
+ tokenizer.convert_tokens_to_string() does not always return the correct string because of issues with prefix
+ space addition/removal. To work around this, we add a static prefix to the start of the token, then remove
+ it (and any prefix that may have been introduced with it) after calling convert_tokens_to_string().
+ """
+ vocab = tokenizer.get_vocab()
+ clean_token_list = []
+ clean_token_indices = []
+ sentence_base = tokenizer(static_prefix, add_special_tokens=False)["input_ids"]
+ tokens_base = [tokenizer._convert_id_to_token(tok) for tok in sentence_base]
+ for token, token_idx in vocab.items():
+ token_string = tokenizer.convert_tokens_to_string(tokens_base + [token])
+ token_string = token_string[token_string.index(static_prefix) + len(static_prefix) :]
+ clean_token_list.append(token_string)
+ clean_token_indices.append(token_idx)
+ return tuple(clean_token_list), tuple(clean_token_indices)
+
+ @staticmethod
+ def _stop_string_get_matching_positions(
+ token_list, token_indices, stop_strings
+ ) -> Tuple[Dict[str, Dict[str, List[int]]], Dict[str, Dict[str, List[int]]]]:
+ """This function preprocesses stop strings and the tokenizer vocabulary to determine where tokens can
+ validly appear in the stop strings. For each token, it computes a list of positions in the stop string where the
+ token appears, as well as a list of the possible "end overlaps" for that token - that is, the number of characters
+ from the end of the stop string that overlap with the start of the token, which can have more than one value.
+
+ The reason for computing these may seem a bit cryptic - please see the docstring for StopStringCriteria for a full
+ explanation of what these values are for!"""
+
+ token_valid_positions = {}
+ token_end_overlaps = {}
+ for stop_string in stop_strings:
+ reversed_stop_string = stop_string[::-1]
+ token_valid_positions[stop_string] = {}
+ token_end_overlaps[stop_string] = {}
+ for token, tok_idx in zip(token_list, token_indices):
+ reversed_token = token[::-1]
+ matching_positions = []
+ possible_end_lengths = []
+ for i in range(1 - len(token), len(stop_string)):
+ if i < 0:
+ tok = reversed_token[-i:]
+ i = 0
+ else:
+ tok = reversed_token
+ stop = reversed_stop_string[i : i + len(tok)]
+ if tok.startswith(stop):
+ if i == 0:
+ possible_end_lengths.append(min(len(tok), len(stop)))
+ else:
+ matching_positions.append(i)
+
+ if matching_positions:
+ token_valid_positions[stop_string][tok_idx] = matching_positions
+ if possible_end_lengths:
+ token_end_overlaps[stop_string][tok_idx] = possible_end_lengths
+ return token_valid_positions, token_end_overlaps
+
+ @staticmethod
+ def _stop_string_create_embedding_vec(token_list, token_indices, stop_strings) -> Dict[str, torch.tensor]:
+ """This function precomputes everything needed for the run-time checks in StopStringCriteria, and packs
+ them into an embedding tensor that can be accessed with pure tensor operations. For the specifics of the values
+ that are precomputed and what they are used for, please refer to the StopStringCriteria docstring!"""
+ token_valid_positions, token_end_overlaps = StopStringCriteria._stop_string_get_matching_positions(
+ token_list, token_indices, stop_strings
+ )
+ all_valid_positions = [len(val) for positions in token_valid_positions.values() for val in positions.values()]
+ # In some cases, tokens may have no valid internal positions (such as single-character stop strings), so
+ # we need a fallback to handle this case
+ max_valid_positions = max(all_valid_positions) if all_valid_positions else 1
+ # There should always be at least one valid end_len, however, so no fallback needed here
+ valid_end_lens = [len(val) for positions in token_end_overlaps.values() for val in positions.values()]
+ if not valid_end_lens:
+ raise ValueError(
+ "Stop string preprocessing was unable to identify tokens matching one or more of the "
+ "supplied stop string(s). This is most often caused by the stop "
+ "strings containing unusual characters that are not in the tokenizer vocabulary."
+ )
+ max_valid_end_lens = max(valid_end_lens)
+ vec_size = len(stop_strings) * (max_valid_positions + max_valid_end_lens) + 1
+ # We use +2 instead of +1 so we can have a dummy entry at the end. We will clamp all token values
+ # over the max to this, ensuring they do not contribute to stop string matching.
+ gather_vec = np.full((max(token_indices) + 2, vec_size), dtype=np.int32, fill_value=-1)
+
+ for i, stop_string in enumerate(stop_strings):
+ positions = token_valid_positions[stop_string]
+ end_lens = token_end_overlaps[stop_string]
+
+ # Since this is lots of very small assignments of lists, we build it with numpy rather
+ # than torch for speed + simplicity, then convert to torch at the end
+ for token_idx, valid_positions in positions.items():
+ gather_vec[token_idx, max_valid_positions * i : max_valid_positions * i + len(valid_positions)] = (
+ valid_positions
+ )
+ for token_idx, possible_end_lens in end_lens.items():
+ gather_vec[
+ token_idx,
+ max_valid_positions * len(stop_strings) + max_valid_end_lens * i : max_valid_positions
+ * len(stop_strings)
+ + max_valid_end_lens * i
+ + len(possible_end_lens),
+ ] = possible_end_lens
+ for token, token_idx in zip(token_list, token_indices):
+ gather_vec[token_idx, -1] = len(token)
+
+ gather_vec = torch.tensor(gather_vec, dtype=torch.int32)
+
+ return gather_vec, max_valid_positions, max_valid_end_lens
+
+ @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.Tensor:
+ self.embedding_vec = self.embedding_vec.to(input_ids.device)
+ self.target_lens = self.target_lens.to(input_ids.device)
+ # The maximum length we need to consider is 1 token per character. Note that input_ids can also be
+ # *shorter* than the global max, and the code below should be ready for that
+ input_ids = input_ids[:, -self.maximum_token_len :]
+
+ # Flip input_ids because we're only matching strings at the end of the generated sequence
+ flipped_ids = torch.flip(input_ids, (1,))
+
+ # Clip out-of-vocab values to the dummy value at the end of the embedding vector
+ flipped_ids = torch.clamp(flipped_ids, max=self.embedding_vec.size(0) - 1)
+
+ # Size of the vector of positions a single token can match
+ max_valid_positions = self.max_valid_positions
+
+ # The embedding vec contains the valid positions, end_lengths and total lengths for each token
+ embedded = F.embedding(flipped_ids, self.embedding_vec)
+
+ # Now we split the embedding vector. valid_positions is the positions in the stop string the token can fit
+ valid_positions = embedded[:, 1:, : max_valid_positions * self.num_stop_strings].unflatten(
+ -1, (self.num_stop_strings, -1)
+ )
+ # end_lengths is the number of characters from the string, counting from the end, that the token
+ # contains. It can have multiple values if the same token can overlap different end lengths
+ end_lengths = embedded[:, :1, max_valid_positions * self.num_stop_strings : -1].unflatten(
+ -1, (self.num_stop_strings, -1)
+ )
+ # Lengths is the total length of each token. Unlike the others, it always has a single value
+ lengths = embedded[:, 1:, None, -1:] # Insert a dummy dimension for stop_strings even though lengths are const
+
+ # Concatenate lengths onto each possible end_lengths value
+ lengths = lengths.expand((-1, -1, end_lengths.shape[-2], end_lengths.shape[-1]))
+ lengths_with_ends = torch.cat([end_lengths, lengths], dim=1)
+
+ # cumsum() to get the number of matched characters in the stop string after each token
+ cumsum = lengths_with_ends.cumsum(dim=1) # B x maximum_token_len x num_stop_strings x max_valid_end_lens
+
+ # The calculation above assumes that all tokens are in valid positions. Now we mask the ones that are not.
+ # First, tokens match the start of the string if they have a positive value in the end_lengths vector
+ initial_match = end_lengths > 0
+
+ # Tokens continue the string if the cumsum() so far is one of the valid positions for that token
+ # Note that we're actually tracking one cumsum() for for each possible end_length
+ later_match = torch.any(cumsum[:, :-1, :, None] == valid_positions[:, :, :, :, None], axis=-2)
+
+ # The match vector is a boolean vector that indicates which positions have valid tokens
+ match = torch.cat([initial_match, later_match], dim=1)
+
+ # Once a single position does not match, all positions following that position are masked
+ mask = (~match).cumsum(dim=1, dtype=torch.int32)
+ mask = mask == 0
+
+ # The string is matched if we reached a cumsum equal to or greater than the length of the string
+ # before hitting the mask
+ string_matches = torch.amax(cumsum * mask, dim=(1, -1)) >= self.target_lens[None, :]
+
+ # We return a per-sample vector that is True if any stop string is matched for that sample
+ return torch.any(string_matches, dim=-1)
+
+
+class EosTokenCriteria(StoppingCriteria):
+ """
+ This class can be used to stop generation whenever the "end-of-sequence" token is generated.
+ By default, it uses the `model.generation_config.eos_token_id`.
+
+ Args:
+ eos_token_id (`Union[int, List[int], torch.Tensor]`):
+ The id(s) of the *end-of-sequence* token.
+ """
+
+ def __init__(self, eos_token_id: Union[int, List[int], torch.Tensor]):
+ if not isinstance(eos_token_id, torch.Tensor):
+ if isinstance(eos_token_id, int):
+ eos_token_id = [eos_token_id]
+ eos_token_id = torch.tensor(eos_token_id)
+ self.eos_token_id = eos_token_id
+
+ @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.BoolTensor:
+ self.eos_token_id = self.eos_token_id.to(input_ids.device)
+ is_done = isin_mps_friendly(input_ids[:, -1], self.eos_token_id)
+ return is_done
+
+
+class ConfidenceCriteria(StoppingCriteria):
+ """
+ This class can be used to stop generation whenever assistant model's confidence in its prediction for the current token is lower than the threshold
+ `model.generation_config.assistant_confidence_threshold` even if the number of speculative tokens (defined by `num_assistant_tokens`) is not yet reached.
+
+ Args:
+ assistant_confidence_threshold (`float`):
+ The value of the threshold.
+ """
+
+ def __init__(self, assistant_confidence_threshold):
+ self.assistant_confidence_threshold = assistant_confidence_threshold
+
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.BoolTensor:
+ probs = scores[-1].softmax(-1)
+ p = probs[0, input_ids[0, -1]].item()
+ if p < self.assistant_confidence_threshold:
+ return True
+ return False
+
+
+class StoppingCriteriaList(list):
+ @add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.BoolTensor:
+ is_done = torch.full((input_ids.shape[0],), False, device=input_ids.device, dtype=torch.bool)
+ for criteria in self:
+ is_done = is_done | criteria(input_ids, scores, **kwargs)
+ return is_done
+
+ @property
+ def max_length(self) -> Optional[int]:
+ for stopping_criterium in self:
+ if isinstance(stopping_criterium, MaxLengthCriteria):
+ return stopping_criterium.max_length
+ return None
+
+
+def validate_stopping_criteria(stopping_criteria: StoppingCriteriaList, max_length: int) -> StoppingCriteriaList:
+ stopping_max_length = stopping_criteria.max_length
+ new_stopping_criteria = deepcopy(stopping_criteria)
+ if stopping_max_length is not None and stopping_max_length != max_length:
+ warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter", UserWarning)
+ elif stopping_max_length is None:
+ new_stopping_criteria.append(MaxLengthCriteria(max_length=max_length))
+ return new_stopping_criteria
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/streamers.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/streamers.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0fc26442b466fdaa09aa7c52e607a37dd0d78ab
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/streamers.py
@@ -0,0 +1,318 @@
+# coding=utf-8
+# Copyright 2023 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import asyncio
+from queue import Queue
+from typing import TYPE_CHECKING, Optional
+
+
+if TYPE_CHECKING:
+ from ..models.auto import AutoTokenizer
+
+
+class BaseStreamer:
+ """
+ Base class from which `.generate()` streamers should inherit.
+ """
+
+ def put(self, value):
+ """Function that is called by `.generate()` to push new tokens"""
+ raise NotImplementedError()
+
+ def end(self):
+ """Function that is called by `.generate()` to signal the end of generation"""
+ raise NotImplementedError()
+
+
+class TextStreamer(BaseStreamer):
+ """
+ Simple text streamer that prints the token(s) to stdout as soon as entire words are formed.
+
+
+
+ The API for the streamer classes is still under development and may change in the future.
+
+
+
+ Parameters:
+ tokenizer (`AutoTokenizer`):
+ The tokenized used to decode the tokens.
+ skip_prompt (`bool`, *optional*, defaults to `False`):
+ Whether to skip the prompt to `.generate()` or not. Useful e.g. for chatbots.
+ decode_kwargs (`dict`, *optional*):
+ Additional keyword arguments to pass to the tokenizer's `decode` method.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer
+
+ >>> tok = AutoTokenizer.from_pretrained("openai-community/gpt2")
+ >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
+ >>> inputs = tok(["An increasing sequence: one,"], return_tensors="pt")
+ >>> streamer = TextStreamer(tok)
+
+ >>> # Despite returning the usual output, the streamer will also print the generated text to stdout.
+ >>> _ = model.generate(**inputs, streamer=streamer, max_new_tokens=20)
+ An increasing sequence: one, two, three, four, five, six, seven, eight, nine, ten, eleven,
+ ```
+ """
+
+ def __init__(self, tokenizer: "AutoTokenizer", skip_prompt: bool = False, **decode_kwargs):
+ self.tokenizer = tokenizer
+ self.skip_prompt = skip_prompt
+ self.decode_kwargs = decode_kwargs
+
+ # variables used in the streaming process
+ self.token_cache = []
+ self.print_len = 0
+ self.next_tokens_are_prompt = True
+
+ def put(self, value):
+ """
+ Receives tokens, decodes them, and prints them to stdout as soon as they form entire words.
+ """
+ if len(value.shape) > 1 and value.shape[0] > 1:
+ raise ValueError("TextStreamer only supports batch size 1")
+ elif len(value.shape) > 1:
+ value = value[0]
+
+ if self.skip_prompt and self.next_tokens_are_prompt:
+ self.next_tokens_are_prompt = False
+ return
+
+ # Add the new token to the cache and decodes the entire thing.
+ self.token_cache.extend(value.tolist())
+ text = self.tokenizer.decode(self.token_cache, **self.decode_kwargs)
+
+ # After the symbol for a new line, we flush the cache.
+ if text.endswith("\n"):
+ printable_text = text[self.print_len :]
+ self.token_cache = []
+ self.print_len = 0
+ # If the last token is a CJK character, we print the characters.
+ elif len(text) > 0 and self._is_chinese_char(ord(text[-1])):
+ printable_text = text[self.print_len :]
+ self.print_len += len(printable_text)
+ # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words,
+ # which may change with the subsequent token -- there are probably smarter ways to do this!)
+ else:
+ printable_text = text[self.print_len : text.rfind(" ") + 1]
+ self.print_len += len(printable_text)
+
+ self.on_finalized_text(printable_text)
+
+ def end(self):
+ """Flushes any remaining cache and prints a newline to stdout."""
+ # Flush the cache, if it exists
+ if len(self.token_cache) > 0:
+ text = self.tokenizer.decode(self.token_cache, **self.decode_kwargs)
+ printable_text = text[self.print_len :]
+ self.token_cache = []
+ self.print_len = 0
+ else:
+ printable_text = ""
+
+ self.next_tokens_are_prompt = True
+ self.on_finalized_text(printable_text, stream_end=True)
+
+ def on_finalized_text(self, text: str, stream_end: bool = False):
+ """Prints the new text to stdout. If the stream is ending, also prints a newline."""
+ print(text, flush=True, end="" if not stream_end else None)
+
+ def _is_chinese_char(self, cp):
+ """Checks whether CP is the codepoint of a CJK character."""
+ # This defines a "chinese character" as anything in the CJK Unicode block:
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
+ #
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
+ # despite its name. The modern Korean Hangul alphabet is a different block,
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
+ # space-separated words, so they are not treated specially and handled
+ # like the all of the other languages.
+ if (
+ (cp >= 0x4E00 and cp <= 0x9FFF)
+ or (cp >= 0x3400 and cp <= 0x4DBF) #
+ or (cp >= 0x20000 and cp <= 0x2A6DF) #
+ or (cp >= 0x2A700 and cp <= 0x2B73F) #
+ or (cp >= 0x2B740 and cp <= 0x2B81F) #
+ or (cp >= 0x2B820 and cp <= 0x2CEAF) #
+ or (cp >= 0xF900 and cp <= 0xFAFF)
+ or (cp >= 0x2F800 and cp <= 0x2FA1F) #
+ ): #
+ return True
+
+ return False
+
+
+class TextIteratorStreamer(TextStreamer):
+ """
+ Streamer that stores print-ready text in a queue, to be used by a downstream application as an iterator. This is
+ useful for applications that benefit from acessing the generated text in a non-blocking way (e.g. in an interactive
+ Gradio demo).
+
+
+
+ The API for the streamer classes is still under development and may change in the future.
+
+
+
+ Parameters:
+ tokenizer (`AutoTokenizer`):
+ The tokenized used to decode the tokens.
+ skip_prompt (`bool`, *optional*, defaults to `False`):
+ Whether to skip the prompt to `.generate()` or not. Useful e.g. for chatbots.
+ timeout (`float`, *optional*):
+ The timeout for the text queue. If `None`, the queue will block indefinitely. Useful to handle exceptions
+ in `.generate()`, when it is called in a separate thread.
+ decode_kwargs (`dict`, *optional*):
+ Additional keyword arguments to pass to the tokenizer's `decode` method.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
+ >>> from threading import Thread
+
+ >>> tok = AutoTokenizer.from_pretrained("openai-community/gpt2")
+ >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
+ >>> inputs = tok(["An increasing sequence: one,"], return_tensors="pt")
+ >>> streamer = TextIteratorStreamer(tok)
+
+ >>> # Run the generation in a separate thread, so that we can fetch the generated text in a non-blocking way.
+ >>> generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=20)
+ >>> thread = Thread(target=model.generate, kwargs=generation_kwargs)
+ >>> thread.start()
+ >>> generated_text = ""
+ >>> for new_text in streamer:
+ ... generated_text += new_text
+ >>> generated_text
+ 'An increasing sequence: one, two, three, four, five, six, seven, eight, nine, ten, eleven,'
+ ```
+ """
+
+ def __init__(
+ self, tokenizer: "AutoTokenizer", skip_prompt: bool = False, timeout: Optional[float] = None, **decode_kwargs
+ ):
+ super().__init__(tokenizer, skip_prompt, **decode_kwargs)
+ self.text_queue = Queue()
+ self.stop_signal = None
+ self.timeout = timeout
+
+ def on_finalized_text(self, text: str, stream_end: bool = False):
+ """Put the new text in the queue. If the stream is ending, also put a stop signal in the queue."""
+ self.text_queue.put(text, timeout=self.timeout)
+ if stream_end:
+ self.text_queue.put(self.stop_signal, timeout=self.timeout)
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ value = self.text_queue.get(timeout=self.timeout)
+ if value == self.stop_signal:
+ raise StopIteration()
+ else:
+ return value
+
+
+class AsyncTextIteratorStreamer(TextStreamer):
+ """
+ Streamer that stores print-ready text in a queue, to be used by a downstream application as an async iterator.
+ This is useful for applications that benefit from acessing the generated text asynchronously (e.g. in an
+ interactive Gradio demo).
+
+
+
+ The API for the streamer classes is still under development and may change in the future.
+
+
+
+ Parameters:
+ tokenizer (`AutoTokenizer`):
+ The tokenized used to decode the tokens.
+ skip_prompt (`bool`, *optional*, defaults to `False`):
+ Whether to skip the prompt to `.generate()` or not. Useful e.g. for chatbots.
+ timeout (`float`, *optional*):
+ The timeout for the text queue. If `None`, the queue will block indefinitely. Useful to handle exceptions
+ in `.generate()`, when it is called in a separate thread.
+ decode_kwargs (`dict`, *optional*):
+ Additional keyword arguments to pass to the tokenizer's `decode` method.
+
+ Raises:
+ TimeoutError: If token generation time exceeds timeout value.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoModelForCausalLM, AutoTokenizer, AsyncTextIteratorStreamer
+ >>> from threading import Thread
+ >>> import asyncio
+
+ >>> tok = AutoTokenizer.from_pretrained("openai-community/gpt2")
+ >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
+ >>> inputs = tok(["An increasing sequence: one,"], return_tensors="pt")
+
+ >>> # Run the generation in a separate thread, so that we can fetch the generated text in a non-blocking way.
+ >>> async def main():
+ ... # Important: AsyncTextIteratorStreamer must be initialized inside a coroutine!
+ ... streamer = AsyncTextIteratorStreamer(tok)
+ ... generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=20)
+ ... thread = Thread(target=model.generate, kwargs=generation_kwargs)
+ ... thread.start()
+ ... generated_text = ""
+ ... async for new_text in streamer:
+ ... generated_text += new_text
+ >>> print(generated_text)
+ >>> asyncio.run(main())
+ An increasing sequence: one, two, three, four, five, six, seven, eight, nine, ten, eleven,
+ ```
+ """
+
+ def __init__(
+ self, tokenizer: "AutoTokenizer", skip_prompt: bool = False, timeout: Optional[float] = None, **decode_kwargs
+ ):
+ super().__init__(tokenizer, skip_prompt, **decode_kwargs)
+ self.text_queue = asyncio.Queue()
+ self.stop_signal = None
+ self.timeout = timeout
+ self.loop = asyncio.get_running_loop()
+ self.has_asyncio_timeout = hasattr(asyncio, "timeout")
+
+ def on_finalized_text(self, text: str, stream_end: bool = False):
+ """Put the new text in the queue. If the stream is ending, also put a stop signal in the queue."""
+ self.loop.call_soon_threadsafe(self.text_queue.put_nowait, text)
+ if stream_end:
+ self.loop.call_soon_threadsafe(self.text_queue.put_nowait, self.stop_signal)
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ try:
+ if self.has_asyncio_timeout:
+ async with asyncio.timeout(self.timeout):
+ value = await self.text_queue.get()
+ else:
+ value = await asyncio.wait_for(self.text_queue.get(), timeout=self.timeout)
+ except asyncio.TimeoutError:
+ raise TimeoutError()
+ else:
+ if value == self.stop_signal:
+ raise StopAsyncIteration()
+ else:
+ return value
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/tf_logits_process.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/tf_logits_process.py
new file mode 100644
index 0000000000000000000000000000000000000000..f70655fb7c1d0b502dfc8f1c4f2c491867aa7e8c
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/tf_logits_process.py
@@ -0,0 +1,603 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import inspect
+from typing import List, Tuple
+
+import numpy as np
+import tensorflow as tf
+
+from ..tf_utils import stable_softmax
+from ..utils import add_start_docstrings
+from ..utils.logging import get_logger
+
+
+logger = get_logger(__name__)
+
+
+TF_LOGITS_PROCESSOR_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ scores (`tf.Tensor` of shape `(batch_size, config.vocab_size)`):
+ Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam
+ search or log softmax for each vocabulary token when using beam search.
+ cur_len (`int`):
+ The current length of valid input sequence tokens. In the TF implementation, the input_ids' sequence length
+ is the maximum length generate can produce, and we need to know which of its tokens are valid.
+ kwargs (`Dict[str, Any]`, *optional*):
+ Additional logits processor specific kwargs.
+
+ Return:
+ `tf.Tensor` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.
+"""
+
+
+class TFLogitsProcessor:
+ """Abstract base class for all logit processors that can be applied during generation."""
+
+ @add_start_docstrings(TF_LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
+ """TF method for processing logits."""
+ raise NotImplementedError(
+ f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
+ )
+
+
+class TFLogitsWarper:
+ """Abstract base class for all logit warpers that can be applied during generation with multinomial sampling."""
+
+ @add_start_docstrings(TF_LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
+ """TF method for warping logits."""
+ raise NotImplementedError(
+ f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
+ )
+
+
+class TFLogitsProcessorList(list):
+ """
+ This class can be used to create a list of [`TFLogitsProcessor`] to subsequently process a `scores` input tensor.
+ This class inherits from list and adds a specific *__call__* method to apply each [`TFLogitsProcessor`] to the
+ inputs.
+ """
+
+ @add_start_docstrings(TF_LOGITS_PROCESSOR_INPUTS_DOCSTRING)
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int, **kwargs) -> tf.Tensor:
+ for processor in self:
+ function_args = inspect.signature(processor.__call__).parameters
+ if len(function_args) > 3:
+ if not all(arg in kwargs for arg in list(function_args.keys())[2:]):
+ raise ValueError(
+ f"Make sure that all the required parameters: {list(function_args.keys())} for "
+ f"{processor.__class__} are passed to the logits processor."
+ )
+ scores = processor(input_ids, scores, cur_len, **kwargs)
+ else:
+ scores = processor(input_ids, scores, cur_len)
+ return scores
+
+
+class TFTemperatureLogitsWarper(TFLogitsWarper):
+ r"""
+ [`TFLogitsWarper`] for temperature (exponential scaling output probability distribution).
+
+ Args:
+ temperature (`float`):
+ The value used to module the logits distribution.
+ """
+
+ def __init__(self, temperature: float):
+ if not isinstance(temperature, float) or not (temperature > 0):
+ raise ValueError(f"`temperature` has to be a strictly positive float, but is {temperature}")
+
+ self.temperature = temperature
+
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
+ scores = scores / self.temperature
+ return scores
+
+
+class TFTopKLogitsWarper(TFLogitsWarper):
+ r"""
+ [`TFLogitsWarper`] that performs top-k, i.e. restricting to the k highest probability elements.
+
+ Args:
+ top_k (`int`):
+ The number of highest probability vocabulary tokens to keep for top-k-filtering.
+ filter_value (`float`, *optional*, defaults to -inf):
+ All filtered values will be set to this float value.
+ min_tokens_to_keep (`int`, *optional*, defaults to 1):
+ Minimum number of tokens that cannot be filtered.
+ """
+
+ def __init__(self, top_k: int, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
+ if not isinstance(top_k, int) or top_k <= 0:
+ raise ValueError(f"`top_k` has to be a strictly positive integer, but is {top_k}")
+
+ self.top_k = max(top_k, min_tokens_to_keep)
+ self.filter_value = filter_value
+
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
+ top_k = min(self.top_k, scores.shape[-1]) # Safety check
+ # Boolean mask containing all tokens with a probability less than the last token of the top-k
+ indices_to_remove = scores < tf.math.top_k(scores, k=top_k)[0][..., -1:]
+ next_scores = tf.where(indices_to_remove, self.filter_value, scores)
+ return next_scores
+
+
+class TFTopPLogitsWarper(TFLogitsWarper):
+ """
+ [`TFLogitsWarper`] that performs top-p, i.e. restricting to top tokens summing to <= prob_cut_off.
+
+ Args:
+ top_p (`float`):
+ If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or
+ higher are kept for generation.
+ filter_value (`float`, *optional*, defaults to -inf):
+ All filtered values will be set to this float value.
+ min_tokens_to_keep (`int`, *optional*, defaults to 1):
+ Minimum number of tokens that cannot be filtered.
+ """
+
+ def __init__(self, top_p: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
+ if not isinstance(top_p, float) or (top_p < 0 or top_p > 1.0):
+ raise ValueError(f"`top_p` has to be a float > 0 and < 1, but is {top_p}")
+ if not isinstance(min_tokens_to_keep, int) or (min_tokens_to_keep < 1):
+ raise ValueError(f"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}")
+
+ self.top_p = top_p
+ self.filter_value = filter_value
+ self.min_tokens_to_keep = min_tokens_to_keep
+
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
+ topk_scores, topk_indices = tf.math.top_k(scores, scores.shape[-1])
+
+ mask_scores = tf.fill(scores.shape, self.filter_value)
+ cumulative_probs = tf.math.cumsum(stable_softmax(topk_scores, axis=-1), axis=-1)
+ score_mask = cumulative_probs < self.top_p
+
+ # Also include the token that is higher than top_p (the first false = shift and insert a True on the left)
+ score_mask = tf.concat((tf.ones([score_mask.shape[0], 1], dtype=tf.bool), score_mask[:, :-1]), axis=-1)
+
+ # Ensure min tokens to keep
+ score_mask = tf.concat(
+ (
+ tf.ones([score_mask.shape[0], self.min_tokens_to_keep], dtype=tf.bool),
+ score_mask[:, self.min_tokens_to_keep :],
+ ),
+ axis=-1,
+ )
+
+ # Mask the values that do not fit the criteria
+ topk_next_scores = tf.where(score_mask, topk_scores, mask_scores)
+
+ # Undo the topk sorting: converts the 2D matrix of per-row original indices of shape (batch_size, vocab_size)
+ # to a 3D tensor of shape (batch_size, vocab_size, 2) containing the original score coordinate, from which we
+ # can scatter (i.e. `scatter_indices[row, col, :]` is a tensor containing `[row, topk_indices[row, col]]`)
+ scatter_rows = tf.tile(tf.expand_dims(tf.range(topk_indices.shape[0]), axis=-1), [1, topk_indices.shape[-1]])
+ scatter_indices = tf.stack((scatter_rows, topk_indices), axis=-1)
+ next_scores = tf.scatter_nd(scatter_indices, topk_next_scores, shape=topk_next_scores.shape)
+
+ return next_scores
+
+
+class TFMinLengthLogitsProcessor(TFLogitsProcessor):
+ r"""
+ [`TFLogitsProcessor`] enforcing a min-length by setting EOS probability to 0.
+
+ Args:
+ min_length (`int`):
+ The minimum length below which the score of `eos_token_id` is set to `-float("Inf")`.
+ eos_token_id (`int`):
+ The id of the *end-of-sequence* token.
+ """
+
+ def __init__(self, min_length: int, eos_token_id: int):
+ if not isinstance(min_length, int) or min_length < 0:
+ raise ValueError(f"`min_length` has to be a positive integer, but is {min_length}")
+
+ if not isinstance(eos_token_id, int) or eos_token_id < 0:
+ raise ValueError(f"`eos_token_id` has to be a positive integer, but is {eos_token_id}")
+
+ self.min_length = min_length
+ self.eos_token_id = eos_token_id
+
+ def _apply_eos_token_mask(self, scores: tf.Tensor) -> tf.Tensor:
+ eos_token_id_mask = tf.range(scores.shape[-1]) == self.eos_token_id
+ scores = tf.where(eos_token_id_mask, float("-inf"), scores)
+ return scores
+
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
+ # applies eos token masking if the first argument is true
+ scores = tf.cond(
+ tf.less(cur_len, self.min_length),
+ lambda: self._apply_eos_token_mask(scores),
+ lambda: tf.identity(scores),
+ )
+ return scores
+
+
+class TFRepetitionPenaltyLogitsProcessor(TFLogitsProcessor):
+ r"""
+ [`TFLogitsProcessor`] enforcing an exponential penalty on repeated sequences.
+
+ Args:
+ repetition_penalty (`float`):
+ The parameter for repetition penalty. 1.0 means no penalty. See [this
+ paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
+ """
+
+ def __init__(self, penalty: float):
+ if not isinstance(penalty, float) or not (penalty > 0):
+ raise ValueError(f"`penalty` has to be a strictly positive float, but is {penalty}")
+
+ self.penalty = penalty
+
+ def _create_score_penalties(self, input_ids: tf.Tensor, logits: tf.Tensor) -> tf.Tensor:
+ # We want to populate the penalties in the positions of `input_ids`. Since XLA can't handle shapes unknown
+ # before runtime, `tf.unique` can't be used. Therefore, we may have redundant updates, when a given row has
+ # the same token multiple times.
+
+ # Gathers the penalties to apply
+ logit_penalties = tf.gather(logits, input_ids, axis=1, batch_dims=1)
+ logit_penalties = tf.where(logit_penalties > 0, 1 / self.penalty, logit_penalties)
+ logit_penalties = tf.where(logit_penalties < 0, self.penalty, logit_penalties)
+
+ # Scatters the penalties
+ token_penalties = tf.ones(logits.shape)
+ batch_size = input_ids.shape[0]
+ seq_len = tf.shape(input_ids)[1] # the sequence length has dynamic size, hence the dynamic shape
+ indexable_prev_input_ids = tf.concat(
+ (
+ tf.expand_dims(tf.repeat(tf.range(batch_size), seq_len), axis=-1),
+ tf.expand_dims(tf.reshape(input_ids, [-1]), axis=-1),
+ ),
+ axis=1,
+ )
+ token_penalties = tf.tensor_scatter_nd_update(
+ token_penalties, indices=indexable_prev_input_ids, updates=tf.reshape(logit_penalties, [-1])
+ )
+ return token_penalties
+
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
+ score_penalties = self._create_score_penalties(input_ids[:, :cur_len], scores)
+
+ scores = tf.math.multiply(scores, score_penalties)
+
+ return scores
+
+
+class TFNoBadWordsLogitsProcessor(TFLogitsProcessor):
+ """
+ [`TFLogitsProcessor`] that enforces that specified sequences will never be sampled.
+
+ Args:
+ bad_words_ids (`List[List[int]]`):
+ List of list of token ids that are not allowed to be generated. In order to get the tokens of the words
+ that should not appear in the generated text, make sure to set `add_prefix_space=True` when initializing
+ the tokenizer, and use `tokenizer(bad_words, add_special_tokens=False).input_ids`. The `add_prefix_space`
+ argument is only supported for some slow tokenizers, as fast tokenizers' prefixing behaviours come from
+ `pre tokenizers`. Read more [here](https://huggingface.co/docs/tokenizers/api/pre-tokenizers).
+ eos_token_id (`int`):
+ The id of the *end-of-sequence* token.
+ """
+
+ def __init__(self, bad_words_ids: List[List[int]], eos_token_id: int):
+ if not isinstance(bad_words_ids, List) or len(bad_words_ids) == 0:
+ raise ValueError(f"`bad_words_ids` has to be a non-empty list, but is {bad_words_ids}.")
+ if any(not isinstance(bad_word_ids, list) for bad_word_ids in bad_words_ids):
+ raise ValueError(f"`bad_words_ids` has to be a list of lists, but is {bad_words_ids}.")
+ if any(
+ any((not isinstance(token_id, (int, np.integer)) or token_id < 0) for token_id in bad_word_ids)
+ for bad_word_ids in bad_words_ids
+ ):
+ raise ValueError(
+ f"Each list in `bad_words_ids` has to be a list of positive integers, but is {bad_words_ids}."
+ )
+
+ # stores the information about bad words in three tensors:
+ # 1. a rectangular tensor with the forbidden sequences (padded with `-1`), for full data comparisons
+ self.bad_word_seqs_ids = tf.ragged.constant(bad_words_ids).to_tensor(default_value=-1)
+ # 2. a tensor with the unpadded length of each forbidden sequence, for quick length comparisons
+ bad_word_seqs_len = [len(bad_words) for bad_words in bad_words_ids]
+ if any(word_len == 0 for word_len in bad_word_seqs_len):
+ raise ValueError(f"Banned words token sequences {bad_words_ids} cannot have an empty list")
+ self.bad_word_seqs_len = tf.convert_to_tensor(bad_word_seqs_len, dtype=tf.int32)
+ # 3. a tensor containing the last token for each sequence, for easy access to the tokens that may be banned
+ self.seq_forbidden_tokens = tf.convert_to_tensor([bad_words[-1] for bad_words in bad_words_ids])
+
+ def _calc_row_banned_bad_tokens(self, row_input_ids: tf.Tensor) -> tf.Tensor:
+ def _tokens_match(bad_word_seq_number):
+ def _len_one():
+ # If the bad sequence only has one token, always mask it
+ return tf.cond(
+ tf.math.equal(self.bad_word_seqs_len[bad_word_seq_number], 1),
+ lambda: tf.ones((), dtype=tf.bool),
+ _len_greater_than_cur_len,
+ )
+
+ def _len_greater_than_cur_len():
+ # Otherwise, if the bad sequence is longer than the current length they can't ever match
+ return tf.cond(
+ tf.math.greater(self.bad_word_seqs_len[bad_word_seq_number], tf.shape(row_input_ids)[0]),
+ lambda: tf.zeros((), dtype=tf.bool),
+ _match_found,
+ )
+
+ def _match_found():
+ # Finaly, runs the actual comparison. Can only be called if the previous comparisons do not yield
+ # an answer (otherwise we get indexing exceptions)
+ compare_len = self.bad_word_seqs_len[bad_word_seq_number] - 1
+ return tf.cond(
+ tf.math.reduce_all(
+ tf.math.equal(
+ row_input_ids[-compare_len:], self.bad_word_seqs_ids[bad_word_seq_number, :compare_len]
+ )
+ ),
+ lambda: tf.ones((), dtype=tf.bool),
+ lambda: tf.zeros((), dtype=tf.bool),
+ )
+
+ match = _len_one()
+ return match
+
+ # Compares the current row against all bad word sequences, obtaining a mask with the matches.
+ match_mask = tf.map_fn(_tokens_match, tf.range(self.bad_word_seqs_ids.shape[0]), fn_output_signature=tf.bool)
+ row_banned_tokens = self.seq_forbidden_tokens[match_mask]
+ return row_banned_tokens
+
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
+ # We want to mask some banned tokens, at a score level. Since the banned tokens depend on the previous
+ # `input_ids`, they may have a different length for each row, and they may even be empty for some rows.
+ # To remain simple and XLA-compatible, we work on a per-row fashion.
+ # TODO (Joao): this function might trigger XLA retracing as `cur_len` increases. Fix it if it becomes
+ # a frequent choke point. (make `cur_len` a tensor?)
+ def _get_row_updated_score(row_inputs: Tuple[tf.Tensor]) -> tf.Tensor:
+ row_input_ids, row_score = row_inputs
+ banned_tokens = self._calc_row_banned_bad_tokens(row_input_ids[:cur_len])
+ banned_tokens_mask = tf.scatter_nd(
+ indices=tf.expand_dims(banned_tokens, axis=-1),
+ updates=tf.ones_like(banned_tokens, dtype=tf.bool),
+ shape=row_score.shape,
+ )
+ row_score = tf.where(banned_tokens_mask, -float("inf"), row_score)
+ return row_score
+
+ scores = tf.map_fn(_get_row_updated_score, (input_ids, scores), fn_output_signature=tf.float32)
+ return scores
+
+
+class TFNoRepeatNGramLogitsProcessor(TFLogitsProcessor):
+ r"""
+ [`TFLogitsProcessor`] that enforces no repetition of n-grams. See
+ [Fairseq](https://github.com/pytorch/fairseq/blob/a07cb6f40480928c9e0548b737aadd36ee66ac76/fairseq/sequence_generator.py#L345).
+
+ Args:
+ ngram_size (`int`):
+ All ngrams of size `ngram_size` can only occur once.
+ """
+
+ def __init__(self, ngram_size: int):
+ if not isinstance(ngram_size, int) or ngram_size <= 0:
+ raise ValueError(f"`ngram_size` has to be a strictly positive integer, but is {ngram_size}")
+ self.ngram_size = ngram_size
+
+ def calc_banned_ngram_tokens(self, input_ids, num_hypos, cur_len):
+ # Copied from fairseq for no_repeat_ngram in beam_search
+ if cur_len + 1 < self.ngram_size:
+ # return no banned tokens if we haven't generated ngram_size tokens yet
+ return [[] for _ in range(num_hypos)]
+ generated_ngrams = [{} for _ in range(num_hypos)]
+ prev_input_ids = input_ids[:, :cur_len]
+ for idx in range(num_hypos):
+ gen_tokens = prev_input_ids[idx].numpy().tolist()
+ generated_ngram = generated_ngrams[idx]
+ for ngram in zip(*[gen_tokens[i:] for i in range(self.ngram_size)]):
+ prev_ngram_tuple = tuple(ngram[:-1])
+ generated_ngram[prev_ngram_tuple] = generated_ngram.get(prev_ngram_tuple, []) + [ngram[-1]]
+
+ def _get_generated_ngrams(hypo_idx):
+ # Before decoding the next token, prevent decoding of ngrams that have already appeared
+ start_idx = cur_len + 1 - self.ngram_size
+ ngram_idx = tuple(prev_input_ids[hypo_idx, start_idx:cur_len].numpy().tolist())
+ return generated_ngrams[hypo_idx].get(ngram_idx, [])
+
+ banned_tokens = [_get_generated_ngrams(hypo_idx) for hypo_idx in range(num_hypos)]
+
+ return banned_tokens
+
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
+ # TODO (joao): enable XLA on this logits processor. See discussion and attempts in
+ # https://github.com/huggingface/transformers/pull/16974
+ if not tf.executing_eagerly():
+ raise NotImplementedError("TFNoRepeatNGramLogitsProcessor is only implemented for eager execution.")
+
+ batch_size, vocab_size = scores.shape
+ banned_tokens = self.calc_banned_ngram_tokens(input_ids, batch_size, cur_len)
+
+ # create banned_tokens boolean mask
+ banned_tokens_indices_mask = []
+ for banned_tokens_slice in banned_tokens:
+ banned_tokens_indices_mask.append(
+ [True if token in banned_tokens_slice else False for token in range(vocab_size)]
+ )
+
+ scores = tf.where(tf.convert_to_tensor(banned_tokens_indices_mask, dtype=tf.bool), -float("inf"), scores)
+
+ return scores
+
+
+class TFForcedBOSTokenLogitsProcessor(TFLogitsProcessor):
+ r"""
+ [`TFLogitsProcessor`] that enforces the specified token as the first generated token.
+
+ Args:
+ bos_token_id (`int`):
+ The id of the token to force as the first generated token.
+ """
+
+ def __init__(self, bos_token_id: int):
+ if bos_token_id < 0:
+ raise ValueError(f"The forced bos token id must be a non-negative integer, got {bos_token_id}")
+ self.bos_token_id = bos_token_id
+
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
+ if cur_len == 1:
+ batch_size, num_tokens = scores.shape
+ # sets the score to 0 in the bos_token_id column
+ scores = tf.zeros((batch_size, 1))
+ # sets the score to -inf everywhere else
+ if self.bos_token_id > 0:
+ scores = tf.concat((tf.broadcast_to(-float("inf"), (batch_size, self.bos_token_id)), scores), axis=-1)
+ if self.bos_token_id < (num_tokens - 1):
+ scores = tf.concat(
+ (scores, tf.broadcast_to(-float("inf"), (batch_size, (num_tokens - 1) - self.bos_token_id))),
+ axis=-1,
+ )
+ return scores
+
+
+class TFForcedEOSTokenLogitsProcessor(TFLogitsProcessor):
+ r"""
+ [`TFLogitsProcessor`] that enforces the specified token as the last generated token when `max_length` is reached.
+
+ Args:
+ max_length (`int`):
+ The maximum length of the sequence to be generated.
+ eos_token_id (`int`):
+ The id of the token to force as the last generated token when `max_length` is reached.
+ """
+
+ def __init__(self, max_length: int, eos_token_id: int):
+ self.max_length = max_length
+ if eos_token_id < 0:
+ raise ValueError(f"The forced eos token id must be a non-negative integer, got {eos_token_id}")
+ self.eos_token_id = eos_token_id
+
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
+ if cur_len == self.max_length - 1:
+ batch_size, num_tokens = scores.shape
+ # sets the score to 0 in the eos_token_id column
+ scores = tf.zeros((batch_size, 1))
+ # sets the score to -inf everywhere else
+ if self.eos_token_id > 0:
+ scores = tf.concat((tf.broadcast_to(-float("inf"), (batch_size, self.eos_token_id)), scores), axis=-1)
+ if self.eos_token_id < (num_tokens - 1):
+ scores = tf.concat(
+ (scores, tf.broadcast_to(-float("inf"), (batch_size, (num_tokens - 1) - self.eos_token_id))),
+ axis=-1,
+ )
+ return scores
+
+
+class TFSuppressTokensAtBeginLogitsProcessor(TFLogitsProcessor):
+ r"""
+ [`TFSuppressTokensAtBeginLogitsProcessor`] suppresses a list of tokens as soon as the `generate` function starts
+ generating using `begin_index` tokens. This should ensure that the tokens defined by `begin_suppress_tokens` at not
+ sampled at the beginning of the generation.
+ """
+
+ def __init__(self, begin_suppress_tokens, begin_index):
+ self.begin_suppress_tokens = list(begin_suppress_tokens)
+ self.begin_index = begin_index
+
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
+ suppressed_indices = []
+ for token in self.begin_suppress_tokens:
+ if token < scores.shape[-1]: # to ensure we don't go beyond the vocab size
+ suppressed_indices.extend([[i, token] for i in range(scores.shape[0])])
+
+ if len(suppressed_indices) > 0:
+ scores = tf.cond(
+ tf.equal(cur_len, self.begin_index),
+ lambda: tf.tensor_scatter_nd_update(
+ scores,
+ indices=suppressed_indices,
+ updates=[-float("inf") for _ in range(scores.shape[0] * len(self.begin_suppress_tokens))],
+ ),
+ lambda: scores,
+ )
+ return scores
+
+
+class TFSuppressTokensLogitsProcessor(TFLogitsProcessor):
+ r"""This processor can be used to suppress a list of tokens. The processor will set their log probs to `-inf` so that they
+ are not sampled."""
+
+ def __init__(self, suppress_tokens):
+ self.suppress_tokens = list(suppress_tokens)
+
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
+ suppressed_indices = []
+ for token in self.suppress_tokens:
+ if token < scores.shape[-1]: # to ensure we don't go beyond the vocab size
+ suppressed_indices.extend([[i, token] for i in range(scores.shape[0])])
+
+ if len(suppressed_indices) > 0:
+ scores = tf.tensor_scatter_nd_update(
+ scores,
+ indices=[[i, token] for i in range(scores.shape[0]) for token in self.suppress_tokens],
+ updates=[-float("inf") for _ in range(scores.shape[0] * len(self.suppress_tokens))],
+ )
+ return scores
+
+
+class TFForceTokensLogitsProcessor(TFLogitsProcessor):
+ r"""This processor takes a list of pairs of integers which indicates a mapping from generation indices to token
+ indices that will be forced before sampling. The processor will set their log probs to `0` and all other tokens to
+ `-inf` so that they are sampled at their corresponding index."""
+
+ def __init__(self, force_token_map: List[List[int]]):
+ force_token_map = dict(force_token_map)
+ # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the
+ # index of the array corresponds to the index of the token to be forced, for XLA compatibility.
+ # Indexes without forced tokens will have an negative value.
+ force_token_array = np.ones((max(force_token_map.keys()) + 1), dtype=np.int32) * -1
+ for index, token in force_token_map.items():
+ if token is not None:
+ force_token_array[index] = token
+ self.force_token_array = tf.convert_to_tensor(force_token_array, dtype=tf.int32)
+
+ def __call__(self, input_ids: tf.Tensor, scores: tf.Tensor, cur_len: int) -> tf.Tensor:
+ def _force_token(generation_idx):
+ batch_size = scores.shape[0]
+ current_token = self.force_token_array[generation_idx]
+
+ new_scores = tf.zeros_like(scores, dtype=scores.dtype) + tf.constant([scores.dtype.min])
+ indices = tf.stack((tf.range(batch_size), tf.tile([current_token], [batch_size])), axis=1)
+ updates = tf.zeros((batch_size,), dtype=scores.dtype)
+ new_scores = tf.tensor_scatter_nd_update(new_scores, indices, updates)
+ return new_scores
+
+ scores = tf.cond(
+ tf.greater_equal(cur_len, tf.shape(self.force_token_array)[0]),
+ # If the current length is geq than the length of force_token_array, the processor does nothing.
+ lambda: tf.identity(scores),
+ # Otherwise, it may force a certain token.
+ lambda: tf.cond(
+ tf.greater_equal(self.force_token_array[cur_len], 0),
+ # Only valid (positive) tokens are forced
+ lambda: _force_token(cur_len),
+ # Otherwise, the processor does nothing.
+ lambda: scores,
+ ),
+ )
+ return scores
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/tf_utils.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/tf_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd1f819fe548aa589ac11c8d3e3ef3338d3d208c
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/tf_utils.py
@@ -0,0 +1,3130 @@
+# coding=utf-8
+# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. 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 inspect
+import warnings
+from dataclasses import dataclass
+from typing import Any, Dict, Optional, Tuple, Union
+
+import numpy as np
+import tensorflow as tf
+from tensorflow.compiler.tf2xla.python.xla import dynamic_update_slice
+
+from ..modeling_tf_outputs import TFCausalLMOutputWithPast, TFSeq2SeqLMOutput
+from ..models.auto import (
+ TF_MODEL_FOR_CAUSAL_LM_MAPPING,
+ TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
+ TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
+ TF_MODEL_FOR_VISION_2_SEQ_MAPPING,
+)
+from ..tf_utils import shape_list, stable_softmax
+from ..utils import ModelOutput, logging
+from .configuration_utils import GenerationConfig
+from .tf_logits_process import (
+ TFForcedBOSTokenLogitsProcessor,
+ TFForcedEOSTokenLogitsProcessor,
+ TFForceTokensLogitsProcessor,
+ TFLogitsProcessorList,
+ TFMinLengthLogitsProcessor,
+ TFNoBadWordsLogitsProcessor,
+ TFNoRepeatNGramLogitsProcessor,
+ TFRepetitionPenaltyLogitsProcessor,
+ TFSuppressTokensAtBeginLogitsProcessor,
+ TFSuppressTokensLogitsProcessor,
+ TFTemperatureLogitsWarper,
+ TFTopKLogitsWarper,
+ TFTopPLogitsWarper,
+)
+
+
+logger = logging.get_logger(__name__)
+
+
+@dataclass
+class TFGreedySearchDecoderOnlyOutput(ModelOutput):
+ """
+ Base class for outputs of decoder-only generation models using greedy search.
+
+
+ Args:
+ sequences (`tf.Tensor` of shape `(batch_size, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each
+ generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
+ attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
+ hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size, generated_length, hidden_size)`.
+ """
+
+ sequences: tf.Tensor = None
+ scores: Optional[Tuple[tf.Tensor]] = None
+ attentions: Optional[Tuple[Tuple[tf.Tensor]]] = None
+ hidden_states: Optional[Tuple[Tuple[tf.Tensor]]] = None
+
+
+@dataclass
+class TFGreedySearchEncoderDecoderOutput(ModelOutput):
+ """
+ Base class for outputs of encoder-decoder generation models using greedy search. Hidden states and attention
+ weights of the decoder (respectively the encoder) can be accessed via the encoder_attentions and the
+ encoder_hidden_states attributes (respectively the decoder_attentions and the decoder_hidden_states attributes)
+
+
+ Args:
+ sequences (`tf.Tensor` of shape `(batch_size, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each
+ generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
+ encoder_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple of `tf.Tensor` (one for each layer of the decoder) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+ encoder_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size, sequence_length, hidden_size)`.
+ decoder_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
+ cross_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
+ decoder_hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size, generated_length, hidden_size)`.
+ """
+
+ sequences: tf.Tensor = None
+ scores: Optional[Tuple[tf.Tensor]] = None
+ encoder_attentions: Optional[Tuple[tf.Tensor]] = None
+ encoder_hidden_states: Optional[Tuple[tf.Tensor]] = None
+ decoder_attentions: Optional[Tuple[Tuple[tf.Tensor]]] = None
+ cross_attentions: Optional[Tuple[Tuple[tf.Tensor]]] = None
+ decoder_hidden_states: Optional[Tuple[Tuple[tf.Tensor]]] = None
+
+
+@dataclass
+class TFSampleDecoderOnlyOutput(ModelOutput):
+ """
+ Base class for outputs of decoder-only generation models using sampling.
+
+
+ Args:
+ sequences (`tf.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each
+ generated token), with each tensor of shape `(batch_size*num_return_sequences, config.vocab_size)`.
+ attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(num_return_sequences*batch_size, num_heads, generated_length, sequence_length)`.
+ hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(num_return_sequences*batch_size, generated_length, hidden_size)`.
+ """
+
+ sequences: tf.Tensor = None
+ scores: Optional[Tuple[tf.Tensor]] = None
+ attentions: Optional[Tuple[Tuple[tf.Tensor]]] = None
+ hidden_states: Optional[Tuple[Tuple[tf.Tensor]]] = None
+
+
+@dataclass
+class TFSampleEncoderDecoderOutput(ModelOutput):
+ """
+ Base class for outputs of encoder-decoder generation models using sampling. Hidden states and attention weights of
+ the decoder (respectively the encoder) can be accessed via the encoder_attentions and the encoder_hidden_states
+ attributes (respectively the decoder_attentions and the decoder_hidden_states attributes)
+
+
+ Args:
+ sequences (`tf.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each
+ generated token), with each tensor of shape `(batch_size*num_return_sequences, config.vocab_size)`.
+ encoder_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple of `tf.Tensor` (one for each layer of the decoder) of shape `(batch_size*num_return_sequences,
+ num_heads, sequence_length, sequence_length)`.
+ encoder_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size*num_return_sequences, sequence_length, hidden_size)`.
+ decoder_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size*num_return_sequences, num_heads, generated_length, sequence_length)`.
+ cross_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
+ decoder_hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size*num_return_sequences, generated_length, hidden_size)`.
+ """
+
+ sequences: tf.Tensor = None
+ scores: Optional[Tuple[tf.Tensor]] = None
+ encoder_attentions: Optional[Tuple[tf.Tensor]] = None
+ encoder_hidden_states: Optional[Tuple[tf.Tensor]] = None
+ decoder_attentions: Optional[Tuple[Tuple[tf.Tensor]]] = None
+ cross_attentions: Optional[Tuple[Tuple[tf.Tensor]]] = None
+ decoder_hidden_states: Optional[Tuple[Tuple[tf.Tensor]]] = None
+
+
+@dataclass
+class TFBeamSearchDecoderOnlyOutput(ModelOutput):
+ """
+ Base class for outputs of decoder-only generation models using beam search.
+
+ Args:
+ sequences (`tf.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ sequences_scores (`tf.Tensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Final beam scores of the generated `sequences`.
+ scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Processed beam scores for each vocabulary token at each generation step. Beam scores consisting of log
+ softmax scores for each vocabulary token and sum of log softmax of previously generated tokens in this
+ beam. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each generated token),
+ with each tensor of shape `(batch_size*num_beams*num_return_sequences, config.vocab_size)`.
+ beam_indices (`tf.Tensor`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Beam indices of generated token id at each generation step. `tf.Tensor` of shape
+ `(batch_size*num_return_sequences, sequence_length)`.
+ attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size*num_beams, num_heads, generated_length, sequence_length)`.
+ hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.
+ """
+
+ sequences: tf.Tensor = None
+ sequences_scores: Optional[tf.Tensor] = None
+ scores: Optional[Tuple[tf.Tensor]] = None
+ beam_indices: Optional[tf.Tensor] = None
+ attentions: Optional[Tuple[Tuple[tf.Tensor]]] = None
+ hidden_states: Optional[Tuple[Tuple[tf.Tensor]]] = None
+
+
+@dataclass
+class TFBeamSearchEncoderDecoderOutput(ModelOutput):
+ """
+ Base class for outputs of encoder-decoder generation models using beam search. Hidden states and attention weights
+ of the decoder (respectively the encoder) can be accessed via the encoder_attentions and the encoder_hidden_states
+ attributes (respectively the decoder_attentions and the decoder_hidden_states attributes)
+
+ Args:
+ sequences (`tf.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ sequences_scores (`tf.Tensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Final beam scores of the generated `sequences`.
+ scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Processed beam scores for each vocabulary token at each generation step. Beam scores consisting of log
+ softmax scores for each vocabulary token and sum of log softmax of previously generated tokens in this
+ beam. `Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each generated token),
+ with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
+ beam_indices (`tf.Tensor`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Beam indices of generated token id at each generation step. `tf.Tensor` of shape
+ `(batch_size*num_return_sequences, sequence_length)`.
+ encoder_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple of `tf.Tensor` (one for each layer of the decoder) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+ encoder_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size*num_beams*num_return_sequences, sequence_length, hidden_size)`.
+ decoder_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size*num_beams*num_return_sequences, num_heads, generated_length,
+ sequence_length)`.
+ cross_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
+ decoder_hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.
+ """
+
+ sequences: tf.Tensor = None
+ sequences_scores: Optional[tf.Tensor] = None
+ scores: Optional[Tuple[tf.Tensor]] = None
+ beam_indices: Optional[tf.Tensor] = None
+ encoder_attentions: Optional[Tuple[tf.Tensor]] = None
+ encoder_hidden_states: Optional[Tuple[tf.Tensor]] = None
+ decoder_attentions: Optional[Tuple[Tuple[tf.Tensor]]] = None
+ cross_attentions: Optional[Tuple[Tuple[tf.Tensor]]] = None
+ decoder_hidden_states: Optional[Tuple[Tuple[tf.Tensor]]] = None
+
+
+@dataclass
+class TFBeamSampleDecoderOnlyOutput(ModelOutput):
+ """
+ Base class for outputs of decoder-only generation models using beam sample.
+
+ Args:
+ sequences (`tf.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ sequences_scores (`tf.Tensor` of shape `(batch_size * num_return_sequence)`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Final beam scores of the generated `sequences`.
+ scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Processed beam scores for each vocabulary token at each generation step. Beam scores consisting of log
+ softmax scores for each vocabulary token and sum of log softmax of previously generated tokens in this
+ beam. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each generated token),
+ with each tensor of shape `(batch_size*num_beams*num_return_sequences, config.vocab_size)`.
+ beam_indices (`tf.Tensor`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Beam indices of generated token id at each generation step. `tf.Tensor` of shape
+ `(batch_size*num_return_sequences, sequence_length)`.
+ attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size*num_beams, num_heads, generated_length, sequence_length)`.
+ hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size*num_beams, generated_length, hidden_size)`.
+ """
+
+ sequences: tf.Tensor = None
+ sequences_scores: Optional[tf.Tensor] = None
+ scores: Optional[Tuple[tf.Tensor]] = None
+ beam_indices: Optional[tf.Tensor] = None
+ attentions: Optional[Tuple[Tuple[tf.Tensor]]] = None
+ hidden_states: Optional[Tuple[Tuple[tf.Tensor]]] = None
+
+
+@dataclass
+class TFBeamSampleEncoderDecoderOutput(ModelOutput):
+ """
+ Base class for outputs of encoder-decoder generation models using beam sampling. Hidden states and attention
+ weights of the decoder (respectively the encoder) can be accessed via the encoder_attentions and the
+ encoder_hidden_states attributes (respectively the decoder_attentions and the decoder_hidden_states attributes)
+
+ Args:
+ sequences (`tf.Tensor` of shape `(batch_size*num_beams, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ sequences_scores (`tf.Tensor` of shape `(batch_size * num_return_sequence)`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Final beam scores of the generated `sequences`.
+ scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Processed beam scores for each vocabulary token at each generation step. Beam scores consisting of log
+ softmax scores for each vocabulary token and sum of log softmax of previously generated tokens in this
+ beam. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each generated token),
+ with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
+ beam_indices (`tf.Tensor`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Beam indices of generated token id at each generation step. `tf.Tensor` of shape
+ `(batch_size*num_return_sequences, sequence_length)`.
+ encoder_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple of `tf.Tensor` (one for each layer of the decoder) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+ encoder_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size*num_beams, sequence_length, hidden_size)`.
+ decoder_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size*num_beams, num_heads, generated_length, sequence_length)`.
+ cross_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
+ decoder_hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size*num_beams, generated_length, hidden_size)`.
+ """
+
+ sequences: tf.Tensor = None
+ sequences_scores: Optional[tf.Tensor] = None
+ scores: Optional[Tuple[tf.Tensor]] = None
+ beam_indices: Optional[tf.Tensor] = None
+ encoder_attentions: Optional[Tuple[tf.Tensor]] = None
+ encoder_hidden_states: Optional[Tuple[tf.Tensor]] = None
+ decoder_attentions: Optional[Tuple[Tuple[tf.Tensor]]] = None
+ cross_attentions: Optional[Tuple[Tuple[tf.Tensor]]] = None
+ decoder_hidden_states: Optional[Tuple[Tuple[tf.Tensor]]] = None
+
+
+@dataclass
+class TFContrastiveSearchDecoderOnlyOutput(ModelOutput):
+ """
+ Base class for outputs of decoder-only generation models using contrastive search.
+
+ Args:
+ sequences (`tf.Tensor` of shape `(batch_size, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each
+ generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
+ attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
+ hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size, generated_length, hidden_size)`.
+ """
+
+ sequences: tf.Tensor = None
+ scores: Optional[Tuple[tf.Tensor]] = None
+ attentions: Optional[Tuple[Tuple[tf.Tensor]]] = None
+ hidden_states: Optional[Tuple[Tuple[tf.Tensor]]] = None
+
+
+@dataclass
+class TFContrastiveSearchEncoderDecoderOutput(ModelOutput):
+ """
+ Base class for outputs of encoder-decoder generation models using contrastive search. Hidden states and attention
+ weights of the decoder (respectively the encoder) can be accessed via the encoder_attentions and the
+ encoder_hidden_states attributes (respectively the decoder_attentions and the decoder_hidden_states attributes)
+
+ Args:
+ sequences (`tf.Tensor` of shape `(batch_size, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ scores (`tuple(tf.Tensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
+ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `tf.Tensor` with up to `max_new_tokens` elements (one element for each
+ generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
+ encoder_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple of `tf.Tensor` (one for each layer of the decoder) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+ encoder_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size, sequence_length, hidden_size)`.
+ decoder_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
+ cross_attentions (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
+ decoder_hidden_states (`tuple(tuple(tf.Tensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `tf.Tensor` of shape `(batch_size, generated_length, hidden_size)`.
+ """
+
+ sequences: tf.Tensor = None
+ scores: Optional[Tuple[tf.Tensor]] = None
+ encoder_attentions: Optional[Tuple[tf.Tensor]] = None
+ encoder_hidden_states: Optional[Tuple[tf.Tensor]] = None
+ decoder_attentions: Optional[Tuple[Tuple[tf.Tensor]]] = None
+ cross_attentions: Optional[Tuple[Tuple[tf.Tensor]]] = None
+ decoder_hidden_states: Optional[Tuple[Tuple[tf.Tensor]]] = None
+
+
+TFGreedySearchOutput = Union[TFGreedySearchEncoderDecoderOutput, TFGreedySearchDecoderOnlyOutput]
+TFSampleOutput = Union[TFSampleEncoderDecoderOutput, TFSampleDecoderOnlyOutput]
+TFBeamSearchOutput = Union[TFBeamSearchEncoderDecoderOutput, TFBeamSearchDecoderOnlyOutput]
+TFBeamSampleOutput = Union[TFBeamSampleEncoderDecoderOutput, TFBeamSampleDecoderOnlyOutput]
+TFContrastiveSearchOutput = Union[TFContrastiveSearchEncoderDecoderOutput, TFContrastiveSearchDecoderOnlyOutput]
+TFGenerateOutput = Union[
+ TFGreedySearchOutput, TFSampleOutput, TFBeamSearchOutput, TFBeamSampleOutput, TFContrastiveSearchOutput
+]
+
+
+class TFGenerationMixin:
+ """
+ A class containing all of the functions supporting generation, to be used as a mixin in [`TFPreTrainedModel`].
+
+ The class exposes [`~generation.TFGenerationMixin.generate`], which can be used for:
+ - *greedy decoding* by calling [`~generation.TFGenerationMixin.greedy_search`] if `num_beams=1` and
+ `do_sample=False`
+ - *contrastive search* by calling [`~generation.TFGenerationMixin.contrastive_search`] if `penalty_alpha>0` and
+ `top_k>1`
+ - *multinomial sampling* by calling [`~generation.TFGenerationMixin.sample`] if `num_beams=1` and
+ `do_sample=True`
+ - *beam-search decoding* by calling [`~generation.TFGenerationMixin.beam_search`] if `num_beams>1`
+
+ You do not need to call any of the above methods directly. Pass custom parameter values to 'generate' instead. To
+ learn more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).
+ """
+
+ _seed_generator = None
+
+ @property
+ def seed_generator(self):
+ warnings.warn("`seed_generator` is deprecated and will be removed in a future version.", UserWarning)
+ if self._seed_generator is None:
+ self._seed_generator = tf.random.Generator.from_non_deterministic_state()
+ return self._seed_generator
+
+ supports_xla_generation = True
+
+ def prepare_inputs_for_generation(self, *args, **kwargs):
+ raise NotImplementedError(
+ "A model class needs to define a `prepare_inputs_for_generation` method in order to use `generate`."
+ )
+
+ def compute_transition_scores(
+ self,
+ sequences: tf.Tensor,
+ scores: Tuple[tf.Tensor],
+ beam_indices: Optional[tf.Tensor] = None,
+ normalize_logits: bool = False,
+ ) -> tf.Tensor:
+ """
+ Computes the transition scores of sequences given the generation scores (and beam indices, if beam search was
+ used). This is a convenient method to quicky obtain the scores of the selected tokens at generation time.
+
+ Parameters:
+ sequences (`tf.Tensor`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or
+ shorter if all batches finished early due to the `eos_token_id`.
+ scores (`tuple(tf.Tensor)`):
+ Transition scores for each vocabulary token at each generation step. Beam transition scores consisting
+ of log probabilities of tokens conditioned on log softmax of previously generated tokens Tuple of
+ `tf.Tensor` with up to `max_new_tokens` elements (one element for each generated token), with each
+ tensor of shape `(batch_size*num_beams, config.vocab_size)`.
+ beam_indices (`tf.Tensor`, *optional*):
+ Beam indices of generated token id at each generation step. `tf.Tensor` of shape
+ `(batch_size*num_return_sequences, sequence_length)`. Only required if a `num_beams>1` at
+ generate-time.
+ normalize_logits (`bool`, *optional*, defaults to `False`):
+ Whether to normalize the logits (which, for legacy reasons, may be unnormalized).
+
+ Return:
+ `tf.Tensor`: A `tf.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)` containing
+ the transition scores (logits)
+
+ Examples:
+
+ ```python
+ >>> from transformers import GPT2Tokenizer, TFAutoModelForCausalLM
+ >>> import numpy as np
+
+ >>> tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
+ >>> model = TFAutoModelForCausalLM.from_pretrained("openai-community/gpt2")
+ >>> tokenizer.pad_token_id = tokenizer.eos_token_id
+ >>> inputs = tokenizer(["Today is"], return_tensors="tf")
+
+ >>> # Example 1: Print the scores for each token generated with Greedy Search
+ >>> outputs = model.generate(**inputs, max_new_tokens=5, return_dict_in_generate=True, output_scores=True)
+ >>> transition_scores = model.compute_transition_scores(
+ ... outputs.sequences, outputs.scores, normalize_logits=True
+ ... )
+ >>> # input_length is the length of the input prompt for decoder-only models, like the GPT family, and 1 for
+ >>> # encoder-decoder models, like BART or T5.
+ >>> input_length = 1 if model.config.is_encoder_decoder else inputs.input_ids.shape[1]
+ >>> generated_tokens = outputs.sequences[:, input_length:]
+ >>> for tok, score in zip(generated_tokens[0], transition_scores[0]):
+ ... # | token | token string | logits | probability
+ ... print(f"| {tok:5d} | {tokenizer.decode(tok):8s} | {score.numpy():.3f} | {np.exp(score.numpy()):.2%}")
+ | 262 | the | -1.414 | 24.33%
+ | 1110 | day | -2.609 | 7.36%
+ | 618 | when | -2.010 | 13.40%
+ | 356 | we | -1.859 | 15.58%
+ | 460 | can | -2.508 | 8.14%
+
+ >>> # Example 2: Reconstruct the sequence scores from Beam Search
+ >>> outputs = model.generate(
+ ... **inputs,
+ ... max_new_tokens=5,
+ ... num_beams=4,
+ ... num_return_sequences=4,
+ ... return_dict_in_generate=True,
+ ... output_scores=True,
+ ... )
+ >>> transition_scores = model.compute_transition_scores(
+ ... outputs.sequences, outputs.scores, outputs.beam_indices, normalize_logits=False
+ ... )
+ >>> # If you sum the generated tokens' scores and apply the length penalty, you'll get the sequence scores.
+ >>> # Tip: recomputing the scores is only guaranteed to match with `normalize_logits=False`. Depending on the
+ >>> # use case, you might want to recompute it with `normalize_logits=True`.
+ >>> output_length = np.sum(transition_scores.numpy() < 0, axis=1)
+ >>> length_penalty = model.generation_config.length_penalty
+ >>> reconstructed_scores = np.sum(transition_scores, axis=1) / (output_length**length_penalty)
+ >>> print(np.allclose(outputs.sequences_scores, reconstructed_scores))
+ True
+ ```"""
+ # 1. In absence of `beam_indices`, we can assume that we come from e.g. greedy search, which is equivalent
+ # to a beam search approach were the first (and only) beam is always selected
+ if beam_indices is None:
+ beam_indices = tf.tile(tf.expand_dims(tf.range(scores[0].shape[0]), axis=1), [1, len(scores)])
+
+ # 2. reshape scores as [batch_size, vocab_size, # generation steps] with # generation steps being
+ # seq_len - input_length
+ scores = tf.transpose(tf.reshape(tf.stack(scores), (len(scores), -1)), (1, 0))
+ scores = tf.reshape(scores, (-1, self.config.vocab_size, scores.shape[-1]))
+
+ # 3. Optionally normalize the logits (across the vocab dimension)
+ if normalize_logits:
+ scores = tf.nn.log_softmax(scores, axis=1)
+
+ # 4. cut beam_indices to longest beam length
+ beam_indices_mask = beam_indices < 0
+ max_beam_length = tf.math.reduce_max(
+ tf.math.reduce_sum((1 - tf.cast(beam_indices_mask, dtype=tf.int32)), axis=-1)
+ )
+ beam_indices = beam_indices[:, -max_beam_length:]
+ beam_indices_mask = beam_indices_mask[:, -max_beam_length:]
+
+ # 5. Set indices of beams that finished early to 0; such indices will be masked correctly afterwards
+ beam_indices = tf.where(beam_indices_mask, 0, beam_indices)
+
+ # 6. Define which indices contributed to scores
+ cut_idx = sequences.shape[-1] - max_beam_length
+ token_indices = sequences[:, cut_idx:]
+ gen_step_idx = tf.broadcast_to(tf.range(scores.shape[-1]), token_indices.shape)
+ indices = tf.stack([beam_indices, token_indices, gen_step_idx], axis=-1)
+
+ # 7. Compute scores
+ transition_scores = tf.gather_nd(scores, indices)
+
+ # 8. Mask out transition_scores of beams that stopped early
+ transition_scores = tf.where(beam_indices_mask, 0, transition_scores)
+
+ return transition_scores
+
+ def _validate_model_class(self):
+ """
+ Confirms that the model class is compatible with generation. If not, raises an exception that points to the
+ right class to use.
+ """
+ if not self.can_generate():
+ generate_compatible_mappings = [
+ TF_MODEL_FOR_CAUSAL_LM_MAPPING,
+ TF_MODEL_FOR_VISION_2_SEQ_MAPPING,
+ TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
+ TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
+ ]
+ generate_compatible_classes = set()
+ for model_mapping in generate_compatible_mappings:
+ supported_models = model_mapping.get(type(self.config), default=None)
+ if supported_models is not None:
+ generate_compatible_classes.add(supported_models.__name__)
+ exception_message = (
+ f"The current model class ({self.__class__.__name__}) is not compatible with `.generate()`, as "
+ "it doesn't have a language model head."
+ )
+ if generate_compatible_classes:
+ exception_message += f" Please use one of the following classes instead: {generate_compatible_classes}"
+ raise TypeError(exception_message)
+
+ def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]):
+ """Validates model kwargs for generation. Generate argument typos will also be caught here."""
+ # Excludes arguments that are handled before calling any model function
+ if self.config.is_encoder_decoder:
+ for key in ["decoder_input_ids"]:
+ model_kwargs.pop(key, None)
+
+ unused_model_args = []
+ model_args = set(inspect.signature(self.prepare_inputs_for_generation).parameters)
+ # `kwargs`/`model_kwargs` is often used to handle optional forward pass inputs like `attention_mask`. If
+ # `prepare_inputs_for_generation` doesn't accept them, then a stricter check can be made ;)
+ if "kwargs" in model_args or "model_kwargs" in model_args:
+ model_args |= set(inspect.signature(self.call).parameters)
+ for key, value in model_kwargs.items():
+ if value is not None and key not in model_args:
+ unused_model_args.append(key)
+
+ if unused_model_args:
+ raise ValueError(
+ f"The following `model_kwargs` are not used by the model: {unused_model_args} (note: typos in the"
+ " generate arguments will also show up in this list)"
+ )
+
+ def generate(
+ self,
+ inputs: Optional[tf.Tensor] = None,
+ generation_config: Optional[GenerationConfig] = None,
+ logits_processor: Optional[TFLogitsProcessorList] = None,
+ seed=None,
+ **kwargs,
+ ) -> Union[TFGenerateOutput, tf.Tensor]:
+ r"""
+ Generates sequences of token ids for models with a language modeling head.
+
+
+
+ Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the
+ model's default generation configuration. You can override any `generation_config` by passing the corresponding
+ parameters to generate, e.g. `.generate(inputs, num_beams=4, do_sample=True)`.
+
+ For an overview of generation strategies and code examples, check out the [following
+ guide](../generation_strategies).
+
+
+
+ Parameters:
+ inputs (`tf.Tensor` of varying shape depending on the modality, *optional*):
+ The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the
+ method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs`
+ should of in the format of `input_ids`. For encoder-decoder models *inputs* can represent any of
+ `input_ids`, `input_values`, `input_features`, or `pixel_values`.
+ generation_config (`~generation.GenerationConfig`, *optional*):
+ The generation configuration to be used as base parametrization for the generation call. `**kwargs`
+ passed to generate matching the attributes of `generation_config` will override them. If
+ `generation_config` is not provided, the default will be used, which had the following loading
+ priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
+ configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
+ default values, whose documentation should be checked to parameterize generation.
+ logits_processor (`LogitsProcessorList`, *optional*):
+ Custom logits processors that complement the default logits processors built from arguments and
+ generation config. If a logit processor is passed that is already created with the arguments or a
+ generation config an error is thrown. This feature is intended for advanced users.
+ seed (`List[int]`, *optional*):
+ Random seed to control sampling, containing two integers, used when `do_sample` is `True`. See the
+ `seed` argument from stateless functions in `tf.random`.
+ kwargs (`Dict[str, Any]`, *optional*):
+ Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be
+ forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
+ specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.
+
+ Return:
+ [`~utils.ModelOutput`] or `tf.Tensor`: A [`~utils.ModelOutput`] (if `return_dict_in_generate=True` or when
+ `config.return_dict_in_generate=True`) or a `tf.Tensor`.
+
+ If the model is *not* an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible
+ [`~utils.ModelOutput`] types are:
+
+ - [`~generation.TFGreedySearchDecoderOnlyOutput`],
+ - [`~generation.TFSampleDecoderOnlyOutput`],
+ - [`~generation.TFBeamSearchDecoderOnlyOutput`],
+ - [`~generation.TFBeamSampleDecoderOnlyOutput`]
+
+ If the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible
+ [`~utils.ModelOutput`] types are:
+
+ - [`~generation.TFGreedySearchEncoderDecoderOutput`],
+ - [`~generation.TFSampleEncoderDecoderOutput`],
+ - [`~generation.TFBeamSearchEncoderDecoderOutput`],
+ - [`~generation.TFBeamSampleEncoderDecoderOutput`]
+
+ """
+
+ # 1. Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call
+ self._validate_model_class()
+
+ # priority: `generation_config` argument > `model.generation_config` (the default generation config)
+ if generation_config is None:
+ # legacy: users may modify the model configuration to control generation. To trigger this legacy behavior,
+ # two conditions must be met
+ # 1) the generation config must have been created from the model config (`_from_model_config` field);
+ # 2) the generation config must have seen no modification since its creation (the hash is the same).
+ if self.generation_config._from_model_config and self.generation_config._original_object_hash == hash(
+ self.generation_config
+ ):
+ new_generation_config = GenerationConfig.from_model_config(self.config)
+ if new_generation_config != self.generation_config:
+ warnings.warn(
+ "You have modified the pretrained model configuration to control generation. This is a"
+ " deprecated strategy to control generation and will be removed soon, in a future version."
+ " Please use and modify the model generation configuration (see"
+ " https://huggingface.co/docs/transformers/generation_strategies#default-text-generation-configuration )"
+ )
+ self.generation_config = new_generation_config
+ generation_config = self.generation_config
+
+ generation_config = copy.deepcopy(generation_config)
+ model_kwargs = generation_config.update(**kwargs) # All unused kwargs must be model kwargs
+ self._validate_model_kwargs(model_kwargs.copy())
+
+ # 2. Cast input dtypes to tf.int32 unless they're floats (which happens for some image models)
+ if inputs is not None:
+ if isinstance(inputs, tf.Tensor) and inputs.dtype.is_floating:
+ pass
+ elif isinstance(inputs, np.ndarray) and np.issubdtype(inputs.dtype, np.floating):
+ pass
+ else:
+ inputs = tf.cast(inputs, tf.int32)
+ if model_kwargs.get("attention_mask") is not None:
+ model_kwargs["attention_mask"] = tf.cast(model_kwargs["attention_mask"], tf.int32)
+ if "decoder_input_ids" in model_kwargs:
+ if (
+ isinstance(model_kwargs["decoder_input_ids"], tf.Tensor)
+ and model_kwargs["decoder_input_ids"].dtype.is_floating
+ ):
+ pass
+ elif isinstance(model_kwargs["decoder_input_ids"], np.ndarray) and np.issubdtype(
+ model_kwargs["decoder_input_ids"].dtype, np.floating
+ ):
+ pass
+ else:
+ model_kwargs["decoder_input_ids"] = tf.cast(model_kwargs["decoder_input_ids"], tf.int32)
+
+ # 3. Set generation parameters if not already defined
+ logits_processor = logits_processor if logits_processor is not None else TFLogitsProcessorList()
+
+ if generation_config.pad_token_id is None and generation_config.eos_token_id is not None:
+ if model_kwargs.get("attention_mask") is None:
+ logger.warning(
+ "The attention mask and the pad token id were not set. As a consequence, you may observe "
+ "unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results."
+ )
+ eos_token_id = generation_config.eos_token_id
+ if isinstance(eos_token_id, list):
+ eos_token_id = eos_token_id[0]
+ generation_config.pad_token_id = eos_token_id
+
+ use_xla = not tf.executing_eagerly()
+ if use_xla and not self.supports_xla_generation:
+ raise ValueError(
+ "The selected model does not support Graph mode nor XLA generation (e.g. from tf.function())"
+ )
+
+ # 4. Define model inputs
+ inputs_tensor, model_input_name, model_kwargs = self._prepare_model_inputs(
+ inputs, generation_config.bos_token_id, model_kwargs
+ )
+ # inputs_ids now has to be defined and cannot be None anymore
+ batch_size = shape_list(inputs_tensor)[0]
+
+ # 5. Prepare other model kwargs
+ model_kwargs["output_attentions"] = generation_config.output_attentions
+ model_kwargs["output_hidden_states"] = generation_config.output_hidden_states
+ model_kwargs["use_cache"] = generation_config.use_cache
+
+ accepts_attention_mask = "attention_mask" in set(inspect.signature(self.call).parameters.keys())
+ requires_attention_mask = "encoder_outputs" not in model_kwargs
+
+ if model_kwargs.get("attention_mask", None) is None and requires_attention_mask and accepts_attention_mask:
+ model_kwargs["attention_mask"] = self._prepare_attention_mask_for_generation(
+ inputs_tensor, generation_config.pad_token_id, generation_config.eos_token_id
+ )
+
+ # decoder-only models should use left-padding for generation
+ if not self.config.is_encoder_decoder:
+ if generation_config.pad_token_id is not None and tf.math.reduce_any(
+ inputs_tensor[:, -1] == generation_config.pad_token_id
+ ):
+ logger.warning(
+ "A decoder-only architecture is being used, but right-padding was detected! For correct "
+ "generation results, please set `padding_side='left'` when initializing the tokenizer."
+ )
+ if self.config.is_encoder_decoder and "encoder_outputs" not in model_kwargs:
+ # if model is encoder decoder encoder_outputs are created and added to `model_kwargs`
+ model_kwargs = self._prepare_encoder_decoder_kwargs_for_generation(
+ inputs_tensor, model_kwargs, model_input_name
+ )
+
+ # 6. Prepare model inputs which will be used for auto-regressive generation
+ if self.config.is_encoder_decoder:
+ input_ids, model_kwargs = self._prepare_decoder_input_ids_for_generation(
+ batch_size=batch_size,
+ model_input_name=model_input_name,
+ model_kwargs=model_kwargs,
+ decoder_start_token_id=generation_config.decoder_start_token_id,
+ bos_token_id=generation_config.bos_token_id,
+ )
+ else:
+ input_ids = inputs_tensor if model_input_name == "input_ids" else model_kwargs.pop("input_ids")
+
+ # 7. Prepare `max_length` depending on other stopping criteria.
+ input_ids_seq_length = shape_list(input_ids)[-1]
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
+ if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length == 20:
+ # 20 is the default max_length of the generation config
+ warnings.warn(
+ f"Using the model-agnostic default `max_length` (={generation_config.max_length}) "
+ "to control the generation length. recommend setting `max_new_tokens` to control the maximum length of the generation.",
+ UserWarning,
+ )
+ elif generation_config.max_new_tokens is not None:
+ if not has_default_max_length and generation_config.max_length is not None:
+ logger.warning(
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
+ "Please refer to the documentation for more information. "
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
+ )
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
+
+ # If the input length is a tensor (i.e. dynamic length), skip length checks
+ if not isinstance(input_ids_seq_length, tf.Tensor):
+ if (
+ generation_config.min_length is not None
+ and generation_config.min_length > generation_config.max_length
+ ):
+ raise ValueError(
+ f"Unfeasable length constraints: the minimum length ({generation_config.min_length}) is larger"
+ f" than the maximum length ({generation_config.max_length})"
+ )
+ if input_ids_seq_length >= generation_config.max_length:
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
+ logger.warning(
+ f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
+ " increasing`max_new_tokens`."
+ )
+
+ # 8. determine generation mode
+ is_contrastive_search_gen_mode = (
+ generation_config.top_k is not None
+ and generation_config.top_k > 1
+ and generation_config.do_sample is False
+ and generation_config.penalty_alpha is not None
+ and generation_config.penalty_alpha > 0
+ )
+ is_greedy_gen_mode = (
+ not is_contrastive_search_gen_mode
+ and (generation_config.num_beams == 1)
+ and generation_config.do_sample is False
+ )
+ is_beam_gen_mode = (
+ not is_contrastive_search_gen_mode
+ and (generation_config.num_beams > 1)
+ and generation_config.do_sample is False
+ )
+ is_sample_gen_mode = (generation_config.num_beams == 1) and generation_config.do_sample is True
+ is_beam_sample_gen_mode = (generation_config.num_beams > 1) and generation_config.do_sample is True
+
+ # 9. prepare distribution pre_processing samplers
+ logits_processor = self._get_logits_processor(
+ generation_config=generation_config,
+ input_ids_seq_length=input_ids_seq_length,
+ logits_processor=logits_processor,
+ )
+
+ # 10. go into different generation modes
+ if is_greedy_gen_mode:
+ if generation_config.num_return_sequences > 1:
+ raise ValueError(
+ f"num_return_sequences has to be 1, but is {generation_config.num_return_sequences} when doing"
+ " greedy search."
+ )
+ # 11. run greedy search
+ return self.greedy_search(
+ input_ids,
+ max_length=generation_config.max_length,
+ pad_token_id=generation_config.pad_token_id,
+ eos_token_id=generation_config.eos_token_id,
+ logits_processor=logits_processor,
+ output_scores=generation_config.output_scores,
+ return_dict_in_generate=generation_config.return_dict_in_generate,
+ **model_kwargs,
+ )
+ elif is_contrastive_search_gen_mode:
+ if generation_config.num_return_sequences > 1:
+ raise ValueError(
+ f"num_return_sequences has to be 1, but is {generation_config.num_return_sequences} when doing"
+ " contrastive search."
+ )
+ # 11. run contrastive search
+ return self.contrastive_search(
+ input_ids,
+ top_k=generation_config.top_k,
+ penalty_alpha=generation_config.penalty_alpha,
+ logits_processor=logits_processor,
+ max_length=generation_config.max_length,
+ pad_token_id=generation_config.pad_token_id,
+ eos_token_id=generation_config.eos_token_id,
+ output_scores=generation_config.output_scores,
+ return_dict_in_generate=generation_config.return_dict_in_generate,
+ **model_kwargs,
+ )
+ elif is_sample_gen_mode:
+ # 11. prepare logits warper
+ logits_warper = self._get_logits_warper(generation_config=generation_config)
+
+ # 12. expand input_ids with `num_return_sequences` additional sequences per batch
+ input_ids, model_kwargs = self._expand_inputs_for_generation(
+ input_ids=input_ids,
+ expand_size=generation_config.num_return_sequences,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ **model_kwargs,
+ )
+
+ # 13. run sample
+ return self.sample(
+ input_ids,
+ logits_processor=logits_processor,
+ logits_warper=logits_warper,
+ max_length=generation_config.max_length,
+ pad_token_id=generation_config.pad_token_id,
+ eos_token_id=generation_config.eos_token_id,
+ seed=seed,
+ output_scores=generation_config.output_scores,
+ return_dict_in_generate=generation_config.return_dict_in_generate,
+ **model_kwargs,
+ )
+
+ elif is_beam_gen_mode:
+ if generation_config.num_beams < generation_config.num_return_sequences:
+ raise ValueError(
+ "Beam search decoding cannot return more sequences than it has beams. Please set num_beams >="
+ f" num_return_sequences, got {generation_config.num_beams} and"
+ f" {generation_config.num_return_sequences} (respectivelly)"
+ )
+
+ # 11. broadcast inputs to the desired number of beams
+ input_ids, model_kwargs = self._expand_inputs_for_generation(
+ input_ids=input_ids,
+ expand_size=generation_config.num_beams,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ expand_in_new_axis=True,
+ **model_kwargs,
+ )
+
+ # 12. run beam search
+ return self.beam_search(
+ input_ids,
+ max_length=generation_config.max_length,
+ pad_token_id=generation_config.pad_token_id,
+ eos_token_id=generation_config.eos_token_id,
+ length_penalty=generation_config.length_penalty,
+ early_stopping=generation_config.early_stopping,
+ logits_processor=logits_processor,
+ output_scores=generation_config.output_scores,
+ return_dict_in_generate=generation_config.return_dict_in_generate,
+ num_return_sequences=generation_config.num_return_sequences,
+ **model_kwargs,
+ )
+
+ elif is_beam_sample_gen_mode:
+ if generation_config.num_beams < generation_config.num_return_sequences:
+ raise ValueError(
+ "Beam search decoding cannot return more sequences than it has beams. Please set num_beams >="
+ f" num_return_sequences, got {generation_config.num_beams} and"
+ f" {generation_config.num_return_sequences} (respectivelly)"
+ )
+
+ # 11. prepare logits warper
+ logits_warper = self._get_logits_warper(generation_config=generation_config)
+
+ # 12. broadcast inputs to the desired number of beams
+ input_ids, model_kwargs = self._expand_inputs_for_generation(
+ input_ids=input_ids,
+ expand_size=generation_config.num_beams,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ expand_in_new_axis=True,
+ **model_kwargs,
+ )
+
+ # 13. run beam sample (beam search with sampling)
+ return self.beam_search(
+ input_ids,
+ do_sample=True,
+ max_length=generation_config.max_length,
+ pad_token_id=generation_config.pad_token_id,
+ eos_token_id=generation_config.eos_token_id,
+ length_penalty=generation_config.length_penalty,
+ early_stopping=generation_config.early_stopping,
+ logits_processor=logits_processor,
+ logits_warper=logits_warper,
+ output_scores=generation_config.output_scores,
+ return_dict_in_generate=generation_config.return_dict_in_generate,
+ num_return_sequences=generation_config.num_return_sequences,
+ **model_kwargs,
+ )
+
+ def _prepare_attention_mask_for_generation(
+ self,
+ inputs: tf.Tensor,
+ pad_token_id: Optional[int],
+ eos_token_id: Optional[int],
+ ) -> tf.Tensor:
+ is_input_ids = len(inputs.shape) == 2 and inputs.dtype in (tf.int32, tf.int64)
+ is_pad_token_in_inputs = (pad_token_id is not None) and tf.math.reduce_any(inputs == pad_token_id)
+ is_pad_token_not_equal_to_eos_token_id = (eos_token_id is None) or (pad_token_id != eos_token_id)
+
+ # Check if input is input_ids and padded -> only then is attention_mask defined
+ if is_input_ids and is_pad_token_in_inputs and is_pad_token_not_equal_to_eos_token_id:
+ return tf.cast(tf.math.not_equal(inputs, pad_token_id), dtype=tf.int32)
+ else:
+ return tf.ones(inputs.shape[:2], dtype=tf.int32)
+
+ def _prepare_encoder_decoder_kwargs_for_generation(
+ self, inputs_tensor: tf.Tensor, model_kwargs, model_input_name: Optional[str] = None
+ ) -> Dict[str, Any]:
+ # 1. get encoder and store encoder outputs
+ encoder = self.get_encoder()
+
+ # 2. prepare encoder args and encoder kwargs from model kwargs
+ irrelevant_prefix = ["decoder_", "cross_attn", "use_cache"]
+ encoder_kwargs = {
+ argument: value
+ for argument, value in model_kwargs.items()
+ if not any(argument.startswith(p) for p in irrelevant_prefix)
+ }
+ encoder_signature = set(inspect.signature(encoder.call).parameters)
+ encoder_accepts_wildcard = "kwargs" in encoder_signature or "model_kwargs" in encoder_signature
+ if not encoder_accepts_wildcard:
+ encoder_kwargs = {
+ argument: value for argument, value in encoder_kwargs.items() if argument in encoder_signature
+ }
+
+ # 3. vision models don't use `attention_mask`.
+ encoder_kwargs["return_dict"] = True
+ encoder_kwargs[model_input_name] = inputs_tensor
+ if model_input_name != self.main_input_name: # in Keras, the first input must always be passed
+ encoder_kwargs[self.main_input_name] = None
+ encoder_outputs = encoder(**encoder_kwargs)
+ model_kwargs["encoder_outputs"] = encoder_outputs
+
+ return model_kwargs
+
+ def _prepare_decoder_input_ids_for_generation(
+ self,
+ batch_size: int,
+ model_input_name: str,
+ model_kwargs: Dict[str, tf.Tensor],
+ decoder_start_token_id: int = None,
+ bos_token_id: int = None,
+ ) -> Tuple[tf.Tensor, Dict[str, tf.Tensor]]:
+ """Prepares `decoder_input_ids` for generation with encoder-decoder models"""
+ # 1. Check whether the user has defined `decoder_input_ids` manually. To facilitate in terms of input naming,
+ # we also allow the user to pass it under `input_ids`, if the encoder does not use it as the main input.
+ if model_kwargs is not None and "decoder_input_ids" in model_kwargs:
+ decoder_input_ids = model_kwargs.pop("decoder_input_ids")
+ elif "input_ids" in model_kwargs and model_input_name != "input_ids":
+ decoder_input_ids = model_kwargs.pop("input_ids")
+ else:
+ decoder_input_ids = None
+
+ # 2. Encoder-decoder models expect the `decoder_input_ids` to start with a special token. Let's ensure that.
+ decoder_start_token_id = self._get_decoder_start_token_id(decoder_start_token_id, bos_token_id)
+ decoder_input_ids_start = tf.ones((batch_size, 1), dtype=tf.int32) * decoder_start_token_id
+
+ # no user input -> use decoder_start_token_id as decoder_input_ids
+ if decoder_input_ids is None:
+ decoder_input_ids = decoder_input_ids_start
+ # user input but doesn't start with decoder_start_token_id -> prepend decoder_start_token_id (and adjust
+ # decoder_attention_mask if provided)
+ elif tf.reduce_all(decoder_input_ids[:, 0] != decoder_start_token_id):
+ decoder_input_ids = tf.concat([decoder_input_ids_start, decoder_input_ids], axis=-1)
+ if "decoder_attention_mask" in model_kwargs:
+ decoder_attention_mask = model_kwargs["decoder_attention_mask"]
+ decoder_attention_mask = tf.concat(
+ (tf.ones_like(decoder_attention_mask)[:, :1], decoder_attention_mask),
+ axis=-1,
+ )
+ model_kwargs["decoder_attention_mask"] = decoder_attention_mask
+
+ return decoder_input_ids, model_kwargs
+
+ def _get_decoder_start_token_id(self, decoder_start_token_id: int = None, bos_token_id: int = None) -> int:
+ # retrieve decoder_start_token_id for encoder-decoder models
+ # fall back to bos_token_id if necessary
+ decoder_start_token_id = (
+ decoder_start_token_id
+ if decoder_start_token_id is not None
+ else self.generation_config.decoder_start_token_id
+ )
+ bos_token_id = bos_token_id if bos_token_id is not None else self.generation_config.bos_token_id
+
+ if decoder_start_token_id is not None:
+ return decoder_start_token_id
+ elif bos_token_id is not None:
+ return bos_token_id
+ raise ValueError(
+ "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation."
+ )
+
+ @staticmethod
+ def _expand_inputs_for_generation(
+ expand_size: int = 1,
+ is_encoder_decoder: bool = False,
+ input_ids: Optional[tf.Tensor] = None,
+ expand_in_new_axis: bool = False,
+ **model_kwargs,
+ ) -> Tuple[tf.Tensor, Dict[str, Any]]:
+ """
+ Expands tensors from [batch_size, ...] to [batch_size * expand_size, ...] or [batch_size, expand_size, ...],
+ depending on `expand_in_new_axis`. Beam-based approaches expect this function to be used with
+ `expand_in_new_axis=True`
+ """
+
+ def _expand_tensor(tensor: tf.Tensor):
+ if expand_in_new_axis:
+ shape = shape_list(tensor)
+ return tf.broadcast_to(tensor[:, None], (shape[0], expand_size) + tuple(shape[1:]))
+ else:
+ return tf.repeat(tensor, expand_size, axis=0)
+
+ def _expand_dict_for_generation(dict_to_expand):
+ for key in dict_to_expand:
+ if dict_to_expand[key] is not None and isinstance(dict_to_expand[key], tf.Tensor):
+ dict_to_expand[key] = _expand_tensor(dict_to_expand[key])
+ return dict_to_expand
+
+ if input_ids is not None:
+ input_ids = _expand_tensor(input_ids)
+
+ model_kwargs = _expand_dict_for_generation(model_kwargs)
+
+ if is_encoder_decoder:
+ if model_kwargs.get("encoder_outputs") is None:
+ raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
+ model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
+
+ return input_ids, model_kwargs
+
+ def _prepare_model_inputs(
+ self,
+ inputs: Optional[tf.Tensor] = None,
+ bos_token_id: Optional[int] = None,
+ model_kwargs: Optional[Dict[str, tf.Tensor]] = None,
+ ) -> Tuple[tf.Tensor, Optional[str], Dict[str, tf.Tensor]]:
+ """
+ This function extracts the model-specific `inputs` for generation.
+ """
+ # 1. retrieve all kwargs that are non-None or non-model input related.
+ # some encoder-decoder models have different names for model and encoder
+ if (
+ self.config.is_encoder_decoder
+ and hasattr(self, "encoder")
+ and hasattr(self.encoder, "main_input_name")
+ and self.encoder.main_input_name != self.main_input_name
+ ):
+ input_name = self.encoder.main_input_name
+ else:
+ input_name = self.main_input_name
+
+ model_kwargs = {k: v for k, v in model_kwargs.items() if v is not None or k != input_name}
+
+ # 2. check whether model_input_name is passed as kwarg
+ # if yes and `inputs` is None use kwarg inputs
+ inputs_kwarg = model_kwargs.pop(input_name, None)
+ if inputs_kwarg is not None and inputs is not None:
+ raise ValueError(
+ f"`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. "
+ f"Make sure to either pass {inputs} or {input_name}=..."
+ )
+ elif inputs_kwarg is not None:
+ inputs = inputs_kwarg
+
+ # 3. In the presence of `inputs_embeds` for text models:
+ # - decoder-only models should complain if the user attempts to pass `inputs_embeds`, but the model
+ # doesn't have its forwarding implemented. `inputs_embeds` is kept in `model_kwargs` and can coexist with
+ # input_ids (`inputs_embeds` will be used in the 1st generation step, as opposed to `input_ids`)
+ # - encoder-decoder models should complain if the user attempts to pass `inputs_embeds` and `input_ids`, and
+ # pull the former to inputs. It will be used in place of `input_ids` to get the encoder hidden states.
+ if input_name == "input_ids" and "inputs_embeds" in model_kwargs:
+ if not self.config.is_encoder_decoder:
+ has_inputs_embeds_forwarding = "inputs_embeds" in set(
+ inspect.signature(self.prepare_inputs_for_generation).parameters.keys()
+ )
+ if not has_inputs_embeds_forwarding:
+ raise ValueError(
+ f"You passed `inputs_embeds` to `.generate()`, but the model class {self.__class__.__name__} "
+ "doesn't have its forwarding implemented. See the GPT2 implementation for an example "
+ "(https://github.com/huggingface/transformers/pull/21405), and feel free to open a PR with it!"
+ )
+ # In this case, `input_ids` is moved to the `model_kwargs`, so a few automations (like the creation of
+ # the attention mask) can rely on the actual model input.
+ model_kwargs["input_ids"] = self._maybe_initialize_input_ids_for_generation(
+ inputs, bos_token_id, model_kwargs=model_kwargs
+ )
+ else:
+ if inputs is not None:
+ raise ValueError("You passed `inputs_embeds` and `input_ids` to `.generate()`. Please pick one.")
+ inputs, input_name = model_kwargs["inputs_embeds"], "inputs_embeds"
+
+ # 4. if `inputs` is still None, try to create `input_ids` from BOS token
+ inputs = self._maybe_initialize_input_ids_for_generation(inputs, bos_token_id, model_kwargs)
+
+ return inputs, input_name, model_kwargs
+
+ def _maybe_initialize_input_ids_for_generation(
+ self,
+ inputs: Optional[tf.Tensor] = None,
+ bos_token_id: Optional[int] = None,
+ model_kwargs: Optional[Dict[str, tf.Tensor]] = None,
+ ) -> tf.Tensor:
+ """Initializes input ids for generation, if necessary."""
+ if inputs is not None:
+ return inputs
+
+ encoder_outputs = model_kwargs.get("encoder_outputs")
+ if self.config.is_encoder_decoder and encoder_outputs is not None:
+ # make dummy input_ids with value -100, as a sanity check ensuring that they won't be used for encoding
+ shape = encoder_outputs.last_hidden_state.shape[:-1]
+ return tf.ones(shape, dtype=tf.int32) * -100
+
+ if bos_token_id is None:
+ raise ValueError("`bos_token_id` has to be defined when no `input_ids` are provided.")
+
+ # If there is some tensor in `model_kwargs`, we can infer the batch size from it. This is helpful with
+ # soft-prompting or in multimodal implementations built on top of decoder-only language models.
+ batch_size = 1
+ for value in model_kwargs.values():
+ if isinstance(value, tf.Tensor):
+ batch_size = value.shape[0]
+ break
+ return tf.ones((batch_size, 1), dtype=tf.int32) * bos_token_id
+
+ @staticmethod
+ def _extract_past_from_model_output(outputs: ModelOutput):
+ past_key_values = None
+ if "past_key_values" in outputs:
+ past_key_values = outputs.past_key_values
+ elif "mems" in outputs:
+ past_key_values = outputs.mems
+ elif "past_buckets_states" in outputs:
+ past_key_values = outputs.past_buckets_states
+ return past_key_values
+
+ def _update_model_kwargs_for_generation(
+ self, outputs: ModelOutput, model_kwargs: Dict[str, Any], is_encoder_decoder: bool = False
+ ) -> Dict[str, Any]:
+ # update past_key_values
+ model_kwargs["past_key_values"] = self._extract_past_from_model_output(outputs)
+
+ # update attention mask
+ if not is_encoder_decoder:
+ if "attention_mask" in model_kwargs:
+ attention_mask = model_kwargs["attention_mask"]
+ model_kwargs["attention_mask"] = tf.concat(
+ [attention_mask, tf.ones((shape_list(attention_mask)[0], 1), dtype=tf.int32)], axis=-1
+ )
+
+ return model_kwargs
+
+ def _update_model_kwargs_for_xla_generation(
+ self,
+ model_outputs: ModelOutput,
+ model_kwargs: Dict[str, Any],
+ cur_len: int,
+ max_length: int,
+ batch_size: int,
+ is_encoder_decoder: bool = False,
+ batch_axis: int = 0,
+ ):
+ def _initialize_attention(model_kwargs, num_padding_values, is_encoder_decoder):
+ """initializes the appropriate attention mask -- encoder-decoder models use `decoder_attention_mask`"""
+ if is_encoder_decoder:
+ # One 1 for decoder_start_token_id, 0s for the currently-unfilled locations in the past_key_values tensor,
+ # 1s for the actual input_ids
+ decoder_attention_mask = tf.concat(
+ [
+ tf.ones((batch_size, 1), dtype=tf.int32),
+ tf.zeros((batch_size, num_padding_values), dtype=tf.int32),
+ tf.ones((batch_size, 1), dtype=tf.int32),
+ ],
+ axis=1,
+ )
+ mask = {"decoder_attention_mask": decoder_attention_mask}
+ else:
+ attention_mask = model_kwargs.pop("attention_mask")
+ # 0s for the currently-unfilled locations in the past_key_values tensor, 1s for the actual input_ids
+ attention_mask = tf.concat(
+ [
+ attention_mask,
+ tf.zeros((batch_size, num_padding_values), dtype=attention_mask.dtype),
+ tf.ones((batch_size, 1), dtype=attention_mask.dtype),
+ ],
+ axis=1,
+ )
+ mask = {"attention_mask": attention_mask}
+ return mask
+
+ def _update_attention(model_kwargs, new_past_index, is_encoder_decoder):
+ """updates the appropriate attention mask -- encoder-decoder models use `decoder_attention_mask`"""
+ update_start = tf.constant([0, 1], dtype=tf.int32) * new_past_index
+ if is_encoder_decoder:
+ decoder_attention_mask = model_kwargs.pop("decoder_attention_mask")
+ decoder_attention_mask_update_slice = tf.ones((batch_size, 1), dtype=decoder_attention_mask.dtype)
+ decoder_attention_mask = dynamic_update_slice(
+ decoder_attention_mask, decoder_attention_mask_update_slice, update_start
+ )
+ mask = {"decoder_attention_mask": decoder_attention_mask}
+ else:
+ attention_mask = model_kwargs.pop("attention_mask")
+ attention_mask_update_slice = tf.ones((batch_size, 1), dtype=attention_mask.dtype)
+ attention_mask = dynamic_update_slice(attention_mask, attention_mask_update_slice, update_start)
+ mask = {"attention_mask": attention_mask}
+ return mask
+
+ def _initialize_past(past_key_values, num_padding_values, batch_axis):
+ """initialize past_key_values with zeros -- the structure depends on `batch_axis`"""
+ if batch_axis == 0:
+ padding_values = tf.constant([[0, 0], [0, 0], [0, num_padding_values], [0, 0]], dtype=tf.int32)
+ new_past = ()
+ for past_layer in past_key_values:
+ new_past_layer = list(past_layer)
+ for i in range(len(new_past_layer[:2])):
+ new_past_layer[i] = tf.pad(past_layer[i], padding_values)
+ new_past += (tuple(new_past_layer),)
+ else:
+ padding_values = tf.scatter_nd(indices=[[3, 1]], updates=[num_padding_values], shape=(5, 2))
+ new_past = list(past_key_values)
+ for i in range(len(past_key_values)):
+ new_past[i] = tf.pad(past_key_values[i], padding_values)
+ return new_past
+
+ def _update_past(past_key_values, new_past_index, batch_axis):
+ if batch_axis == 0:
+ slice_start_base = tf.constant([0, 0, 1, 0])
+ new_past = ()
+ for past_layer in past_key_values:
+ new_past_layer = list(past_layer)
+ for i in range(len(new_past_layer[:2])):
+ update_slice = past_layer[i][:, :, -1:]
+ # Write the last slice to the first open location in the padded past_key_values array
+ # and then truncate the last slice off the array
+ new_past_layer[i] = dynamic_update_slice(
+ past_layer[i][:, :, :-1], update_slice, slice_start_base * new_past_index
+ )
+ new_past += (tuple(new_past_layer),)
+ else:
+ slice_start_base = tf.constant([0, 0, 0, 1, 0])
+ new_past = [None for _ in range(len(past_key_values))]
+ for i in range(len(past_key_values)):
+ update_slice = past_key_values[i][:, :, :, -1:]
+ # Write the last slice to the first open location in the padded past_key_values array
+ # and then truncate the last slice off the array
+ new_past[i] = dynamic_update_slice(
+ past_key_values[i][:, :, :, :-1], update_slice, slice_start_base * new_past_index
+ )
+ return new_past
+
+ past_key_values = self._extract_past_from_model_output(model_outputs)
+ if past_key_values is None:
+ raise ValueError(
+ "No known `past_key_values variable` found in model outputs (model outputs keys:"
+ f" {list(model_outputs.keys())})"
+ )
+ is_past_initialized = model_kwargs.pop("past_key_values", None) is not None
+
+ if not is_past_initialized:
+ # The padded version of `past_key_values` has a length of `max_length - 1`, as `past_key_values` holds information relative to
+ # previous autoregressive generation steps (step 0 has no past_key_values, step 1 has 1 past_key_values value, ..., the last step
+ # has `max_length - 1` past_key_values values).
+ num_padding_values = max_length - cur_len - 1
+ mask = _initialize_attention(model_kwargs, num_padding_values, is_encoder_decoder)
+ new_past = _initialize_past(past_key_values, num_padding_values, batch_axis)
+ else:
+ # The new index of past_key_values to be filled corresponds to the current length of the sequence, with two
+ # subtractions: -1 because past_key_values holds information regarding previous generation steps (read comment above)
+ # and -1 again because in an array the index is the length of the array minus 1.
+ new_past_index = cur_len - 2
+ mask = _update_attention(model_kwargs, new_past_index, is_encoder_decoder)
+ new_past = _update_past(past_key_values, new_past_index, batch_axis)
+
+ # sets the updated variables (mask and past_key_values)
+ model_kwargs.update(mask)
+ model_kwargs["past_key_values"] = tuple(new_past)
+
+ return model_kwargs
+
+ def _get_logits_warper(
+ self,
+ generation_config: GenerationConfig,
+ ) -> TFLogitsProcessorList:
+ """
+ This class returns a [`TFLogitsProcessorList`] list object that contains all relevant [`TFLogitsWarper`]
+ instances used for multinomial sampling.
+ """
+
+ # instantiate warpers list
+ warpers = TFLogitsProcessorList()
+
+ # In beam methods, we need to keep at least one non-eos token to explore continuations that might have a
+ # better score (i.e. keep len(generation_config.eos_token_id) + 1)
+ if generation_config.num_beams > 1:
+ if isinstance(generation_config.eos_token_id, list):
+ min_tokens_to_keep = len(generation_config.eos_token_id) + 1
+ else:
+ min_tokens_to_keep = 2
+ else:
+ min_tokens_to_keep = 1
+
+ if generation_config.temperature is not None and generation_config.temperature != 1.0:
+ warpers.append(TFTemperatureLogitsWarper(generation_config.temperature))
+ if generation_config.top_k is not None and generation_config.top_k != 0:
+ warpers.append(TFTopKLogitsWarper(top_k=generation_config.top_k, min_tokens_to_keep=min_tokens_to_keep))
+ if generation_config.top_p is not None and generation_config.top_p < 1.0:
+ warpers.append(TFTopPLogitsWarper(top_p=generation_config.top_p, min_tokens_to_keep=min_tokens_to_keep))
+ return warpers
+
+ def _get_logits_processor(
+ self,
+ generation_config: GenerationConfig,
+ input_ids_seq_length: int,
+ logits_processor: Optional[TFLogitsProcessorList],
+ ) -> TFLogitsProcessorList:
+ """
+ This class returns a [`TFLogitsProcessorList`] list object that contains all relevant [`TFLogitsProcessor`]
+ instances used to modify the scores of the language model head.
+ """
+ processors = TFLogitsProcessorList()
+
+ # instantiate processors list
+ if generation_config.repetition_penalty is not None and generation_config.repetition_penalty != 1.0:
+ processors.append(TFRepetitionPenaltyLogitsProcessor(penalty=generation_config.repetition_penalty))
+ if generation_config.no_repeat_ngram_size is not None and generation_config.no_repeat_ngram_size > 0:
+ processors.append(TFNoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size))
+ if generation_config.bad_words_ids is not None:
+ processors.append(
+ TFNoBadWordsLogitsProcessor(generation_config.bad_words_ids, generation_config.eos_token_id)
+ )
+ if (
+ generation_config.min_length is not None
+ and generation_config.eos_token_id is not None
+ and generation_config.min_length > 0
+ ):
+ processors.append(TFMinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id))
+ if generation_config.forced_bos_token_id is not None:
+ processors.append(TFForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id))
+ if generation_config.forced_eos_token_id is not None:
+ processors.append(
+ TFForcedEOSTokenLogitsProcessor(generation_config.max_length, generation_config.forced_eos_token_id)
+ )
+ if generation_config.suppress_tokens is not None:
+ processors.append(TFSuppressTokensLogitsProcessor(generation_config.suppress_tokens))
+ if generation_config.begin_suppress_tokens is not None:
+ begin_index = input_ids_seq_length
+ begin_index = (
+ begin_index
+ if (input_ids_seq_length > 1 or generation_config.forced_bos_token_id is None)
+ else begin_index + 1
+ )
+ if generation_config.forced_decoder_ids is not None:
+ begin_index += generation_config.forced_decoder_ids[-1][
+ 0
+ ] # generation starts after the last token that is forced
+ processors.append(
+ TFSuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index)
+ )
+ if generation_config.forced_decoder_ids is not None:
+ processors.append(TFForceTokensLogitsProcessor(generation_config.forced_decoder_ids))
+
+ processors = self._merge_criteria_processor_list(processors, logits_processor)
+ return processors
+
+ def _merge_criteria_processor_list(
+ self,
+ default_list: TFLogitsProcessorList,
+ custom_list: TFLogitsProcessorList,
+ ) -> TFLogitsProcessorList:
+ if len(custom_list) == 0:
+ return default_list
+ for default in default_list:
+ for custom in custom_list:
+ if type(custom) is type(default):
+ object_type = "logits processor"
+ raise ValueError(
+ f"A custom {object_type} of type {type(custom)} with values {custom} has been passed to"
+ f" `generate`, but it has already been created with the values {default}. {default} has been"
+ " created by passing the corresponding arguments to generate or by the model's config default"
+ f" values. If you just want to change the default values of {object_type} consider passing"
+ f" them as arguments to `generate` instead of using a custom {object_type}."
+ )
+ default_list.extend(custom_list)
+ return default_list
+
+ def greedy_search(
+ self,
+ input_ids: tf.Tensor,
+ max_length: Optional[int] = None,
+ pad_token_id: Optional[int] = None,
+ eos_token_id: Optional[int] = None,
+ logits_processor: Optional[TFLogitsProcessorList] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ output_scores: Optional[bool] = None,
+ return_dict_in_generate: Optional[bool] = None,
+ **model_kwargs,
+ ) -> Union[TFGreedySearchOutput, tf.Tensor]:
+ r"""
+ Generates sequences for models with a language modeling head using greedy decoding.
+
+ Parameters:
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
+ The sequence used as a prompt for the generation.
+ logits_processor (`TFLogitsProcessorList`, *optional*):
+ An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ max_length (`int`, *optional*, defaults to 20):
+ The maximum length of the sequence to be generated.
+ pad_token_id (`int`, *optional*):
+ The id of the *padding* token.
+ eos_token_id (`Union[int, List[int]]`, *optional*):
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
+ output_attentions (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more details.
+ output_hidden_states (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
+ for more details.
+ output_scores (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
+ return_dict_in_generate (`bool`, *optional*, defaults to `False`):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+ model_kwargs:
+ Additional model specific keyword arguments will be forwarded to the `call` function of the model. If
+ model is an encoder-decoder model the kwargs should include `encoder_outputs`.
+
+ Return:
+ [`~generation.TFGreedySearchDecoderOnlyOutput`], [`~generation.TFGreedySearchEncoderDecoderOutput`] or
+ `tf.Tensor`: A `tf.Tensor` containing the generated tokens (default behaviour) or a
+ [`~generation.TFGreedySearchDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
+ `return_dict_in_generate=True` or a [`~generation.TFGreedySearchEncoderDecoderOutput`] if
+ `model.config.is_encoder_decoder=True`.
+
+ Examples:
+
+ ```python
+ >>> from transformers import (
+ ... AutoTokenizer,
+ ... TFAutoModelForCausalLM,
+ ... TFLogitsProcessorList,
+ ... TFMinLengthLogitsProcessor,
+ ... )
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
+ >>> model = TFAutoModelForCausalLM.from_pretrained("openai-community/gpt2")
+
+ >>> # set pad_token_id to eos_token_id because GPT2 does not have a PAD token
+ >>> model.generation_config.pad_token_id = model.generation_config.eos_token_id
+
+ >>> input_prompt = "Today is a beautiful day, and"
+ >>> input_ids = tokenizer(input_prompt, return_tensors="tf").input_ids
+
+ >>> # instantiate logits processors
+ >>> logits_processor = TFLogitsProcessorList(
+ ... [
+ ... TFMinLengthLogitsProcessor(15, eos_token_id=model.generation_config.eos_token_id),
+ ... ]
+ ... )
+
+ >>> outputs = model.greedy_search(input_ids, logits_processor=logits_processor)
+ >>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
+ ["Today is a beautiful day, and I'm so happy to be here. I'm so happy to"]
+ ```"""
+
+ # 1. init greedy_search values
+ logits_processor = logits_processor if logits_processor is not None else TFLogitsProcessorList()
+
+ max_length = max_length if max_length is not None else self.generation_config.max_length
+ pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
+ eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
+ if isinstance(eos_token_id, int):
+ eos_token_id = [eos_token_id]
+ output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
+ output_attentions = (
+ output_attentions if output_attentions is not None else self.generation_config.output_attentions
+ )
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
+ )
+ return_dict_in_generate = (
+ return_dict_in_generate
+ if return_dict_in_generate is not None
+ else self.generation_config.return_dict_in_generate
+ )
+ use_cache = model_kwargs.pop("use_cache", self.generation_config.use_cache)
+ use_xla = not tf.executing_eagerly()
+ # TODO (Joao): fix cache format or find programatic way to detect cache index
+ # GPT2 and other models has a slightly different cache structure, with a different batch axis
+ model_name = str(self.decoder) if "EncoderDecoder" in str(self) else str(self)
+ cache_batch_axis = 1 if any(model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")) else 0
+ # some models, like XLNet, need more than the last token in the presence of past_key_values
+ needs_full_input = "use_mems" in set(inspect.signature(self.prepare_inputs_for_generation).parameters.keys())
+
+ # 2. init `attentions`, `hidden_states`, and `scores` tuples
+ scores = [] if (return_dict_in_generate and output_scores) else None
+ decoder_attentions = [] if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = [] if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = [] if (return_dict_in_generate and output_hidden_states) else None
+
+ # 3. init tensors to use for "xla-compileable" generate function
+ batch_size, cur_len = shape_list(input_ids)
+
+ # initialize `generated` (`input_ids` padded with `pad_token_id`), `finished_sequences`
+ input_ids_padding = tf.ones((batch_size, max_length - cur_len), dtype=tf.int32) * (pad_token_id or 0)
+ generated = tf.concat([input_ids, input_ids_padding], axis=-1)
+ finished_sequences = tf.zeros((batch_size,), dtype=tf.bool)
+
+ # 4. define "xla-compile-able" stop-condition and auto-regressive function
+ # define condition fn
+ def greedy_search_cond_fn(generated, finished_sequences, cur_len, model_kwargs):
+ """state termination condition fn."""
+ return ~tf.reduce_all(finished_sequences)
+
+ # define condition fn
+ def greedy_search_body_fn(generated, finished_sequences, cur_len, model_kwargs):
+ """state update fn."""
+ if model_kwargs.get("past_key_values") is None or needs_full_input:
+ input_ids = generated[:, :cur_len]
+ else:
+ input_ids = tf.expand_dims(generated[:, cur_len - 1], -1)
+ model_inputs = self.prepare_inputs_for_generation(input_ids, use_cache=use_cache, **model_kwargs)
+ # forward pass to get next token logits
+ model_outputs = self(
+ **model_inputs,
+ return_dict=True,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ )
+ next_token_logits = model_outputs.logits[:, -1]
+
+ # pre-process distribution
+ next_tokens_scores = logits_processor(generated, next_token_logits, cur_len)
+
+ # Store scores, attentions and hidden_states when required
+ if not use_xla and return_dict_in_generate:
+ if output_scores:
+ scores.append(next_tokens_scores)
+ if output_attentions and self.config.is_encoder_decoder:
+ decoder_attentions.append(model_outputs.decoder_attentions)
+ elif output_attentions and not self.config.is_encoder_decoder:
+ decoder_attentions.append(model_outputs.attentions)
+ if self.config.is_encoder_decoder:
+ cross_attentions.append(model_outputs.cross_attentions)
+
+ if output_hidden_states and self.config.is_encoder_decoder:
+ decoder_hidden_states.append(model_outputs.decoder_hidden_states)
+ elif output_hidden_states and self.config.is_encoder_decoder:
+ decoder_hidden_states.append(model_outputs.hidden_states)
+
+ # argmax
+ next_tokens = tf.argmax(next_tokens_scores, axis=-1, output_type=tf.int32)
+
+ if eos_token_id is not None:
+ if pad_token_id is None:
+ raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
+ unfinished_seq = 1 - tf.cast(finished_sequences, tf.int32)
+ next_tokens = next_tokens * unfinished_seq + pad_token_id * (1 - unfinished_seq)
+ next_token_is_eos = tf.math.reduce_any(
+ tf.equal(
+ tf.broadcast_to(next_tokens, (len(eos_token_id), batch_size)), tf.expand_dims(eos_token_id, -1)
+ ),
+ axis=0,
+ )
+ finished_sequences = finished_sequences | next_token_is_eos
+
+ # update `generated` and `cur_len`
+ update_indices = tf.stack([tf.range(batch_size), tf.broadcast_to(cur_len, [batch_size])], axis=-1)
+ generated = tf.tensor_scatter_nd_update(tensor=generated, indices=update_indices, updates=next_tokens)
+ cur_len += 1
+
+ # update model_kwargs
+ if use_xla:
+ model_kwargs = self._update_model_kwargs_for_xla_generation(
+ model_outputs=model_outputs,
+ model_kwargs=model_kwargs,
+ cur_len=cur_len,
+ max_length=max_length,
+ batch_size=batch_size,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ batch_axis=cache_batch_axis,
+ )
+ else:
+ model_kwargs = self._update_model_kwargs_for_generation(
+ model_outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
+ )
+ # if we don't cache past_key_values key values we need the whole input
+ if model_kwargs.get("past_key_values", None) is None:
+ # let's throw out `past_key_values` since we don't want `None` tensors
+ model_kwargs.pop("past_key_values", None)
+
+ return generated, finished_sequences, cur_len, model_kwargs
+
+ # 5. run generation
+ # 1st generation step has to be run before to initialize `past_key_values`
+ generated, finished_sequences, cur_len, model_kwargs = greedy_search_body_fn(
+ generated, finished_sequences, cur_len, model_kwargs
+ )
+
+ # 2-to-n generation steps can then be run in autoregressive fashion
+ # only in case 1st generation step does NOT yield EOS token though
+ maximum_iterations = max_length - cur_len
+ generated, _, cur_len, _ = tf.while_loop(
+ greedy_search_cond_fn,
+ greedy_search_body_fn,
+ (generated, finished_sequences, cur_len, model_kwargs),
+ maximum_iterations=maximum_iterations,
+ )
+
+ # 6. prepare outputs
+ if not use_xla:
+ # cut for backward compatibility
+ generated = generated[:, :cur_len]
+
+ if return_dict_in_generate:
+ if self.config.is_encoder_decoder:
+ # if model is an encoder-decoder, retrieve encoder attention weights
+ # and hidden states
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
+ encoder_hidden_states = (
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
+ )
+
+ scores = tuple(scores) if scores is not None else None
+ decoder_attentions = tuple(decoder_attentions) if decoder_attentions is not None else None
+ cross_attentions = tuple(cross_attentions) if cross_attentions is not None else None
+ decoder_hidden_states = tuple(decoder_hidden_states) if decoder_hidden_states is not None else None
+
+ return TFGreedySearchEncoderDecoderOutput(
+ sequences=generated,
+ scores=scores,
+ encoder_attentions=encoder_attentions,
+ encoder_hidden_states=encoder_hidden_states,
+ decoder_attentions=decoder_attentions,
+ cross_attentions=cross_attentions,
+ decoder_hidden_states=decoder_hidden_states,
+ )
+ else:
+ return TFGreedySearchDecoderOnlyOutput(
+ sequences=generated,
+ scores=scores,
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ )
+ else:
+ return generated
+
+ def sample(
+ self,
+ input_ids: tf.Tensor,
+ logits_processor: Optional[TFLogitsProcessorList] = None,
+ logits_warper: Optional[TFLogitsProcessorList] = None,
+ max_length: Optional[int] = None,
+ pad_token_id: Optional[int] = None,
+ eos_token_id: Optional[int] = None,
+ seed: Optional[Tuple[int, int]] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ output_scores: Optional[bool] = None,
+ return_dict_in_generate: Optional[bool] = None,
+ **model_kwargs,
+ ) -> Union[TFSampleOutput, tf.Tensor]:
+ r"""
+ Generates sequences for models with a language modeling head using multinomial sampling.
+
+ Parameters:
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
+ The sequence used as a prompt for the generation.
+ logits_processor (`TFLogitsProcessorList`, *optional*):
+ An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ logits_warper (`TFLogitsProcessorList`, *optional*):
+ An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsWarper`]
+ used to warp the prediction score distribution of the language modeling head applied before multinomial
+ sampling at each generation step.
+ max_length (`int`, *optional*, defaults to 20):
+ The maximum length of the sequence to be generated.
+ pad_token_id (`int`, *optional*):
+ The id of the *padding* token.
+ eos_token_id (`Union[int, List[int]]`, *optional*):
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
+ seed (`List[int]`, *optional*):
+ Random seed to control sampling, containing two integers, used when `do_sample` is `True`. See the
+ `seed` argument from stateless functions in `tf.random`.
+ output_attentions (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more details.
+ output_hidden_states (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
+ for more details.
+ output_scores (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
+ return_dict_in_generate (`bool`, *optional*, defaults to `False`):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+ model_kwargs:
+ Additional model specific kwargs will be forwarded to the `call` function of the model. If model is an
+ encoder-decoder model the kwargs should include `encoder_outputs`.
+
+ Return:
+ [`~generation.TFSampleDecoderOnlyOutput`], [`~generation.TFSampleEncoderDecoderOutput`] or `tf.Tensor`: A
+ `tf.Tensor` containing the generated tokens (default behaviour) or a
+ [`~generation.TFSampleDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
+ `return_dict_in_generate=True` or a [`~generation.TFSampleEncoderDecoderOutput`] if
+ `model.config.is_encoder_decoder=True`.
+
+ Examples:
+
+ ```python
+ >>> import tensorflow as tf
+ >>> from transformers import (
+ ... AutoTokenizer,
+ ... TFAutoModelForCausalLM,
+ ... TFLogitsProcessorList,
+ ... TFMinLengthLogitsProcessor,
+ ... TFTopKLogitsWarper,
+ ... TFTemperatureLogitsWarper,
+ ... )
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
+ >>> model = TFAutoModelForCausalLM.from_pretrained("openai-community/gpt2")
+
+ >>> # set pad_token_id to eos_token_id because GPT2 does not have a EOS token
+ >>> model.generation_config.pad_token_id = model.generation_config.eos_token_id
+
+ >>> input_prompt = "Today is a beautiful day, and"
+ >>> input_ids = tokenizer(input_prompt, return_tensors="tf").input_ids
+
+ >>> # instantiate logits processors
+ >>> logits_processor = TFLogitsProcessorList(
+ ... [
+ ... TFMinLengthLogitsProcessor(15, eos_token_id=model.generation_config.eos_token_id),
+ ... ]
+ ... )
+ >>> # instantiate logits processors
+ >>> logits_warper = TFLogitsProcessorList(
+ ... [
+ ... TFTopKLogitsWarper(50),
+ ... TFTemperatureLogitsWarper(0.7),
+ ... ]
+ ... )
+
+ >>> tf.random.set_seed(0)
+ >>> outputs = model.sample(input_ids, logits_processor=logits_processor, logits_warper=logits_warper)
+
+ >>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
+ ['Today is a beautiful day, and I love my country. But when I look at Donald Trump,']
+ ```"""
+
+ # 1. init greedy_search values
+ logits_processor = logits_processor if logits_processor is not None else TFLogitsProcessorList()
+ logits_warper = logits_warper if logits_warper is not None else TFLogitsProcessorList()
+
+ max_length = max_length if max_length is not None else self.generation_config.max_length
+ pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
+ eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
+ if isinstance(eos_token_id, int):
+ eos_token_id = [eos_token_id]
+ output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
+ output_attentions = (
+ output_attentions if output_attentions is not None else self.generation_config.output_attentions
+ )
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
+ )
+ return_dict_in_generate = (
+ return_dict_in_generate
+ if return_dict_in_generate is not None
+ else self.generation_config.return_dict_in_generate
+ )
+ use_cache = model_kwargs.pop("use_cache", self.generation_config.use_cache)
+ use_xla = not tf.executing_eagerly()
+ # TODO (Joao): fix cache format or find programatic way to detect cache index
+ # GPT2 and other models has a slightly different cache structure, with a different batch axis
+ model_name = str(self.decoder) if "EncoderDecoder" in str(self) else str(self)
+ cache_batch_axis = 1 if any(model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")) else 0
+ # some models, like XLNet, need more than the last token in the presence of past_key_values
+ needs_full_input = "use_mems" in set(inspect.signature(self.prepare_inputs_for_generation).parameters.keys())
+
+ # 2. init `attentions`, `hidden_states`, and `scores` tuples
+ scores = [] if (return_dict_in_generate and output_scores) else None
+ decoder_attentions = [] if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = [] if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = [] if (return_dict_in_generate and output_hidden_states) else None
+
+ # 3. init tensors to use for "xla-compileable" generate function
+ batch_size, cur_len = shape_list(input_ids)
+
+ # initialize `generated` (pre-populated with `pad_token_id`), `finished_sequences`
+ input_ids_padding = tf.ones((batch_size, max_length - cur_len), dtype=tf.int32) * (pad_token_id or 0)
+ generated = tf.concat([input_ids, input_ids_padding], axis=-1)
+ finished_sequences = tf.zeros((batch_size,), dtype=tf.bool)
+
+ # 4. define "xla-compile-able" stop-condition and auto-regressive function
+ def sample_cond_fn(generated, finished_sequences, cur_len, model_kwargs):
+ return ~tf.reduce_all(finished_sequences)
+
+ def sample_body_fn(generated, finished_sequences, cur_len, model_kwargs):
+ if model_kwargs.get("past_key_values") is None or needs_full_input:
+ input_ids = generated[:, :cur_len]
+ else:
+ input_ids = tf.expand_dims(generated[:, cur_len - 1], -1)
+ model_inputs = self.prepare_inputs_for_generation(input_ids, use_cache=use_cache, **model_kwargs)
+ # forward pass to get next token logits
+ model_outputs = self(
+ **model_inputs,
+ return_dict=True,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ )
+ next_token_logits = model_outputs.logits[:, -1]
+
+ # pre-process distribution
+ next_tokens_scores = logits_processor(generated, next_token_logits, cur_len)
+ next_tokens_scores = logits_warper(generated, next_tokens_scores, cur_len)
+
+ # Store scores, attentions and hidden_states when required
+ if not use_xla and return_dict_in_generate:
+ if output_scores:
+ scores.append(next_tokens_scores)
+ if output_attentions and self.config.is_encoder_decoder:
+ decoder_attentions.append(model_outputs.decoder_attentions)
+ elif output_attentions and not self.config.is_encoder_decoder:
+ decoder_attentions.append(model_outputs.attentions)
+ if self.config.is_encoder_decoder:
+ cross_attentions.append(model_outputs.cross_attentions)
+
+ if output_hidden_states and self.config.is_encoder_decoder:
+ decoder_hidden_states.append(model_outputs.decoder_hidden_states)
+ elif output_hidden_states and self.config.is_encoder_decoder:
+ decoder_hidden_states.append(model_outputs.hidden_states)
+
+ # sample
+ if seed is not None:
+ sample_seed = seed
+ else:
+ sample_seed = tf.experimental.numpy.random.randint(tf.int32.min, tf.int32.max, (2,), dtype=tf.int32)
+ next_tokens = tf.squeeze(
+ tf.random.stateless_categorical(
+ logits=next_tokens_scores, num_samples=1, seed=sample_seed, dtype=tf.int32
+ ),
+ axis=1,
+ )
+
+ if eos_token_id is not None:
+ if pad_token_id is None:
+ raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
+ unfinished_seq = 1 - tf.cast(finished_sequences, tf.int32)
+ next_tokens = next_tokens * unfinished_seq + pad_token_id * (1 - unfinished_seq)
+ next_token_is_eos = tf.math.reduce_any(
+ tf.equal(
+ tf.broadcast_to(next_tokens, (len(eos_token_id), batch_size)), tf.expand_dims(eos_token_id, -1)
+ ),
+ axis=0,
+ )
+ finished_sequences = finished_sequences | next_token_is_eos
+
+ # update `generated` and `cur_len`
+ update_indices = tf.stack([tf.range(batch_size), tf.broadcast_to(cur_len, [batch_size])], axis=-1)
+ generated = tf.tensor_scatter_nd_update(tensor=generated, indices=update_indices, updates=next_tokens)
+ cur_len += 1
+
+ # update model_kwargs
+ if use_xla:
+ model_kwargs = self._update_model_kwargs_for_xla_generation(
+ model_outputs=model_outputs,
+ model_kwargs=model_kwargs,
+ cur_len=cur_len,
+ max_length=max_length,
+ batch_size=batch_size,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ batch_axis=cache_batch_axis,
+ )
+ else:
+ model_kwargs = self._update_model_kwargs_for_generation(
+ model_outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
+ )
+ # if we don't cache past_key_values key values we need the whole input
+ if model_kwargs.get("past_key_values", None) is None:
+ # let's throw out `past_key_values` since we don't want `None` tensors
+ model_kwargs.pop("past_key_values", None)
+
+ return generated, finished_sequences, cur_len, model_kwargs
+
+ # 5. run generation
+ # 1st generation step has to be run before to initialize `past_key_values`
+ generated, finished_sequences, cur_len, model_kwargs = sample_body_fn(
+ generated, finished_sequences, cur_len, model_kwargs
+ )
+
+ # 2-to-n generation steps can then be run in autoregressive fashion
+ # only in case 1st generation step does NOT yield EOS token though
+ maximum_iterations = max_length - cur_len
+ generated, _, cur_len, _ = tf.while_loop(
+ sample_cond_fn,
+ sample_body_fn,
+ (generated, finished_sequences, cur_len, model_kwargs),
+ maximum_iterations=maximum_iterations,
+ )
+
+ # 6. prepare outputs
+ if not use_xla:
+ # cut for backward compatibility
+ generated = generated[:, :cur_len]
+
+ if return_dict_in_generate:
+ if self.config.is_encoder_decoder:
+ # if model is an encoder-decoder, retrieve encoder attention weights
+ # and hidden states
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
+ encoder_hidden_states = (
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
+ )
+
+ scores = tuple(scores) if scores is not None else None
+ decoder_attentions = tuple(decoder_attentions) if decoder_attentions is not None else None
+ cross_attentions = tuple(cross_attentions) if cross_attentions is not None else None
+ decoder_hidden_states = tuple(decoder_hidden_states) if decoder_hidden_states is not None else None
+
+ return TFSampleEncoderDecoderOutput(
+ sequences=generated,
+ scores=scores,
+ encoder_attentions=encoder_attentions,
+ encoder_hidden_states=encoder_hidden_states,
+ decoder_attentions=decoder_attentions,
+ cross_attentions=cross_attentions,
+ decoder_hidden_states=decoder_hidden_states,
+ )
+ else:
+ return TFSampleDecoderOnlyOutput(
+ sequences=generated,
+ scores=scores,
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ )
+ else:
+ return generated
+
+ @staticmethod
+ def _gather_beams(nested, beam_indices, batch_axis=0):
+ """Gathers the beam slices indexed by beam_indices into new beam array."""
+
+ def gather_fn(tensor):
+ if batch_axis > 0:
+ # pushes all dimentions before the batch to the end, so we get (batch, beam_id, ...)
+ perm = tf.concat((tf.range(tf.rank(tensor))[batch_axis:], tf.range(batch_axis)), axis=0)
+ tensor = tf.transpose(tensor, perm=perm)
+
+ gathered_tensor = tf.gather(params=tensor, indices=beam_indices, axis=1, batch_dims=1)
+ if batch_axis > 0:
+ # transposes back to the original dimensions
+ perm = tf.concat((tf.range(tf.rank(tensor))[batch_axis:], tf.range(batch_axis)), axis=0)
+ perm = tf.math.invert_permutation(perm)
+ gathered_tensor = tf.transpose(gathered_tensor, perm=perm)
+
+ return gathered_tensor
+
+ return tf.nest.map_structure(gather_fn, nested)
+
+ def beam_search(
+ self,
+ input_ids: tf.Tensor,
+ do_sample: bool = False,
+ max_length: Optional[int] = None,
+ pad_token_id: Optional[int] = None,
+ eos_token_id: Optional[int] = None,
+ length_penalty: Optional[float] = None,
+ early_stopping: Optional[Union[bool, str]] = None,
+ logits_processor: Optional[TFLogitsProcessorList] = None,
+ logits_warper: Optional[TFLogitsProcessorList] = None,
+ num_return_sequences: Optional[int] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ output_scores: Optional[bool] = None,
+ return_dict_in_generate: Optional[bool] = None,
+ **model_kwargs,
+ ) -> Union[TFBeamSearchOutput, TFBeamSampleOutput, tf.Tensor]:
+ r"""
+ Generates sequences for models with a language modeling head using beam search. If `do_sample` is `False`, uses
+ a greedy approach, otherwise does multinomial sampling without replacement.
+
+ Parameters:
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
+ The sequence used as a prompt for the generation.
+ do_sample (`bool`, *optional*, defaults to `False`):
+ Whether or not to use sampling ; use greedy decoding otherwise.
+ max_length (`int`, *optional*, defaults to 20):
+ The maximum length of the sequence to be generated.
+ pad_token_id (`int`, *optional*):
+ The id of the *padding* token.
+ eos_token_id (`Union[int, List[int]]`, *optional*):
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
+ length_penalty (`float`, *optional*, defaults to 1.0):
+ Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent
+ to the sequence length, which in turn is used to divide the score of the sequence. Since the score is
+ the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences,
+ while `length_penalty` < 0.0 encourages shorter sequences.
+ early_stopping (`bool` or `str`, *optional*, defaults to `False`):
+ Controls the stopping condition for beam-based methods, like beam-search. It accepts the following
+ values: `True`, where the generation stops as soon as there are `num_beams` complete candidates;
+ `False`, where an heuristic is applied and the generation stops when is it very unlikely to find better
+ candidates; `"never"`, where the beam search procedure only stops when there cannot be better
+ candidates (canonical beam search algorithm).
+ logits_processor (`[TFLogitsProcessorList]`, *optional*):
+ An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ logits_warper (`TFLogitsProcessorList`, *optional*):
+ An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsWarper`]
+ used to warp the prediction score distribution of the language modeling head applied before multinomial
+ sampling at each generation step.
+ num_return_sequences(`int`, *optional*, defaults to 1):
+ The number of independently computed returned sequences for each element in the batch.
+ output_attentions (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more details.
+ output_hidden_states (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
+ for more details.
+ return_dict_in_generate (`bool`, *optional*, defaults to `False`):
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
+ model_kwargs:
+ Additional model specific kwargs will be forwarded to the `call` function of the model. If model is an
+ encoder-decoder model the kwargs should include `encoder_outputs`.
+
+ Return:
+ [`~generation.TFBeamSearchDecoderOnlyOutput`], [`~generation.TFBeamSearchEncoderDecoderOutput`] or
+ `tf.Tensor`: A `tf.Tensor` containing the generated tokens (default behaviour) or a
+ [`~generation.TFBeamSearchDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
+ `return_dict_in_generate=True` or a [`~generation.TFBeamSearchEncoderDecoderOutput`] if
+ `model.config.is_encoder_decoder=True`.
+
+ Examples:
+
+ ```python
+ >>> from transformers import (
+ ... AutoTokenizer,
+ ... TFAutoModelForSeq2SeqLM,
+ ... TFLogitsProcessorList,
+ ... TFMinLengthLogitsProcessor,
+ ... )
+ >>> import tensorflow as tf
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-base")
+ >>> model = TFAutoModelForSeq2SeqLM.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="tf").input_ids
+
+ >>> # lets run beam search using 3 beams
+ >>> num_beams = 3
+ >>> # define decoder start token ids
+ >>> input_ids = tf.ones((1, num_beams, 1), dtype=tf.int32)
+ >>> input_ids = input_ids * model.generation_config.decoder_start_token_id
+
+ >>> # add encoder_outputs to model keyword arguments
+ >>> encoder_outputs = model.get_encoder()(encoder_input_ids, return_dict=True)
+ >>> encoder_outputs.last_hidden_state = tf.repeat(
+ ... tf.expand_dims(encoder_outputs.last_hidden_state, axis=0), num_beams, axis=1
+ ... )
+ >>> model_kwargs = {"encoder_outputs": encoder_outputs}
+
+ >>> # instantiate logits processors
+ >>> logits_processor = TFLogitsProcessorList(
+ ... [TFMinLengthLogitsProcessor(5, eos_token_id=model.generation_config.eos_token_id)]
+ ... )
+
+ >>> outputs = model.beam_search(input_ids, logits_processor=logits_processor, **model_kwargs)
+ >>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
+ ['Wie alt bist du?']
+ ```"""
+
+ def flatten_beam_dim(tensor, batch_axis=0):
+ """Flattens the first two dimensions of a non-scalar array."""
+ shape = shape_list(tensor)
+ return tf.reshape(
+ tensor,
+ shape[:batch_axis] + [shape[batch_axis] * shape[batch_axis + 1]] + shape[batch_axis + 2 :],
+ )
+
+ def unflatten_beam_dim(tensor, num_beams, batch_axis=0):
+ """Unflattens the first, flat batch*beam dimension of a non-scalar array."""
+ shape = shape_list(tensor)
+ return tf.reshape(tensor, shape[:batch_axis] + [-1, num_beams] + shape[batch_axis + 1 :])
+
+ # 1. init beam_search values
+ logits_processor = logits_processor if logits_processor is not None else TFLogitsProcessorList()
+ logits_warper = logits_warper if logits_warper is not None else TFLogitsProcessorList()
+
+ max_length = max_length if max_length is not None else self.generation_config.max_length
+ pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
+ eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
+ if isinstance(eos_token_id, int):
+ eos_token_id = [eos_token_id]
+ num_return_sequences = (
+ num_return_sequences if num_return_sequences is not None else self.generation_config.num_return_sequences
+ )
+
+ output_attentions = (
+ output_attentions if output_attentions is not None else self.generation_config.output_attentions
+ )
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
+ )
+ output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
+ return_dict_in_generate = (
+ return_dict_in_generate
+ if return_dict_in_generate is not None
+ else self.generation_config.return_dict_in_generate
+ )
+
+ length_penalty = length_penalty if length_penalty is not None else self.generation_config.length_penalty
+ early_stopping = early_stopping if early_stopping is not None else self.generation_config.early_stopping
+
+ use_cache = model_kwargs.pop("use_cache", self.generation_config.use_cache)
+ use_xla = not tf.executing_eagerly()
+ # TODO (Joao): fix cache format or find programatic way to detect cache index
+ # GPT2 and other models has a slightly different cache structure, with a different batch axis
+ model_name = str(self.decoder) if "EncoderDecoder" in str(self) else str(self)
+ cache_batch_axis = 1 if any(model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")) else 0
+ # some models, like XLNet, need more than the last token in the presence of past_key_values
+ needs_full_input = "use_mems" in set(inspect.signature(self.prepare_inputs_for_generation).parameters.keys())
+
+ # 2. init `attentions`, `hidden_states`, and `scores` tuples
+ all_scores = [] if (return_dict_in_generate and output_scores) else None
+ decoder_attentions = [] if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = [] if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = [] if (return_dict_in_generate and output_hidden_states) else None
+
+ # 3. init tensors to use for "xla-compileable" generate function
+ batch_size, num_beams, cur_len = shape_list(input_ids)
+ # store the prompt length of decoder
+ decoder_prompt_len = cur_len
+
+ # per batch, beam-item holding current token in loop, pre-populated with `pad_token_id`
+ input_ids_padding = tf.ones((batch_size, num_beams, max_length - cur_len), dtype=tf.int32) * (
+ pad_token_id or 0
+ )
+ running_sequences = tf.concat([input_ids, input_ids_padding], axis=-1)
+ sequences = tf.ones((batch_size, num_beams, max_length), dtype=tf.int32) * (pad_token_id or 0)
+
+ # per batch,beam-item state bit indicating if sentence has finished.
+ is_sent_finished = tf.zeros((batch_size, num_beams), dtype=tf.bool)
+
+ # per batch, beam-item score, logprobs
+ running_scores = tf.tile(
+ tf.expand_dims(tf.convert_to_tensor([0.0] + [-1.0e9] * (num_beams - 1)), axis=0), [batch_size, 1]
+ )
+ scores = tf.ones((batch_size, num_beams)) * -1.0e9
+
+ # per batch beam indices
+ running_beam_indices = tf.ones((batch_size, num_beams, max_length - decoder_prompt_len), dtype=tf.int32) * -1
+ beam_indices = tf.ones((batch_size, num_beams, max_length - decoder_prompt_len), dtype=tf.int32) * -1
+
+ # flatten beam dim
+ if "encoder_outputs" in model_kwargs:
+ model_kwargs["encoder_outputs"]["last_hidden_state"] = flatten_beam_dim(
+ model_kwargs["encoder_outputs"]["last_hidden_state"]
+ )
+ if "attention_mask" in model_kwargs:
+ model_kwargs["attention_mask"] = flatten_beam_dim(model_kwargs["attention_mask"])
+
+ # 4. define "xla-compile-able" stop-condition and auto-regressive function
+ # define stop-condition and auto-regressive function
+ def beam_search_cond_fn(
+ cur_len,
+ running_sequences,
+ running_scores,
+ running_beam_indices,
+ sequences,
+ scores,
+ beam_indices,
+ is_sent_finished,
+ decoder_prompt_len,
+ model_kwargs,
+ ):
+ """
+ Beam Search termination condition function -- halts the generation loop if any of these conditions becomes
+ False
+ """
+ # 1. is less than max length?
+ not_max_length_yet = cur_len < max_length
+
+ # 2. can the new beams still improve?
+ # early_stopping == False -> apply heuristic = always get the best score from `cur_len - decoder_prompt_len`. See the discussion
+ # below for more details.
+ # https://github.com/huggingface/transformers/pull/20901#issuecomment-1369845565
+ # early_stopping == "never" -> compute the best score from max_length or cur_len, depending on the sign of
+ # length_penalty. Positive length_penalty favors longer sequences, thus we use max_length there.
+ if early_stopping == "never" and length_penalty > 0.0:
+ best_running_score = running_scores[:, :1] / ((max_length - decoder_prompt_len) ** length_penalty)
+ else:
+ best_running_score = running_scores[:, :1] / (
+ tf.cast(cur_len - decoder_prompt_len, dtype=tf.float32) ** length_penalty
+ )
+ worst_finished_score = tf.where(
+ is_sent_finished, tf.math.reduce_min(scores, axis=1, keepdims=True), -1.0e9
+ )
+ improvement_still_possible = tf.math.reduce_any(best_running_score > worst_finished_score)
+
+ # 3. is there still a beam that has not finished?
+ still_open_beam = ~(tf.math.reduce_all(is_sent_finished) & (early_stopping is True))
+
+ return not_max_length_yet & still_open_beam & improvement_still_possible
+
+ def beam_search_body_fn(
+ cur_len,
+ running_sequences,
+ running_scores,
+ running_beam_indices,
+ sequences,
+ scores,
+ beam_indices,
+ is_sent_finished,
+ decoder_prompt_len,
+ model_kwargs,
+ ):
+ """
+ Beam Search iterative update function -- each iteration adds a new token and updates the best sequences
+ seen so far
+ """
+ # 1. Forward current tokens
+ if model_kwargs.get("past_key_values") is None or needs_full_input:
+ input_ids = running_sequences[:, :, :cur_len]
+ else:
+ input_ids = tf.expand_dims(running_sequences[:, :, cur_len - 1], -1)
+ model_inputs = self.prepare_inputs_for_generation(
+ flatten_beam_dim(input_ids), use_cache=use_cache, **model_kwargs
+ )
+ model_outputs = self(
+ **model_inputs,
+ return_dict=True,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ )
+ logits = unflatten_beam_dim(model_outputs.logits[:, -1], num_beams)
+
+ # 2. Compute log probs
+ # get log probabilities from logits, process logits with processors (*e.g.* min_length, ...), and
+ # add new logprobs to existing running logprobs scores.
+ log_probs = tf.nn.log_softmax(logits)
+ log_probs = logits_processor(flatten_beam_dim(running_sequences), flatten_beam_dim(log_probs), cur_len)
+ log_probs = unflatten_beam_dim(log_probs, num_beams)
+ if do_sample:
+ log_probs = logits_warper(flatten_beam_dim(running_sequences), flatten_beam_dim(log_probs), cur_len)
+ log_probs = unflatten_beam_dim(log_probs, num_beams)
+ log_probs_processed = log_probs
+ log_probs = log_probs + tf.expand_dims(running_scores, axis=2)
+ vocab_size = log_probs.shape[2]
+ log_probs = tf.reshape(log_probs, (batch_size, num_beams * vocab_size))
+
+ # Store scores, attentions and hidden_states when required
+ if not use_xla and return_dict_in_generate:
+ if output_scores:
+ all_scores.append(
+ logits_warper(
+ flatten_beam_dim(running_sequences),
+ flatten_beam_dim(log_probs_processed),
+ cur_len,
+ )
+ )
+ if output_attentions and self.config.is_encoder_decoder:
+ decoder_attentions.append(model_outputs.decoder_attentions)
+ elif output_attentions and not self.config.is_encoder_decoder:
+ decoder_attentions.append(model_outputs.attentions)
+ if self.config.is_encoder_decoder:
+ cross_attentions.append(model_outputs.cross_attentions)
+
+ if output_hidden_states and self.config.is_encoder_decoder:
+ decoder_hidden_states.append(model_outputs.decoder_hidden_states)
+ elif output_hidden_states and self.config.is_encoder_decoder:
+ decoder_hidden_states.append(model_outputs.hidden_states)
+
+ # 3. Retrieve top-K
+ # Each item in batch has num_beams * vocab_size candidate sequences. For each item, get the top 2*k
+ # candidates with the highest log-probabilities. We gather the top 2*K beams here so that even if the
+ # best K sequences reach EOS simultaneously, we have another K sequences remaining to continue the live
+ # beam search.
+ # Gather the top 2*K scores from _all_ beams.
+ # Gather 2*k top beams.
+ # Recover the beam index by floor division.
+ # Recover token id by modulo division and expand Id array for broadcasting.
+ # Update sequences for the 2*K top-k new sequences.
+ beams_to_keep = 2 * num_beams
+ if do_sample:
+ topk_indices = sample_without_replacement(log_probs, beams_to_keep)
+ topk_log_probs = tf.gather(log_probs, topk_indices, axis=1, batch_dims=1)
+ else:
+ topk_log_probs, topk_indices = tf.math.top_k(log_probs, k=beams_to_keep)
+ topk_current_beam_indices = topk_indices // vocab_size
+ topk_running_beam_indices = self._gather_beams(running_beam_indices, topk_current_beam_indices)
+ topk_running_sequences = self._gather_beams(running_sequences, topk_current_beam_indices)
+ topk_ids = topk_indices % vocab_size
+
+ # writes the new token
+ indices_batch = tf.repeat(tf.range(batch_size), [beams_to_keep])
+ indices_beam = tf.tile(tf.range(beams_to_keep), [batch_size])
+ update_indices = tf.stack(
+ [indices_batch, indices_beam, tf.broadcast_to(cur_len, [batch_size * beams_to_keep])], axis=-1
+ )
+ topk_sequences = tf.tensor_scatter_nd_update(
+ tensor=topk_running_sequences,
+ indices=update_indices,
+ updates=tf.reshape(topk_ids, [batch_size * beams_to_keep]),
+ )
+
+ # we want to store the beam indices with batch information -> real beam index = beam index % num beams
+ batch_modified_indices = topk_current_beam_indices + tf.broadcast_to(
+ tf.expand_dims(tf.range(batch_size) * num_beams, axis=1), topk_current_beam_indices.shape
+ )
+ update_indices = tf.stack(
+ [
+ indices_batch,
+ indices_beam,
+ tf.broadcast_to(cur_len - decoder_prompt_len, [batch_size * beams_to_keep]),
+ ],
+ axis=-1,
+ )
+ topk_beam_indices = tf.tensor_scatter_nd_update(
+ tensor=topk_running_beam_indices,
+ indices=update_indices,
+ updates=tf.reshape(batch_modified_indices, [batch_size * beams_to_keep]),
+ )
+
+ # 4. Check which sequences have ended
+ # Update current sequences: Did the top `num_beams` sequences reach an end marker?
+ # To prevent these just finished sequences from being added to the current sequences
+ # set of active beam search sequences, set their log probs to a very large negative value.
+ if eos_token_id is None:
+ eos_in_next_token = tf.zeros(topk_sequences[:, :, cur_len].shape, dtype=tf.bool)
+ else:
+ eos_in_next_token = tf.math.reduce_any(
+ tf.equal(
+ tf.broadcast_to(
+ topk_sequences[:, :, cur_len],
+ [len(eos_token_id)] + topk_sequences[:, :, cur_len].shape,
+ ),
+ tf.expand_dims(tf.expand_dims(eos_token_id, -1), -1),
+ ),
+ axis=0,
+ )
+ did_topk_just_finished = eos_in_next_token & tf.broadcast_to(
+ tf.concat((tf.ones((num_beams), dtype=tf.bool), tf.zeros((num_beams), dtype=tf.bool)), axis=0),
+ shape_list(eos_in_next_token),
+ )
+
+ # non-top `num_beams` eos tokens can't be used to finish a beam, but the others can't be used in the next
+ # running sentences either
+ running_topk_log_probs = topk_log_probs + tf.cast(eos_in_next_token, tf.float32) * -1.0e9
+
+ # 5. Get running sequences scores for next
+ # Determine the top k beam indices (from top 2*k beams) from log probs and gather top k beams
+ # (from top 2*k beams).
+ next_topk_indices = tf.math.top_k(running_topk_log_probs, k=num_beams)[1]
+ next_running_sequences, next_running_scores, next_running_beam_indices = self._gather_beams(
+ [topk_sequences, running_topk_log_probs, topk_beam_indices], next_topk_indices
+ )
+
+ # 6. Process topk logits
+ # Further process log probs:
+ # - add length penalty
+ # - make sure no scores can be added anymore if beam is full
+ # - make sure still running sequences cannot be chosen as finalized beam
+ topk_log_probs = topk_log_probs / (
+ tf.cast(cur_len + 1 - decoder_prompt_len, dtype=tf.float32) ** length_penalty
+ )
+ beams_in_batch_are_full = tf.broadcast_to(
+ tf.math.reduce_all(is_sent_finished, axis=-1, keepdims=True), shape_list(did_topk_just_finished)
+ ) & (early_stopping is True)
+ add_penalty = ~did_topk_just_finished | beams_in_batch_are_full
+ topk_log_probs += tf.cast(add_penalty, tf.float32) * -1.0e9
+
+ # 7. Get scores, sequences, is sentence finished for next.
+ # Combine sequences, scores, and flags along the beam dimension and compare new finished sequence scores
+ # to existing finished scores and select the best from the new set of beams
+ merged_sequences = tf.concat([sequences, topk_sequences], axis=1)
+ merged_scores = tf.concat([scores, topk_log_probs], axis=1)
+ merged_beams = tf.concat([beam_indices, topk_beam_indices], axis=1)
+ merged_is_sent_finished = tf.concat([is_sent_finished, did_topk_just_finished], axis=1)
+ topk_merged_indices = tf.math.top_k(merged_scores, k=num_beams)[1]
+ next_sequences, next_scores, next_beam_indices, next_is_sent_finished = self._gather_beams(
+ [merged_sequences, merged_scores, merged_beams, merged_is_sent_finished], topk_merged_indices
+ )
+
+ # 8. Prepare data for the next iteration
+ # Determine the top k beam indices from the original set of all beams. With these, gather the top k
+ # beam-associated caches.
+ cur_len = cur_len + 1
+ if "past_key_values" in model_outputs:
+ cache = tf.nest.map_structure(
+ lambda tensor: unflatten_beam_dim(tensor, num_beams, batch_axis=cache_batch_axis),
+ model_outputs.past_key_values,
+ )
+ next_running_indices = self._gather_beams(topk_current_beam_indices, next_topk_indices)
+ next_cache = self._gather_beams(cache, next_running_indices, batch_axis=cache_batch_axis)
+ model_outputs["past_key_values"] = tf.nest.map_structure(
+ lambda tensor: flatten_beam_dim(tensor, batch_axis=cache_batch_axis), next_cache
+ )
+
+ if use_xla:
+ next_model_kwargs = self._update_model_kwargs_for_xla_generation(
+ model_outputs=model_outputs,
+ model_kwargs=model_kwargs,
+ cur_len=cur_len,
+ max_length=max_length,
+ batch_size=(batch_size * num_beams),
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ batch_axis=cache_batch_axis,
+ )
+ else:
+ next_model_kwargs = self._update_model_kwargs_for_generation(
+ model_outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
+ )
+
+ # if we don't cache past_key_values key values we need the whole input
+ if model_kwargs.get("past_key_values", None) is None:
+ # let's throw out `past_key_values` since we don't want `None` tensors
+ model_kwargs.pop("past_key_values", None)
+
+ return (
+ cur_len,
+ next_running_sequences,
+ next_running_scores,
+ next_running_beam_indices,
+ next_sequences,
+ next_scores,
+ next_beam_indices,
+ next_is_sent_finished,
+ decoder_prompt_len,
+ next_model_kwargs,
+ )
+
+ # 5. run generation
+ # 1st generation step has to be run before to initialize `past_key_values` (if active)
+ (
+ cur_len,
+ running_sequences,
+ running_scores,
+ running_beam_indices,
+ sequences,
+ scores,
+ beam_indices,
+ is_sent_finished,
+ decoder_prompt_len,
+ model_kwargs,
+ ) = beam_search_body_fn(
+ cur_len,
+ running_sequences,
+ running_scores,
+ running_beam_indices,
+ sequences,
+ scores,
+ beam_indices,
+ is_sent_finished,
+ decoder_prompt_len,
+ model_kwargs,
+ )
+
+ # 2-to-n generation steps can then be run in autoregressive fashion (only in case 1st generation step does
+ # NOT yield EOS token though)
+ maximum_iterations = max_length - cur_len
+ (
+ cur_len,
+ running_sequences,
+ running_scores,
+ running_beam_indices,
+ sequences,
+ scores,
+ beam_indices,
+ is_sent_finished,
+ decoder_prompt_len,
+ _,
+ ) = tf.while_loop(
+ beam_search_cond_fn,
+ beam_search_body_fn,
+ (
+ cur_len,
+ running_sequences,
+ running_scores,
+ running_beam_indices,
+ sequences,
+ scores,
+ beam_indices,
+ is_sent_finished,
+ decoder_prompt_len,
+ model_kwargs,
+ ),
+ maximum_iterations=maximum_iterations,
+ )
+
+ # 6. prepare outputs
+ # Account for the edge-case where there are no finished sequences for a particular batch item. If so, return
+ # running sequences for that batch item.
+ none_finished = tf.math.reduce_any(is_sent_finished, axis=1)
+ sequences = tf.where(none_finished[:, None, None], sequences, running_sequences)
+ beam_indices = tf.where(none_finished[:, None, None], beam_indices, running_beam_indices)
+
+ # Apply the length penalty so that running scores match the finalized scores if they are used
+ running_scores = running_scores / (tf.cast(cur_len - decoder_prompt_len, dtype=tf.float32) ** length_penalty)
+ scores = tf.where(none_finished[:, None], scores, running_scores)
+
+ # Take best beams for each batch (the score is sorted in descending order)
+ sequences = flatten_beam_dim(sequences[:, :num_return_sequences, :])
+ scores = flatten_beam_dim(scores[:, :num_return_sequences])
+ beam_indices = flatten_beam_dim(beam_indices[:, :num_return_sequences, :])
+
+ if not use_xla:
+ # Cut for backward compatibility
+ sequences = sequences[:, :cur_len]
+ beam_indices = beam_indices[:, : cur_len - decoder_prompt_len]
+
+ if return_dict_in_generate:
+ if self.config.is_encoder_decoder:
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
+ encoder_hidden_states = (
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
+ )
+
+ output_cls = TFBeamSampleEncoderDecoderOutput if do_sample else TFBeamSearchEncoderDecoderOutput
+ return output_cls(
+ sequences=sequences,
+ sequences_scores=scores,
+ scores=all_scores,
+ beam_indices=beam_indices,
+ encoder_attentions=encoder_attentions,
+ encoder_hidden_states=encoder_hidden_states,
+ decoder_attentions=decoder_attentions,
+ cross_attentions=cross_attentions,
+ decoder_hidden_states=decoder_hidden_states,
+ )
+ else:
+ output_cls = TFBeamSampleDecoderOnlyOutput if do_sample else TFBeamSearchDecoderOnlyOutput
+ return output_cls(
+ sequences=sequences,
+ sequences_scores=scores,
+ scores=all_scores,
+ beam_indices=beam_indices,
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ )
+ else:
+ return sequences
+
+ def contrastive_search(
+ self,
+ input_ids: tf.Tensor,
+ top_k: Optional[int] = 1,
+ penalty_alpha: Optional[float] = 0,
+ logits_processor: Optional[TFLogitsProcessorList] = None,
+ logits_warper: Optional[TFLogitsProcessorList] = None,
+ max_length: Optional[int] = None,
+ pad_token_id: Optional[int] = None,
+ eos_token_id: Optional[int] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ output_scores: Optional[bool] = None,
+ return_dict_in_generate: Optional[bool] = None,
+ **model_kwargs,
+ ) -> Union[TFContrastiveSearchOutput, tf.Tensor]:
+ r"""
+ Generates sequences of token ids for models with a language modeling head using **contrastive search** and can
+ be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
+
+ Parameters:
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
+ The sequence used as a prompt for the generation.
+ top_k (`int`, *optional*, defaults to 1):
+ The size of the candidate set that is used to re-rank for contrastive search
+ penalty_alpha (`float`, *optional*, defaults to 0):
+ The degeneration penalty for contrastive search; activate when it is larger than 0
+ logits_processor (`TFLogitsProcessorList`, *optional*):
+ An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ logits_warper (`TFLogitsProcessorList`, *optional*):
+ An instance of [`TFLogitsProcessorList`]. List of instances of class derived from [`TFLogitsWarper`]
+ used to warp the prediction score distribution of the language modeling head applied before multinomial
+ sampling at each generation step.
+ max_length (`int`, *optional*, defaults to 20):
+ The maximum length of the sequence to be generated.
+ pad_token_id (`int`, *optional*):
+ The id of the *padding* token.
+ eos_token_id (`Union[int, List[int]]`, *optional*):
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
+ output_attentions (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more details.
+ output_hidden_states (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
+ for more details.
+ output_scores (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
+ return_dict_in_generate (`bool`, *optional*, defaults to `False`):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+ model_kwargs:
+ Additional model specific keyword arguments will be forwarded to the `call` function of the model. If
+ model is an encoder-decoder model the kwargs should include `encoder_outputs`.
+ Return:
+ [`~generation.TFContrastiveSearchDecoderOnlyOutput`],
+ [`~generation.TFContrastiveSearchEncoderDecoderOutput`] or `tf.Tensor`: A `tf.Tensor` containing the
+ generated tokens (default behaviour) or a [`~generation.TFContrastiveySearchDecoderOnlyOutput`] if
+ `model.config.is_encoder_decoder=False` and `return_dict_in_generate=True` or a
+ [`~generation.TFContrastiveSearchEncoderDecoderOutput`] if `model.config.is_encoder_decoder=True`.
+ Examples:
+ ```python
+ >>> from transformers import AutoTokenizer, TFAutoModelForCausalLM
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-125m")
+ >>> model = TFAutoModelForCausalLM.from_pretrained("facebook/opt-125m")
+ >>> # set pad_token_id to eos_token_id because OPT does not have a PAD token
+ >>> model.config.pad_token_id = model.config.eos_token_id
+ >>> input_prompt = "DeepMind Company is"
+ >>> input_ids = tokenizer(input_prompt, return_tensors="tf")
+ >>> outputs = model.contrastive_search(**input_ids, penalty_alpha=0.6, top_k=4, max_length=64)
+ >>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
+ ['DeepMind Company is a company that focuses on the development and commercialization of artificial intelligence (AI). DeepMind’s mission is to help people understand and solve problems that are difficult to solve in the world today.\n\nIn this post, we talk about the benefits of deep learning in business and how it']
+ ```"""
+
+ def gather_best_candidate(nested, selected_idx_stacked, batch_axis=0):
+ """Gathers the slices indexed by selected_idx_stacked from a potentially nested structure of tensors."""
+
+ def gather_fn(tensor):
+ gathered_tensor = tf.gather(params=tensor, indices=selected_idx_stacked, axis=batch_axis)
+ return gathered_tensor
+
+ return tf.nest.map_structure(gather_fn, nested)
+
+ # 1. init greedy_search values
+ logits_processor = logits_processor if logits_processor is not None else TFLogitsProcessorList()
+ logits_warper = logits_warper if logits_warper is not None else TFLogitsProcessorList()
+ max_length = max_length if max_length is not None else self.generation_config.max_length
+ pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
+ eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
+ if isinstance(eos_token_id, int):
+ eos_token_id = [eos_token_id]
+ output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
+ output_attentions = (
+ output_attentions if output_attentions is not None else self.generation_config.output_attentions
+ )
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
+ )
+ return_dict_in_generate = (
+ return_dict_in_generate
+ if return_dict_in_generate is not None
+ else self.generation_config.return_dict_in_generate
+ )
+ use_cache = True # In contrastive search, we always use cache
+ model_kwargs.pop("use_cache", None)
+
+ use_xla = not tf.executing_eagerly()
+ # TODO (Joao): fix cache format or find programatic way to detect cache index
+ # GPT2 and other models has a slightly different cache structure, with a different batch axis
+ model_name = str(self.decoder) if "EncoderDecoder" in str(self) else str(self)
+ cache_batch_axis = 1 if any(model_prefix in model_name for model_prefix in ("TFGPT2", "TFCTRL")) else 0
+
+ # 2. init `attentions`, `hidden_states`, and `scores` tuples
+ scores = [] if (return_dict_in_generate and output_scores) else None
+ decoder_attentions = [] if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = [] if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = [] if (return_dict_in_generate and output_hidden_states) else None
+
+ # 3. init tensors to use for "xla-compileable" generate function
+ batch_size, cur_len = shape_list(input_ids)
+
+ # initialize `generated` (`input_ids` padded with `pad_token_id`), `finished_sequences`
+ input_ids_padding = tf.ones((batch_size, max_length - cur_len), dtype=tf.int32) * (pad_token_id or 0)
+ generated = tf.concat([input_ids, input_ids_padding], axis=-1)
+ finished_sequences = tf.zeros((batch_size,), dtype=tf.bool)
+
+ # 4. define "xla-compile-able" stop-condition and auto-regressive function
+ # define condition fn
+ def contrastive_search_cond_fn(
+ generated, finished_sequences, cur_len, model_kwargs, next_step_cached_variables
+ ):
+ """state termination condition fn."""
+ return ~tf.reduce_all(finished_sequences)
+
+ # define condition fn
+ def contrastive_search_body_fn(
+ generated, finished_sequences, cur_len, model_kwargs, next_step_cached_variables
+ ):
+ """state update fn."""
+
+ # if the first step in the loop, encode all the prefix and obtain: (1) past_key_values;
+ # (2) last_hidden_states; (3) logit_for_next_step; (4) update model kwargs for the next step
+ if model_kwargs.get("past_key_values") is None:
+ # prepare inputs
+ model_inputs = self.prepare_inputs_for_generation(
+ generated[:, :cur_len], use_cache=use_cache, **model_kwargs
+ )
+
+ # encode the given prefix and prepare model inputs; encoder-decoder model process the prefix and save
+ # the `encoder_outputs`
+ outputs = self(
+ **model_inputs, return_dict=True, output_hidden_states=True, output_attentions=output_attentions
+ )
+
+ # last decoder hidden states will be used to compute the degeneration penalty (cosine similarity with
+ # previous tokens)
+ if self.config.is_encoder_decoder:
+ last_hidden_states = outputs.decoder_hidden_states[-1]
+ else:
+ last_hidden_states = outputs.hidden_states[-1]
+
+ # XLA: last_hidden_states normally grows at each step, but in XLA it is padded so as to be used across
+ # iterations (with fixed shapes)
+ if use_xla:
+ last_hidden_states = tf.pad(last_hidden_states, [[0, 0], [0, max_length - cur_len], [0, 0]])
+
+ # next logit for contrastive search to select top-k candidate tokens
+ logit_for_next_step = outputs.logits[:, -1, :]
+
+ if use_xla:
+ model_kwargs = self._update_model_kwargs_for_xla_generation(
+ model_outputs=outputs,
+ model_kwargs=model_kwargs,
+ cur_len=cur_len,
+ max_length=max_length,
+ batch_size=batch_size,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ batch_axis=cache_batch_axis,
+ )
+ else:
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
+ )
+
+ # Expands model inputs top_k times, for batched forward passes (akin to beam search).
+ _, model_kwargs = self._expand_inputs_for_generation(
+ expand_size=top_k, is_encoder_decoder=self.config.is_encoder_decoder, **model_kwargs
+ )
+
+ past_key_values = model_kwargs.get("past_key_values")
+ if past_key_values is None:
+ raise ValueError(
+ f"{self.__class__.__name__} does not support caching and therefore **can't** be used "
+ "for contrastive search."
+ )
+ elif (
+ not isinstance(past_key_values[0], (tuple, tf.Tensor))
+ or past_key_values[0][0].shape[0] != batch_size
+ ):
+ raise ValueError(
+ f"{self.__class__.__name__} does not have a standard cache format and therefore **can't** be "
+ "used for contrastive search without further modifications."
+ )
+ else:
+ logit_for_next_step = next_step_cached_variables["logit_for_next_step"]
+ last_hidden_states = next_step_cached_variables["last_hidden_states"]
+ outputs = next_step_cached_variables["outputs"]
+
+ # contrastive_search main logic start:
+ # contrastive search decoding consists of two steps: (1) candidate tokens recall; (2) candidate re-rank by
+ # degeneration penalty
+
+ logit_for_next_step = logits_processor(generated, logit_for_next_step, cur_len)
+ logit_for_next_step = logits_warper(generated, logit_for_next_step, cur_len)
+ next_probs = stable_softmax(logit_for_next_step, axis=-1)
+ top_k_probs, top_k_ids = tf.math.top_k(next_probs, k=top_k)
+
+ # Store scores, attentions and hidden_states when required
+ if not use_xla and return_dict_in_generate:
+ if output_scores:
+ scores.append(logit_for_next_step)
+ if output_attentions and self.config.is_encoder_decoder:
+ decoder_attentions.append(outputs.decoder_attentions)
+ elif output_attentions and not self.config.is_encoder_decoder:
+ decoder_attentions.append(outputs.attentions)
+ if self.config.is_encoder_decoder:
+ cross_attentions.append(outputs.cross_attentions)
+
+ if output_hidden_states and self.config.is_encoder_decoder:
+ decoder_hidden_states.append(outputs.decoder_hidden_states)
+ elif output_hidden_states and self.config.is_encoder_decoder:
+ decoder_hidden_states.append(outputs.hidden_states)
+
+ # Replicates the new past_key_values to match the `top_k` candidates
+ model_kwargs["past_key_values"] = tf.nest.map_structure(
+ lambda tensor: tf.repeat(tensor, top_k, axis=cache_batch_axis), model_kwargs["past_key_values"]
+ )
+
+ # compute the candidate tokens by the language model and collects their hidden_states
+ next_model_inputs = self.prepare_inputs_for_generation(
+ tf.reshape(top_k_ids, [-1, 1]), use_cache=use_cache, **model_kwargs
+ )
+ outputs = self(
+ **next_model_inputs, return_dict=True, output_hidden_states=True, output_attentions=output_attentions
+ )
+ next_past_key_values = self._extract_past_from_model_output(outputs)
+
+ logits = outputs.logits[:, -1, :]
+ # name is different for encoder-decoder and decoder-only models
+ if self.config.is_encoder_decoder:
+ next_hidden = outputs.decoder_hidden_states[-1]
+ full_hidden_states = outputs.decoder_hidden_states
+ else:
+ next_hidden = outputs.hidden_states[-1]
+ full_hidden_states = outputs.hidden_states
+ context_hidden = tf.repeat(last_hidden_states[:, :cur_len, :], top_k, axis=0)
+
+ # compute the degeneration penalty and re-rank the candidates based on the degeneration penalty and the
+ # model confidence
+ selected_idx = _ranking_fast(context_hidden, next_hidden, top_k_probs, penalty_alpha, top_k)
+
+ # converts indices to a dimension of top_k to the stacked top_k * batch_size dimension, for indexing
+ # without a need to reshape on tensors that have these two dimensions stacked
+ selected_idx_stacked = selected_idx + tf.range(selected_idx.shape[0], dtype=tf.int64) * top_k
+
+ # prepare for the next step: (1) next token_id; (2) past_key_values; (3) last_hidden_states for computing
+ # the degeneration penalty; (4) logits for selecting next top-k candidates; (5) selected tokens scores
+ # (model confidence minus degeneration penalty); (6) decoder hidden_states
+ next_tokens = tf.gather(top_k_ids, selected_idx, axis=1, batch_dims=1)
+ next_hidden = gather_best_candidate(next_hidden, selected_idx_stacked)
+
+ # XLA: last_hidden_states normally grows at each step, but in XLA it is padded so as to be used across
+ # iterations (with fixed shapes)
+ if use_xla:
+ last_hidden_states = dynamic_update_slice(last_hidden_states, next_hidden, [0, cur_len, 0])
+ else:
+ last_hidden_states = tf.concat([last_hidden_states, next_hidden], axis=1)
+
+ next_decoder_hidden_states = gather_best_candidate(full_hidden_states, selected_idx_stacked)
+ next_past_key_values = gather_best_candidate(
+ next_past_key_values, selected_idx_stacked, batch_axis=cache_batch_axis
+ )
+ logit_for_next_step = gather_best_candidate(logits, selected_idx_stacked)
+
+ # Rebuilds the relevant parts of the model output for the selected token, for use in the next iteration
+ if self.config.is_encoder_decoder:
+ next_step_cross_attentions = ()
+ next_step_decoder_attentions = ()
+ if output_attentions:
+ next_step_cross_attentions = gather_best_candidate(outputs.cross_attentions, selected_idx_stacked)
+ next_step_decoder_attentions = gather_best_candidate(
+ outputs.decoder_attentions, selected_idx_stacked
+ )
+ outputs = TFSeq2SeqLMOutput(
+ past_key_values=next_past_key_values,
+ decoder_hidden_states=next_decoder_hidden_states,
+ decoder_attentions=next_step_decoder_attentions or None,
+ cross_attentions=next_step_cross_attentions or None,
+ )
+ else:
+ next_step_attentions = ()
+ if output_attentions:
+ next_step_attentions = gather_best_candidate(outputs.attentions, selected_idx_stacked)
+ outputs = TFCausalLMOutputWithPast(
+ past_key_values=next_past_key_values,
+ hidden_states=next_decoder_hidden_states,
+ attentions=next_step_attentions or None,
+ )
+ # contrastive_search main logic end
+
+ if eos_token_id is not None:
+ if pad_token_id is None:
+ raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
+ unfinished_seq = 1 - tf.cast(finished_sequences, tf.int32)
+ next_tokens = next_tokens * unfinished_seq + pad_token_id * (1 - unfinished_seq)
+ next_token_is_eos = tf.math.reduce_any(
+ tf.equal(
+ tf.broadcast_to(next_tokens, (len(eos_token_id), batch_size)), tf.expand_dims(eos_token_id, -1)
+ ),
+ axis=0,
+ )
+ finished_sequences = finished_sequences | next_token_is_eos
+
+ # update `generated` and `cur_len`
+ update_indices = tf.stack([tf.range(batch_size), tf.broadcast_to(cur_len, [batch_size])], axis=-1)
+ generated = tf.tensor_scatter_nd_update(tensor=generated, indices=update_indices, updates=next_tokens)
+ cur_len += 1
+
+ if use_xla:
+ # NOTE: 1) relative to other generation strategies, contrastive search is always running forward
+ # passes one step ahead -- hence the `cur_len=cur_len + 1`; 2) the attention mask here is expanded from
+ # [batch_size, ...] to [batch_size*top_k, ...] -- hence the `batch_size=batch_size * top_k`
+ model_kwargs = self._update_model_kwargs_for_xla_generation(
+ model_outputs=outputs,
+ model_kwargs=model_kwargs,
+ cur_len=cur_len + 1,
+ max_length=max_length,
+ batch_size=batch_size * top_k,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ batch_axis=cache_batch_axis,
+ )
+ else:
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
+ )
+
+ next_step_cached_variables = {
+ "logit_for_next_step": logit_for_next_step,
+ "last_hidden_states": last_hidden_states,
+ "outputs": outputs,
+ }
+ return generated, finished_sequences, cur_len, model_kwargs, next_step_cached_variables
+
+ # 5. run generation
+ # 1st generation step has to be run before to initialize `past_key_values`
+ generated, finished_sequences, cur_len, model_kwargs, next_step_cached_variables = contrastive_search_body_fn(
+ generated, finished_sequences, cur_len, model_kwargs, None
+ )
+
+ # 2-to-n generation steps can then be run in autoregressive fashion
+ # only in case 1st generation step does NOT yield EOS token though
+ maximum_iterations = max_length - cur_len
+ generated, _, cur_len, _, _ = tf.while_loop(
+ contrastive_search_cond_fn,
+ contrastive_search_body_fn,
+ (generated, finished_sequences, cur_len, model_kwargs, next_step_cached_variables),
+ maximum_iterations=maximum_iterations,
+ )
+
+ # 6. prepare outputs
+ if not use_xla:
+ # cut for backward compatibility
+ generated = generated[:, :cur_len]
+
+ if return_dict_in_generate:
+ if self.config.is_encoder_decoder:
+ # if model is an encoder-decoder, retrieve encoder attention weights
+ # and hidden states
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
+ encoder_hidden_states = (
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
+ )
+
+ scores = tuple(scores) if scores is not None else None
+ decoder_attentions = tuple(decoder_attentions) if decoder_attentions is not None else None
+ cross_attentions = tuple(cross_attentions) if cross_attentions is not None else None
+ decoder_hidden_states = tuple(decoder_hidden_states) if decoder_hidden_states is not None else None
+
+ return TFContrastiveSearchEncoderDecoderOutput(
+ sequences=generated,
+ scores=scores,
+ encoder_attentions=encoder_attentions,
+ encoder_hidden_states=encoder_hidden_states,
+ decoder_attentions=decoder_attentions,
+ cross_attentions=cross_attentions,
+ decoder_hidden_states=decoder_hidden_states,
+ )
+ else:
+ return TFContrastiveSearchDecoderOnlyOutput(
+ sequences=generated,
+ scores=scores,
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ )
+ else:
+ return generated
+
+
+def scatter_values_on_batch_indices(values, batch_indices):
+ shape = shape_list(batch_indices)
+ # broadcast batch dim to shape
+ broad_casted_batch_dims = tf.reshape(tf.broadcast_to(tf.expand_dims(tf.range(shape[0]), axis=-1), shape), [1, -1])
+ # transform batch_indices to pair_indices
+ pair_indices = tf.transpose(tf.concat([broad_casted_batch_dims, tf.reshape(batch_indices, [1, -1])], 0))
+ # scatter values to pair indices
+ return tf.scatter_nd(pair_indices, tf.reshape(values, [-1]), shape)
+
+
+def sample_without_replacement(logits, num_samples):
+ """
+ categorical sampling without replacement is currently not implemented the gumbel-max trick will do for now see
+ https://github.com/tensorflow/tensorflow/issues/9260 for more info
+ """
+ z = -tf.math.log(-tf.math.log(tf.random.uniform(shape_list(logits), 0, 1)))
+ _, indices = tf.nn.top_k(logits + z, num_samples)
+ return indices
+
+
+def _ranking_fast(
+ context_hidden: tf.Tensor,
+ next_hidden: tf.Tensor,
+ next_top_k_probs: tf.Tensor,
+ alpha: float,
+ beam_width: int,
+) -> tf.Tensor:
+ """
+ Reranks the top_k candidates based on a degeneration penalty (cosine similarity with previous tokens), as described
+ in the paper "A Contrastive Framework for Neural Text Generation". Returns the index of the best candidate for each
+ row in the batch.
+ """
+ norm_context_hidden = context_hidden / tf.norm(context_hidden, axis=2, keepdims=True)
+ norm_next_hidden = next_hidden / tf.norm(next_hidden, axis=2, keepdims=True)
+ cosine_matrix = tf.squeeze(tf.linalg.matmul(norm_context_hidden, norm_next_hidden, transpose_b=True), axis=-1)
+ degeneration_penalty = tf.reduce_max(cosine_matrix, axis=-1)
+ next_top_k_probs = tf.reshape(next_top_k_probs, shape=[-1])
+ contrastive_score = (1.0 - alpha) * next_top_k_probs - alpha * degeneration_penalty
+ contrastive_score = tf.reshape(contrastive_score, shape=[-1, beam_width])
+ selected_idx = tf.argmax(contrastive_score, axis=1)
+ return selected_idx
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/utils.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d5be7d7a05e73c9266651da2c5cbaa22b80507d
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/utils.py
@@ -0,0 +1,4808 @@
+# coding=utf-8
+# Copyright 2020 The Google AI Language Team Authors, Facebook AI Research authors and The HuggingFace Inc. team.
+# Copyright (c) 2020, NVIDIA CORPORATION. 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 inspect
+import os
+import warnings
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
+
+import numpy as np
+import torch
+import torch.distributed as dist
+from torch import nn
+from torch.nn import functional as F
+
+from transformers.generation.candidate_generator import AssistantVocabTranslatorCache
+
+from ..cache_utils import (
+ Cache,
+ DynamicCache,
+ EncoderDecoderCache,
+ OffloadedCache,
+ QuantizedCacheConfig,
+ StaticCache,
+)
+from ..configuration_utils import PretrainedConfig
+from ..integrations.deepspeed import is_deepspeed_zero3_enabled
+from ..integrations.fsdp import is_fsdp_managed_module
+from ..modeling_outputs import CausalLMOutputWithPast, Seq2SeqLMOutput
+from ..pytorch_utils import isin_mps_friendly
+from ..tokenization_utils import ExtensionsTrie
+from ..utils import (
+ ModelOutput,
+ is_accelerate_available,
+ is_hqq_available,
+ is_optimum_quanto_available,
+ is_torchdynamo_compiling,
+ logging,
+)
+from .beam_constraints import DisjunctiveConstraint, PhrasalConstraint
+from .beam_search import BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer
+from .candidate_generator import (
+ AssistedCandidateGenerator,
+ AssistedCandidateGeneratorDifferentTokenizers,
+ CandidateGenerator,
+ EarlyExitCandidateGenerator,
+ PromptLookupCandidateGenerator,
+ UniversalSpeculativeDecodingGenerator,
+ _crop_past_key_values,
+ _prepare_attention_mask,
+ _prepare_token_type_ids,
+)
+from .configuration_utils import (
+ NEED_SETUP_CACHE_CLASSES_MAPPING,
+ QUANT_BACKEND_CLASSES_MAPPING,
+ GenerationConfig,
+ GenerationMode,
+)
+from .logits_process import (
+ EncoderNoRepeatNGramLogitsProcessor,
+ EncoderRepetitionPenaltyLogitsProcessor,
+ EpsilonLogitsWarper,
+ EtaLogitsWarper,
+ ExponentialDecayLengthPenalty,
+ ForcedBOSTokenLogitsProcessor,
+ ForcedEOSTokenLogitsProcessor,
+ HammingDiversityLogitsProcessor,
+ InfNanRemoveLogitsProcessor,
+ LogitNormalization,
+ LogitsProcessorList,
+ MinLengthLogitsProcessor,
+ MinNewTokensLengthLogitsProcessor,
+ MinPLogitsWarper,
+ NoBadWordsLogitsProcessor,
+ NoRepeatNGramLogitsProcessor,
+ PrefixConstrainedLogitsProcessor,
+ RepetitionPenaltyLogitsProcessor,
+ SequenceBiasLogitsProcessor,
+ SuppressTokensAtBeginLogitsProcessor,
+ SuppressTokensLogitsProcessor,
+ TemperatureLogitsWarper,
+ TopKLogitsWarper,
+ TopPLogitsWarper,
+ TypicalLogitsWarper,
+ UnbatchedClassifierFreeGuidanceLogitsProcessor,
+)
+from .stopping_criteria import (
+ ConfidenceCriteria,
+ EosTokenCriteria,
+ MaxLengthCriteria,
+ MaxTimeCriteria,
+ StoppingCriteria,
+ StoppingCriteriaList,
+ StopStringCriteria,
+)
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..tokenization_utils_base import PreTrainedTokenizerBase
+ from .streamers import BaseStreamer
+
+logger = logging.get_logger(__name__)
+
+if is_accelerate_available():
+ from accelerate.hooks import AlignDevicesHook, add_hook_to_module
+
+
+# Variable names used to hold the cache at generation time
+ALL_CACHE_NAMES = [
+ "past_key_values", # default
+ "cache_params", # mamba-based models
+ "state", # rwkv
+ "mems", # xlnet
+ "past_buckets_states", # reformer
+]
+
+
+@dataclass
+class GenerateDecoderOnlyOutput(ModelOutput):
+ """
+ Outputs of decoder-only generation models, when using non-beam methods.
+
+ Args:
+ sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
+ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
+ logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
+ Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
+ attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
+ hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.
+ past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True`):
+ Returns the model cache, used to speed up decoding. Different models have a different cache format, check
+ the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
+ """
+
+ sequences: torch.LongTensor = None
+ scores: Optional[Tuple[torch.FloatTensor]] = None
+ logits: Optional[Tuple[torch.FloatTensor]] = None
+ attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
+
+
+@dataclass
+class GenerateEncoderDecoderOutput(ModelOutput):
+ """
+ Outputs of encoder-decoder generation models, when using non-beam methods.
+
+ Args:
+ sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
+ Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
+ logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
+ Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
+ encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer of the decoder) of shape `(batch_size, num_heads,
+ sequence_length, sequence_length)`.
+ encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, sequence_length, hidden_size)`.
+ decoder_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
+ cross_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
+ decoder_hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.
+ past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ Returns the model cache, used to speed up decoding. Different models have a different cache format, check
+ the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
+ """
+
+ sequences: torch.LongTensor = None
+ scores: Optional[Tuple[torch.FloatTensor]] = None
+ logits: Optional[Tuple[torch.FloatTensor]] = None
+ encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
+ encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
+ decoder_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ cross_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ decoder_hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
+
+
+@dataclass
+class GenerateBeamDecoderOnlyOutput(ModelOutput):
+ """
+ Outputs of decoder-only generation models, when using beam methods.
+
+ Args:
+ sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ sequences_scores (`torch.FloatTensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True`):
+ Final beam scores of the generated `sequences`.
+ scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
+ Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting
+ of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
+ Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
+ with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
+ logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
+ Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
+ beam_indices (`torch.LongTensor`, *optional*, returned when `output_scores=True`):
+ Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
+ `(batch_size*num_return_sequences, sequence_length)`.
+ attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size*num_beams, num_heads, generated_length, sequence_length)`.
+ hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.
+ past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True`):
+ Returns the model cache, used to speed up decoding. Different models have a different cache format, check
+ the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
+ """
+
+ sequences: torch.LongTensor = None
+ sequences_scores: Optional[torch.FloatTensor] = None
+ scores: Optional[Tuple[torch.FloatTensor]] = None
+ logits: Optional[Tuple[torch.FloatTensor]] = None
+ beam_indices: Optional[torch.LongTensor] = None
+ attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
+
+
+@dataclass
+class GenerateBeamEncoderDecoderOutput(ModelOutput):
+ """
+ Outputs of encoder-decoder generation models, when using beam methods.
+
+ Args:
+ sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
+ if all batches finished early due to the `eos_token_id`.
+ sequences_scores (`torch.FloatTensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True`):
+ Final beam scores of the generated `sequences`.
+ scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):
+ Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting
+ of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
+ Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
+ with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
+ logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
+ Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
+ at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
+ each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
+ beam_indices (`torch.LongTensor`, *optional*, returned when `output_scores=True`):
+ Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
+ `(batch_size*num_return_sequences, sequence_length)`.
+ encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer of the decoder) of shape `(batch_size, num_heads,
+ sequence_length, sequence_length)`.
+ encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size*num_beams*num_return_sequences, sequence_length, hidden_size)`.
+ decoder_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, num_heads, generated_length,
+ sequence_length)`.
+ cross_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
+ decoder_hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
+ Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
+ `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.
+ past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True`):
+ Returns the model cache, used to speed up decoding. Different models have a different cache format, check
+ the model's documentation. Usually, a [`~cache_utils.Cache`] instance.
+ """
+
+ sequences: torch.LongTensor = None
+ sequences_scores: Optional[torch.FloatTensor] = None
+ scores: Optional[Tuple[torch.FloatTensor]] = None
+ logits: Optional[Tuple[torch.FloatTensor]] = None
+ beam_indices: Optional[torch.LongTensor] = None
+ encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
+ encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
+ decoder_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ cross_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ decoder_hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
+ past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
+
+
+# TODO (joao): remove the equivalent classes and typing shortcuts below in v5
+# Equivalent classes (kept for retrocompatibility purposes)
+GreedySearchDecoderOnlyOutput = GenerateDecoderOnlyOutput
+ContrastiveSearchDecoderOnlyOutput = GenerateDecoderOnlyOutput
+SampleDecoderOnlyOutput = GenerateDecoderOnlyOutput
+
+ContrastiveSearchEncoderDecoderOutput = GenerateEncoderDecoderOutput
+GreedySearchEncoderDecoderOutput = GenerateEncoderDecoderOutput
+SampleEncoderDecoderOutput = GenerateEncoderDecoderOutput
+
+BeamSearchDecoderOnlyOutput = GenerateBeamDecoderOnlyOutput
+BeamSampleDecoderOnlyOutput = GenerateBeamDecoderOnlyOutput
+
+BeamSearchEncoderDecoderOutput = GenerateBeamEncoderDecoderOutput
+BeamSampleEncoderDecoderOutput = GenerateBeamEncoderDecoderOutput
+
+GreedySearchOutput = Union[GreedySearchEncoderDecoderOutput, GreedySearchDecoderOnlyOutput]
+SampleOutput = Union[SampleEncoderDecoderOutput, SampleDecoderOnlyOutput]
+BeamSearchOutput = Union[BeamSearchEncoderDecoderOutput, BeamSearchDecoderOnlyOutput]
+BeamSampleOutput = Union[BeamSampleEncoderDecoderOutput, BeamSampleDecoderOnlyOutput]
+ContrastiveSearchOutput = Union[ContrastiveSearchEncoderDecoderOutput, ContrastiveSearchDecoderOnlyOutput]
+
+# Typing shortcuts
+GenerateNonBeamOutput = Union[GenerateDecoderOnlyOutput, GenerateEncoderDecoderOutput]
+GenerateBeamOutput = Union[GenerateBeamDecoderOnlyOutput, GenerateBeamEncoderDecoderOutput]
+GenerateOutput = Union[GenerateNonBeamOutput, GenerateBeamOutput]
+
+
+class GenerationMixin:
+ """
+ A class containing all functions for auto-regressive text generation, to be used as a mixin in [`PreTrainedModel`].
+
+ The class exposes [`~generation.GenerationMixin.generate`], which can be used for:
+ - *greedy decoding* if `num_beams=1` and `do_sample=False`
+ - *contrastive search* if `penalty_alpha>0` and `top_k>1`
+ - *multinomial sampling* if `num_beams=1` and `do_sample=True`
+ - *beam-search decoding* if `num_beams>1` and `do_sample=False`
+ - *beam-search multinomial sampling* if `num_beams>1` and `do_sample=True`
+ - *diverse beam-search decoding* if `num_beams>1` and `num_beam_groups>1`
+ - *constrained beam-search decoding* if `constraints!=None` or `force_words_ids!=None`
+ - *assisted decoding* if `assistant_model` or `prompt_lookup_num_tokens` is passed to `.generate()`
+
+ To learn more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).
+ """
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids: torch.LongTensor,
+ past_key_values: Optional[Cache] = None,
+ attention_mask: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ **kwargs,
+ ):
+ """
+ Prepare the model inputs for generation. In includes operations like computing the 4D attention mask or
+ slicing inputs given the existing cache.
+
+ See the forward pass in the model documentation for expected arguments (different models might have different
+ requirements for e.g. `past_key_values`). This function should work as is for most LLMs.
+ """
+
+ # 1. Handle BC:
+ model_inputs = {}
+ # - some models don't have `Cache` support (which implies they don't expect `cache_position` in `forward`)
+ if self._supports_cache_class:
+ model_inputs["cache_position"] = cache_position
+ # - `cache_position` was not a mandatory input in `prepare_inputs_for_generation` for those models, and this
+ # function may be called outside of `generate`. Handle most use cases by creating `cache_position` on the fly
+ # (this alternative is not as robust as calling `generate` and letting it create `cache_position`)
+ elif cache_position is None:
+ past_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
+ cache_position = torch.arange(past_length, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
+
+ # 2. Generic cache-dependent input preparation
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
+ # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case.
+ # (we can't check exception 3 while compiling)
+ # Excpetion 4: If input_embeds are passed then slice it through `cache_position`, to keep only the unprocessed tokens and
+ # generate the first token for each sequence. Later use the generated Input ids for continuation.
+ if past_key_values is not None:
+ model_inputs["past_key_values"] = past_key_values
+ if inputs_embeds is not None and input_ids.shape[1] == 0: # Exception 4
+ inputs_embeds = inputs_embeds[:, -cache_position.shape[0] :]
+ elif (
+ inputs_embeds is not None # Exception 1
+ or (is_torchdynamo_compiling() or cache_position[-1] >= input_ids.shape[1]) # Exception 3
+ ):
+ input_ids = input_ids[:, -cache_position.shape[0] :]
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
+ input_ids = input_ids[:, cache_position]
+
+ # 3. Prepare base model inputs
+ input_ids_key = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step for every prompt.
+ if not self.config.is_encoder_decoder:
+ if inputs_embeds is not None and len(cache_position) == inputs_embeds.shape[1]:
+ model_inputs[input_ids_key] = None
+ model_inputs["inputs_embeds"] = inputs_embeds
+ else:
+ # `clone` calls in this function ensure a consistent stride. See #32227
+ model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)
+ model_inputs["inputs_embeds"] = None
+ else:
+ model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)
+
+ # 4. Create missing `position_ids` on the fly
+ encoder_attention_mask = attention_mask if self.config.is_encoder_decoder else None
+ attention_mask = (
+ kwargs.pop("decoder_attention_mask", None) if self.config.is_encoder_decoder else attention_mask
+ )
+ attention_mask_key = "decoder_attention_mask" if self.config.is_encoder_decoder else "attention_mask"
+ position_ids_key = "decoder_position_ids" if self.config.is_encoder_decoder else "position_ids"
+ if (
+ attention_mask is not None
+ and kwargs.get(position_ids_key) is None
+ and position_ids_key in set(inspect.signature(self.forward).parameters.keys())
+ ):
+ position_ids = attention_mask.long().cumsum(-1) - 1
+ position_ids.masked_fill_(attention_mask == 0, 1)
+ kwargs[position_ids_key] = position_ids # placed in kwargs for further processing (see below)
+
+ # 5. Slice model inputs if it's an input that should have the same length as `input_ids`
+ for model_input_name in ["position_ids", "token_type_ids", "decoder_position_ids"]:
+ model_input = kwargs.get(model_input_name)
+ if model_input is not None:
+ if past_key_values is not None:
+ current_input_length = (
+ model_inputs["inputs_embeds"].shape[1]
+ if model_inputs.get("inputs_embeds") is not None
+ else model_inputs[input_ids_key].shape[1]
+ )
+ model_input = model_input[:, -current_input_length:]
+ model_input = model_input.clone(memory_format=torch.contiguous_format)
+ model_inputs[model_input_name] = model_input
+
+ # 6. Create 4D attention mask is we are using a `StaticCache` (important for performant compiled forward pass)
+ if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
+ if model_inputs["inputs_embeds"] is not None:
+ batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
+ device = model_inputs["inputs_embeds"].device
+ else:
+ batch_size, sequence_length = model_inputs[input_ids_key].shape
+ device = model_inputs[input_ids_key].device
+
+ # Create the causal mask with fixed shape in advance, to reduce recompilations. If the function to create
+ # the 4D causal mask exists, it should be present in the base model (XXXModel class).
+ base_model = getattr(self, self.base_model_prefix, None)
+ if base_model is None:
+ causal_mask_creation_function = getattr(
+ self, "_prepare_4d_causal_attention_mask_with_cache_position", None
+ )
+ else:
+ causal_mask_creation_function = getattr(
+ base_model, "_prepare_4d_causal_attention_mask_with_cache_position", None
+ )
+ if causal_mask_creation_function is None:
+ logger.warning_once(
+ f"{self.__class__.__name__} has no `_prepare_4d_causal_attention_mask_with_cache_position` method "
+ "defined in its base modeling class. Compiled forward passes will be sub-optimal. If you're "
+ "writing code, see Llama for an example implementation. If you're a user, please report this "
+ "issue on GitHub."
+ )
+ else:
+ attention_mask = causal_mask_creation_function(
+ attention_mask,
+ sequence_length=sequence_length,
+ target_length=past_key_values.get_max_cache_shape(),
+ dtype=self.dtype,
+ device=device,
+ cache_position=cache_position,
+ batch_size=batch_size,
+ config=self.config,
+ past_key_values=past_key_values,
+ )
+ if attention_mask is not None:
+ model_inputs[attention_mask_key] = attention_mask
+
+ if encoder_attention_mask is not None:
+ model_inputs["attention_mask"] = encoder_attention_mask
+
+ # 7. Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
+ for key, value in kwargs.items():
+ if key not in model_inputs:
+ model_inputs[key] = value
+
+ # 8. Remove unexpected `generate` inputs (TODO @joao: fix trainer and examples)
+ model_inputs.pop("labels", None)
+ return model_inputs
+
+ def _prepare_model_inputs(
+ self,
+ inputs: Optional[torch.Tensor] = None,
+ bos_token_id: Optional[torch.Tensor] = None,
+ model_kwargs: Optional[Dict[str, torch.Tensor]] = None,
+ ) -> Tuple[torch.Tensor, Optional[str], Dict[str, torch.Tensor]]:
+ """
+ This function extracts the model-specific `inputs` for generation.
+ """
+ # 1. retrieve all kwargs that are non-None or non-model input related.
+ # some encoder-decoder models have different names for model and encoder
+ if (
+ self.config.is_encoder_decoder
+ and hasattr(self, "encoder")
+ and self.encoder.main_input_name != self.main_input_name
+ ):
+ input_name = self.encoder.main_input_name
+ else:
+ input_name = self.main_input_name
+
+ model_kwargs = {k: v for k, v in model_kwargs.items() if v is not None or k != input_name}
+
+ # 2. check whether model_input_name is passed as kwarg
+ # if yes and `inputs` is None use kwarg inputs
+ inputs_kwarg = model_kwargs.pop(input_name, None)
+ if inputs_kwarg is not None and inputs is not None:
+ raise ValueError(
+ f"`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. "
+ f"Make sure to either pass {inputs} or {input_name}=..."
+ )
+ elif inputs_kwarg is not None:
+ inputs = inputs_kwarg
+
+ # 3. In the presence of `inputs_embeds` for text models:
+ # - decoder-only models should complain if the user attempts to pass `inputs_embeds`, but the model
+ # doesn't have its forwarding implemented. `inputs_embeds` is kept in `model_kwargs` and can coexist with
+ # input_ids (`inputs_embeds` will be used in the 1st generation step, as opposed to `input_ids`)
+ # - encoder-decoder models should complain if the user attempts to pass `inputs_embeds` and `input_ids`, and
+ # pull the former to inputs. It will be used in place of `input_ids` to get the encoder hidden states.
+ if input_name == "input_ids" and "inputs_embeds" in model_kwargs:
+ if not self.config.is_encoder_decoder:
+ has_inputs_embeds_forwarding = "inputs_embeds" in set(
+ inspect.signature(self.prepare_inputs_for_generation).parameters.keys()
+ )
+ if not has_inputs_embeds_forwarding:
+ raise ValueError(
+ f"You passed `inputs_embeds` to `.generate()`, but the model class {self.__class__.__name__} "
+ "doesn't have its forwarding implemented. See the GPT2 implementation for an example "
+ "(https://github.com/huggingface/transformers/pull/21405), and feel free to open a PR with it!"
+ )
+ # In this case, `input_ids` is moved to the `model_kwargs`, so a few automations (like the creation of
+ # the attention mask) can rely on the actual model input.
+ model_kwargs["input_ids"] = self._maybe_initialize_input_ids_for_generation(
+ inputs, bos_token_id, model_kwargs=model_kwargs
+ )
+ else:
+ if inputs is not None:
+ raise ValueError("You passed `inputs_embeds` and `input_ids` to `.generate()`. Please pick one.")
+ inputs, input_name = model_kwargs["inputs_embeds"], "inputs_embeds"
+
+ # 4. if `inputs` is still None, try to create `input_ids` from BOS token
+ inputs = self._maybe_initialize_input_ids_for_generation(inputs, bos_token_id, model_kwargs)
+ return inputs, input_name, model_kwargs
+
+ def _maybe_initialize_input_ids_for_generation(
+ self,
+ inputs: Optional[torch.Tensor] = None,
+ bos_token_id: Optional[torch.Tensor] = None,
+ model_kwargs: Optional[Dict[str, torch.Tensor]] = None,
+ ) -> torch.LongTensor:
+ """Initializes input ids for generation, if necessary."""
+ if inputs is not None:
+ return inputs
+
+ encoder_outputs = model_kwargs.get("encoder_outputs")
+ if self.config.is_encoder_decoder and encoder_outputs is not None:
+ # make dummy input_ids with value -100, as a sanity check ensuring that they won't be used for encoding
+ shape = encoder_outputs.last_hidden_state.size()[:-1]
+ return torch.ones(shape, dtype=torch.long, device=self.device) * -100
+
+ # If there is some tensor in `model_kwargs`, we can infer the batch size from it. This is helpful with
+ # soft-prompting or in multimodal implementations built on top of decoder-only language models.
+ batch_size = 1
+ for value in model_kwargs.values():
+ if isinstance(value, torch.Tensor):
+ batch_size = value.shape[0]
+ break
+
+ if "inputs_embeds" in model_kwargs:
+ return torch.ones((batch_size, 0), dtype=torch.long, device=self.device)
+
+ if bos_token_id is None:
+ raise ValueError("`bos_token_id` has to be defined when no `input_ids` are provided.")
+
+ return torch.ones((batch_size, 1), dtype=torch.long, device=self.device) * bos_token_id
+
+ def _prepare_attention_mask_for_generation(
+ self,
+ inputs_tensor: torch.Tensor,
+ generation_config: GenerationConfig,
+ model_kwargs: Dict[str, Any],
+ ) -> torch.LongTensor:
+ pad_token_id = generation_config._pad_token_tensor
+ eos_token_id = generation_config._eos_token_tensor
+
+ # `input_ids` may be present in the model kwargs, instead of being the main input (e.g. multimodal model)
+ if "input_ids" in model_kwargs and model_kwargs["input_ids"].shape[1] > 0:
+ inputs_tensor = model_kwargs["input_ids"]
+
+ # No information for attention mask inference -> return default attention mask
+ default_attention_mask = torch.ones(inputs_tensor.shape[:2], dtype=torch.long, device=inputs_tensor.device)
+ if pad_token_id is None:
+ return default_attention_mask
+
+ is_input_ids = len(inputs_tensor.shape) == 2 and inputs_tensor.dtype in [torch.int, torch.long]
+ if not is_input_ids:
+ return default_attention_mask
+
+ is_pad_token_in_inputs = (pad_token_id is not None) and (
+ isin_mps_friendly(elements=inputs_tensor, test_elements=pad_token_id).any()
+ )
+ is_pad_token_not_equal_to_eos_token_id = (eos_token_id is None) or ~(
+ isin_mps_friendly(elements=eos_token_id, test_elements=pad_token_id).any()
+ )
+ can_infer_attention_mask = is_pad_token_in_inputs * is_pad_token_not_equal_to_eos_token_id
+ attention_mask_from_padding = inputs_tensor.ne(pad_token_id).long()
+
+ attention_mask = (
+ attention_mask_from_padding * can_infer_attention_mask + default_attention_mask * ~can_infer_attention_mask
+ )
+ return attention_mask
+
+ def _prepare_encoder_decoder_kwargs_for_generation(
+ self,
+ inputs_tensor: torch.Tensor,
+ model_kwargs,
+ model_input_name: Optional[str],
+ generation_config: GenerationConfig,
+ ) -> Dict[str, Any]:
+ # 1. get encoder
+ encoder = self.get_encoder()
+ # Compatibility with Accelerate big model inference: we need the encoder to outputs stuff on the same device
+ # as the inputs.
+ if hasattr(self, "hf_device_map"):
+ if hasattr(encoder, "_hf_hook"):
+ encoder._hf_hook.io_same_device = True
+ else:
+ add_hook_to_module(encoder, AlignDevicesHook(io_same_device=True))
+
+ # 2. Prepare encoder args and encoder kwargs from model kwargs and generation config.
+ irrelevant_prefix = ["decoder_", "cross_attn", "use_cache"]
+ encoder_kwargs = {
+ argument: value
+ for argument, value in model_kwargs.items()
+ if not any(argument.startswith(p) for p in irrelevant_prefix)
+ }
+ encoder_signature = set(inspect.signature(encoder.forward).parameters)
+ encoder_accepts_wildcard = "kwargs" in encoder_signature or "model_kwargs" in encoder_signature
+ if not encoder_accepts_wildcard:
+ encoder_kwargs = {
+ argument: value for argument, value in encoder_kwargs.items() if argument in encoder_signature
+ }
+ encoder_kwargs["output_attentions"] = generation_config.output_attentions
+ encoder_kwargs["output_hidden_states"] = generation_config.output_hidden_states
+
+ # 3. make sure that encoder returns `ModelOutput`
+ model_input_name = model_input_name if model_input_name is not None else self.main_input_name
+ encoder_kwargs["return_dict"] = True
+ encoder_kwargs[model_input_name] = inputs_tensor
+ model_kwargs["encoder_outputs"]: ModelOutput = encoder(**encoder_kwargs) # type: ignore
+
+ return model_kwargs
+
+ def _prepare_decoder_input_ids_for_generation(
+ self,
+ batch_size: int,
+ model_input_name: str,
+ model_kwargs: Dict[str, torch.Tensor],
+ decoder_start_token_id: torch.Tensor,
+ device: torch.device = None,
+ ) -> Tuple[torch.LongTensor, Dict[str, torch.Tensor]]:
+ """Prepares `decoder_input_ids` for generation with encoder-decoder models"""
+ # 1. Check whether the user has defined `decoder_input_ids` manually. To facilitate in terms of input naming,
+ # we also allow the user to pass it under `input_ids`, if the encoder does not use it as the main input.
+ if model_kwargs is not None and "decoder_input_ids" in model_kwargs:
+ decoder_input_ids = model_kwargs.pop("decoder_input_ids")
+ elif "input_ids" in model_kwargs and model_input_name != "input_ids":
+ decoder_input_ids = model_kwargs.pop("input_ids")
+ else:
+ decoder_input_ids = None
+
+ # 2. `decoder_start_token_id` must have shape (batch_size, 1)
+ if device is None:
+ device = self.device
+ if decoder_start_token_id.ndim == 1:
+ if decoder_start_token_id.shape[0] != batch_size:
+ raise ValueError(
+ f"`decoder_start_token_id` expected to have length {batch_size} but got {decoder_start_token_id.shape[0]}"
+ )
+ decoder_start_token_id = decoder_start_token_id.view(-1, 1)
+ else:
+ decoder_start_token_id = (
+ torch.ones((batch_size, 1), dtype=torch.long, device=device) * decoder_start_token_id
+ )
+
+ # 3. Encoder-decoder models expect the `decoder_input_ids` to start with a special token. Let's ensure that.
+ # no user input -> use decoder_start_token_id as decoder_input_ids
+ if decoder_input_ids is None:
+ decoder_input_ids = decoder_start_token_id
+ # exception: Donut checkpoints have task-specific decoder starts and don't expect a BOS token. Note that the
+ # original checkpoints can't be detected through `self.__class__.__name__.lower()`, needing custom logic.
+ # See: https://github.com/huggingface/transformers/pull/31470
+ elif "donut" in self.__class__.__name__.lower() or (
+ self.config.model_type == "vision-encoder-decoder" and "donut" in self.config.encoder.model_type.lower()
+ ):
+ pass
+ elif self.config.model_type in ["whisper"]:
+ pass
+ # user input but doesn't start with decoder_start_token_id -> prepend decoder_start_token_id (and adjust
+ # decoder_attention_mask if provided)
+ elif (decoder_input_ids[:, 0] != decoder_start_token_id[:, 0]).all().item():
+ decoder_input_ids = torch.cat([decoder_start_token_id, decoder_input_ids], dim=-1)
+ if "decoder_attention_mask" in model_kwargs:
+ decoder_attention_mask = model_kwargs["decoder_attention_mask"]
+ decoder_attention_mask = torch.cat(
+ (torch.ones_like(decoder_attention_mask)[:, :1], decoder_attention_mask),
+ dim=-1,
+ )
+ model_kwargs["decoder_attention_mask"] = decoder_attention_mask
+
+ return decoder_input_ids, model_kwargs
+
+ @staticmethod
+ def _expand_inputs_for_generation(
+ expand_size: int = 1,
+ is_encoder_decoder: bool = False,
+ input_ids: Optional[torch.LongTensor] = None,
+ **model_kwargs,
+ ) -> Tuple[torch.LongTensor, Dict[str, Any]]:
+ """Expands tensors from [batch_size, ...] to [batch_size * expand_size, ...]"""
+ # Do not call torch.repeat_interleave if expand_size is 1 because it clones
+ # the input tensor and thus requires more memory although no change is applied
+ if expand_size == 1:
+ return input_ids, model_kwargs
+
+ def _expand_dict_for_generation(dict_to_expand):
+ for key in dict_to_expand:
+ if (
+ key != "cache_position"
+ and dict_to_expand[key] is not None
+ and isinstance(dict_to_expand[key], torch.Tensor)
+ ):
+ dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0)
+ return dict_to_expand
+
+ if input_ids is not None:
+ input_ids = input_ids.repeat_interleave(expand_size, dim=0)
+
+ model_kwargs = _expand_dict_for_generation(model_kwargs)
+
+ if is_encoder_decoder:
+ if model_kwargs.get("encoder_outputs") is None:
+ raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
+ model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
+
+ return input_ids, model_kwargs
+
+ def _update_model_kwargs_for_generation(
+ self,
+ outputs: ModelOutput,
+ model_kwargs: Dict[str, Any],
+ is_encoder_decoder: bool = False,
+ num_new_tokens: int = 1,
+ ) -> Dict[str, Any]:
+ # update past_key_values keeping its naming used in model code
+ for possible_cache_name in ALL_CACHE_NAMES:
+ if possible_cache_name in outputs:
+ # TODO (joao): remove output/input mismatch when these old models (xlnet, reformer) are deprecated
+ if possible_cache_name in ("past_buckets_states", "mems"):
+ cache_name = "past_key_values"
+ else:
+ cache_name = possible_cache_name
+ model_kwargs[cache_name] = getattr(outputs, possible_cache_name)
+ break
+
+ # update token_type_ids with last value
+ if "token_type_ids" in model_kwargs:
+ token_type_ids = model_kwargs["token_type_ids"]
+ model_kwargs["token_type_ids"] = torch.cat([token_type_ids, token_type_ids[:, -1].unsqueeze(-1)], dim=-1)
+
+ if not is_encoder_decoder:
+ # update attention mask
+ if "attention_mask" in model_kwargs:
+ attention_mask = model_kwargs["attention_mask"]
+ model_kwargs["attention_mask"] = torch.cat(
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
+ )
+ else:
+ # update decoder attention mask
+ if "decoder_attention_mask" in model_kwargs:
+ decoder_attention_mask = model_kwargs["decoder_attention_mask"]
+ model_kwargs["decoder_attention_mask"] = torch.cat(
+ [decoder_attention_mask, decoder_attention_mask.new_ones((decoder_attention_mask.shape[0], 1))],
+ dim=-1,
+ )
+
+ if model_kwargs.get("use_cache", True):
+ model_kwargs["cache_position"] = model_kwargs["cache_position"][-1:] + num_new_tokens
+ else:
+ past_positions = model_kwargs.pop("cache_position")
+ new_positions = torch.arange(
+ past_positions[-1] + 1, past_positions[-1] + num_new_tokens + 1, dtype=past_positions.dtype
+ ).to(past_positions.device)
+ model_kwargs["cache_position"] = torch.cat((past_positions, new_positions))
+ return model_kwargs
+
+ def _reorder_cache(self, past_key_values, beam_idx):
+ raise NotImplementedError(
+ f"Make sure that a `_reorder_cache` function is correctly implemented in {self.__class__.__module__} to"
+ f" enable beam search for {self.__class__}"
+ )
+
+ def _get_candidate_generator(
+ self,
+ generation_config: GenerationConfig,
+ input_ids: torch.LongTensor,
+ inputs_tensor: torch.Tensor,
+ assistant_model: "PreTrainedModel",
+ logits_processor: LogitsProcessorList,
+ target_tokenizer: "PreTrainedTokenizerBase",
+ assistant_tokenizer: "PreTrainedTokenizerBase",
+ model_kwargs: Dict,
+ ) -> CandidateGenerator:
+ """
+ Returns the candidate generator to be used in `assisted_generation`
+ """
+ different_tokenizers = all(v is not None for v in (assistant_model, target_tokenizer, assistant_tokenizer))
+
+ if generation_config.assistant_early_exit is not None:
+ candidate_generator = EarlyExitCandidateGenerator(
+ input_ids=input_ids,
+ assistant_model=self,
+ generation_config=generation_config,
+ model_kwargs=model_kwargs,
+ inputs_tensor=inputs_tensor,
+ logits_processor=logits_processor,
+ )
+ elif generation_config.prompt_lookup_num_tokens is not None:
+ candidate_generator = PromptLookupCandidateGenerator(
+ eos_token_id=generation_config._eos_token_tensor,
+ num_output_tokens=generation_config.prompt_lookup_num_tokens,
+ max_matching_ngram_size=generation_config.max_matching_ngram_size,
+ max_length=generation_config.max_length,
+ )
+ elif different_tokenizers:
+ if generation_config.do_sample is True:
+ atm_translator = AssistantVocabTranslatorCache.get_translator(
+ target_tokenizer, assistant_tokenizer, self.config.vocab_size, assistant_model.device
+ )
+ candidate_generator = UniversalSpeculativeDecodingGenerator(
+ input_ids=input_ids,
+ assistant_model=assistant_model,
+ generation_config=generation_config,
+ model_kwargs=model_kwargs,
+ inputs_tensor=inputs_tensor,
+ logits_processor=logits_processor,
+ target_tokenizer=target_tokenizer,
+ assistant_tokenizer=assistant_tokenizer,
+ atm_translator=atm_translator,
+ )
+ elif generation_config.do_sample is False:
+ candidate_generator = AssistedCandidateGeneratorDifferentTokenizers(
+ input_ids=input_ids,
+ assistant_model=assistant_model,
+ generation_config=generation_config,
+ model_kwargs=model_kwargs,
+ inputs_tensor=inputs_tensor,
+ logits_processor=logits_processor,
+ target_tokenizer=target_tokenizer,
+ assistant_tokenizer=assistant_tokenizer,
+ )
+ else:
+ raise ValueError(
+ f"Invalid value for `do_sample`: expected a boolean, got {type(generation_config.do_sample).__name__}"
+ )
+ else:
+ candidate_generator = AssistedCandidateGenerator(
+ input_ids=input_ids,
+ assistant_model=assistant_model,
+ generation_config=generation_config,
+ model_kwargs=model_kwargs,
+ inputs_tensor=inputs_tensor,
+ logits_processor=logits_processor,
+ )
+ return candidate_generator
+
+ def _get_logits_processor(
+ self,
+ generation_config: GenerationConfig,
+ input_ids_seq_length: int,
+ encoder_input_ids: torch.LongTensor,
+ prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], List[int]],
+ logits_processor: Optional[LogitsProcessorList],
+ device: str = None,
+ model_kwargs: Optional[Dict[str, Any]] = None,
+ negative_prompt_ids: Optional[torch.Tensor] = None,
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
+ ) -> LogitsProcessorList:
+ """
+ This class returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsProcessor`]
+ instances used to modify the scores of the language model head.
+ """
+ # instantiate processors list
+ processors = LogitsProcessorList()
+
+ if generation_config.guidance_scale is not None and generation_config.guidance_scale != 1:
+ processors.append(
+ UnbatchedClassifierFreeGuidanceLogitsProcessor(
+ generation_config.guidance_scale,
+ self,
+ unconditional_ids=negative_prompt_ids,
+ unconditional_attention_mask=negative_prompt_attention_mask,
+ use_cache=generation_config.use_cache,
+ )
+ )
+ if generation_config.sequence_bias is not None:
+ processors.append(SequenceBiasLogitsProcessor(sequence_bias=generation_config.sequence_bias))
+
+ if generation_config.diversity_penalty is not None and generation_config.diversity_penalty > 0.0:
+ processors.append(
+ HammingDiversityLogitsProcessor(
+ diversity_penalty=generation_config.diversity_penalty,
+ num_beams=generation_config.num_beams,
+ num_beam_groups=generation_config.num_beam_groups,
+ )
+ )
+ if (
+ generation_config.encoder_repetition_penalty is not None
+ and generation_config.encoder_repetition_penalty != 1.0
+ ):
+ if len(encoder_input_ids.shape) == 2:
+ processors.append(
+ EncoderRepetitionPenaltyLogitsProcessor(
+ penalty=generation_config.encoder_repetition_penalty,
+ encoder_input_ids=encoder_input_ids,
+ )
+ )
+ else:
+ warnings.warn(
+ "Passing `encoder_repetition_penalty` requires some form of `input_ids` to be passed to "
+ "`generate`, ignoring the argument.",
+ UserWarning,
+ )
+ if generation_config.repetition_penalty is not None and generation_config.repetition_penalty != 1.0:
+ processors.append(RepetitionPenaltyLogitsProcessor(penalty=generation_config.repetition_penalty))
+ if generation_config.no_repeat_ngram_size is not None and generation_config.no_repeat_ngram_size > 0:
+ processors.append(NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size))
+ if (
+ generation_config.encoder_no_repeat_ngram_size is not None
+ and generation_config.encoder_no_repeat_ngram_size > 0
+ ):
+ if len(encoder_input_ids.shape) == 2:
+ processors.append(
+ EncoderNoRepeatNGramLogitsProcessor(
+ generation_config.encoder_no_repeat_ngram_size,
+ encoder_input_ids,
+ )
+ )
+ else:
+ warnings.warn(
+ "Passing `encoder_no_repeat_ngram_size` requires some form of `input_ids` to be passed to "
+ "`generate`, ignoring the argument.",
+ UserWarning,
+ )
+ if generation_config.bad_words_ids is not None:
+ processors.append(
+ NoBadWordsLogitsProcessor(
+ generation_config.bad_words_ids,
+ generation_config._eos_token_tensor,
+ )
+ )
+ if (
+ generation_config.min_length is not None
+ and generation_config._eos_token_tensor is not None
+ and generation_config.min_length > 0
+ ):
+ processors.append(
+ MinLengthLogitsProcessor(
+ generation_config.min_length,
+ generation_config._eos_token_tensor,
+ device=device,
+ )
+ )
+ if (
+ generation_config.min_new_tokens is not None
+ and generation_config._eos_token_tensor is not None
+ and generation_config.min_new_tokens > 0
+ ):
+ processors.append(
+ MinNewTokensLengthLogitsProcessor(
+ input_ids_seq_length,
+ generation_config.min_new_tokens,
+ generation_config._eos_token_tensor,
+ device=device,
+ )
+ )
+ if prefix_allowed_tokens_fn is not None:
+ processors.append(
+ PrefixConstrainedLogitsProcessor(
+ prefix_allowed_tokens_fn,
+ generation_config.num_beams // generation_config.num_beam_groups,
+ )
+ )
+ if generation_config.forced_bos_token_id is not None:
+ processors.append(
+ ForcedBOSTokenLogitsProcessor(
+ generation_config.forced_bos_token_id,
+ )
+ )
+ if generation_config.forced_eos_token_id is not None:
+ processors.append(
+ ForcedEOSTokenLogitsProcessor(
+ generation_config.max_length,
+ generation_config.forced_eos_token_id,
+ device=device,
+ )
+ )
+ if generation_config.remove_invalid_values is True:
+ processors.append(InfNanRemoveLogitsProcessor())
+ if generation_config.exponential_decay_length_penalty is not None:
+ processors.append(
+ ExponentialDecayLengthPenalty(
+ generation_config.exponential_decay_length_penalty,
+ generation_config._eos_token_tensor,
+ input_ids_seq_length,
+ )
+ )
+ if generation_config.suppress_tokens is not None:
+ processors.append(
+ SuppressTokensLogitsProcessor(
+ generation_config.suppress_tokens,
+ device=device,
+ )
+ )
+ if generation_config.begin_suppress_tokens is not None:
+ begin_index = input_ids_seq_length
+ begin_index = (
+ begin_index
+ if (input_ids_seq_length > 1 or generation_config.forced_bos_token_id is None)
+ else begin_index + 1
+ )
+ processors.append(
+ SuppressTokensAtBeginLogitsProcessor(
+ generation_config.begin_suppress_tokens,
+ begin_index,
+ device=device,
+ )
+ )
+ if generation_config.forced_decoder_ids is not None:
+ # TODO (sanchit): move this exception to GenerationConfig.validate() when TF & FLAX are aligned with PT
+ raise ValueError(
+ "You have explicitly specified `forced_decoder_ids`. Please remove the `forced_decoder_ids` argument "
+ "in favour of `input_ids` or `decoder_input_ids` respectively.",
+ )
+
+ # TODO (joao): find a strategy to specify the order of the processors
+ processors = self._merge_criteria_processor_list(processors, logits_processor)
+
+ # Processors previously known as `LogitsWarpers`, only applied with sampling strategies
+ if generation_config.do_sample:
+ # In beam methods, we need to keep at least one non-eos token to explore continuations that might have a
+ # better score (i.e. keep len(list(generation_config._eos_token_tensor)) + 1)
+ if generation_config.num_beams > 1:
+ if isinstance(generation_config._eos_token_tensor, list):
+ min_tokens_to_keep = len(generation_config._eos_token_tensor) + 1
+ elif isinstance(generation_config._eos_token_tensor, torch.Tensor):
+ min_tokens_to_keep = generation_config._eos_token_tensor.shape[0] + 1
+ else:
+ min_tokens_to_keep = 2
+ else:
+ min_tokens_to_keep = 1
+
+ # the following idea is largely copied from this PR: https://github.com/huggingface/transformers/pull/5420/files
+ # all samplers can be found in `generation_utils_samplers.py`
+ if generation_config.temperature is not None and generation_config.temperature != 1.0:
+ processors.append(TemperatureLogitsWarper(generation_config.temperature))
+ if generation_config.top_k is not None and generation_config.top_k != 0:
+ processors.append(
+ TopKLogitsWarper(top_k=generation_config.top_k, min_tokens_to_keep=min_tokens_to_keep)
+ )
+ if generation_config.top_p is not None and generation_config.top_p < 1.0:
+ processors.append(
+ TopPLogitsWarper(top_p=generation_config.top_p, min_tokens_to_keep=min_tokens_to_keep)
+ )
+ if generation_config.min_p is not None:
+ # Applied after temperature scaling (see https://github.com/ggerganov/llama.cpp/pull/3841#issuecomment-2073826084)
+ processors.append(
+ MinPLogitsWarper(min_p=generation_config.min_p, min_tokens_to_keep=min_tokens_to_keep)
+ )
+ if generation_config.typical_p is not None and generation_config.typical_p < 1.0:
+ processors.append(
+ TypicalLogitsWarper(mass=generation_config.typical_p, min_tokens_to_keep=min_tokens_to_keep)
+ )
+ if generation_config.epsilon_cutoff is not None and 0.0 < generation_config.epsilon_cutoff < 1.0:
+ processors.append(
+ EpsilonLogitsWarper(
+ epsilon=generation_config.epsilon_cutoff, min_tokens_to_keep=min_tokens_to_keep
+ )
+ )
+ if generation_config.eta_cutoff is not None and 0.0 < generation_config.eta_cutoff < 1.0:
+ processors.append(
+ EtaLogitsWarper(
+ epsilon=generation_config.eta_cutoff, min_tokens_to_keep=min_tokens_to_keep, device=device
+ )
+ )
+
+ # Watermarking should be after all logits processing is finished (see #34630)
+ if generation_config.watermarking_config is not None:
+ processors.append(
+ generation_config.watermarking_config.construct_processor(self.config.vocab_size, device)
+ )
+
+ # `LogitNormalization` should always be the last logit processor, when present
+ if generation_config.renormalize_logits is True:
+ processors.append(LogitNormalization())
+ return processors
+
+ def _get_stopping_criteria(
+ self,
+ generation_config: GenerationConfig,
+ stopping_criteria: Optional[StoppingCriteriaList],
+ tokenizer: Optional["PreTrainedTokenizerBase"] = None,
+ **kwargs,
+ ) -> StoppingCriteriaList:
+ criteria = StoppingCriteriaList()
+ if generation_config.max_length is not None:
+ max_position_embeddings = getattr(self.config, "max_position_embeddings", None)
+ criteria.append(
+ MaxLengthCriteria(
+ max_length=generation_config.max_length,
+ max_position_embeddings=max_position_embeddings,
+ )
+ )
+ if generation_config.max_time is not None:
+ criteria.append(MaxTimeCriteria(max_time=generation_config.max_time))
+ if generation_config.stop_strings is not None:
+ if tokenizer is None:
+ raise ValueError(
+ "There are one or more stop strings, either in the arguments to `generate` or in the "
+ "model's generation config, but we could not locate a tokenizer. When generating with "
+ "stop strings, you must pass the model's tokenizer to the `tokenizer` argument of `generate`."
+ )
+ criteria.append(StopStringCriteria(stop_strings=generation_config.stop_strings, tokenizer=tokenizer))
+ if generation_config._eos_token_tensor is not None:
+ criteria.append(EosTokenCriteria(eos_token_id=generation_config._eos_token_tensor))
+ if (
+ generation_config.is_assistant
+ and generation_config.assistant_confidence_threshold is not None
+ and generation_config.assistant_confidence_threshold > 0
+ ):
+ criteria.append(
+ ConfidenceCriteria(assistant_confidence_threshold=generation_config.assistant_confidence_threshold)
+ )
+ criteria = self._merge_criteria_processor_list(criteria, stopping_criteria)
+ return criteria
+
+ def _merge_criteria_processor_list(
+ self,
+ default_list: Union[LogitsProcessorList, StoppingCriteriaList],
+ custom_list: Union[LogitsProcessorList, StoppingCriteriaList],
+ ) -> Union[LogitsProcessorList, StoppingCriteriaList]:
+ if len(custom_list) == 0:
+ return default_list
+ for default in default_list:
+ for custom in custom_list:
+ if type(custom) is type(default):
+ object_type = "stopping criteria" if isinstance(custom, StoppingCriteria) else "logits processor"
+ raise ValueError(
+ f"A custom {object_type} of type {type(custom)} with values {custom} has been passed to"
+ f" `.generate()`, but it has already been created with the values {default}. {default} has been"
+ " created by passing the corresponding arguments to generate or by the model's config default"
+ f" values. If you just want to change the default values of {object_type} consider passing"
+ f" them as arguments to `.generate()` instead of using a custom {object_type}."
+ )
+ default_list.extend(custom_list)
+ return default_list
+
+ def compute_transition_scores(
+ self,
+ sequences: torch.Tensor,
+ scores: Tuple[torch.Tensor],
+ beam_indices: Optional[torch.Tensor] = None,
+ normalize_logits: bool = False,
+ ) -> torch.Tensor:
+ """
+ Computes the transition scores of sequences given the generation scores (and beam indices, if beam search was
+ used). This is a convenient method to quicky obtain the scores of the selected tokens at generation time.
+
+ Parameters:
+ sequences (`torch.LongTensor`):
+ The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or
+ shorter if all batches finished early due to the `eos_token_id`.
+ scores (`tuple(torch.FloatTensor)`):
+ Transition scores for each vocabulary token at each generation step. Beam transition scores consisting
+ of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
+ Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
+ with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
+ beam_indices (`torch.LongTensor`, *optional*):
+ Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
+ `(batch_size*num_return_sequences, sequence_length)`. Only required if a `num_beams>1` at
+ generate-time.
+ normalize_logits (`bool`, *optional*, defaults to `False`):
+ Whether to normalize the logits (which, for legacy reasons, may be unnormalized).
+
+ Return:
+ `torch.Tensor`: A `torch.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)` containing
+ the transition scores (logits)
+
+ Examples:
+
+ ```python
+ >>> from transformers import GPT2Tokenizer, AutoModelForCausalLM
+ >>> import numpy as np
+
+ >>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
+ >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
+ >>> tokenizer.pad_token_id = tokenizer.eos_token_id
+ >>> inputs = tokenizer(["Today is"], return_tensors="pt")
+
+ >>> # Example 1: Print the scores for each token generated with Greedy Search
+ >>> outputs = model.generate(**inputs, max_new_tokens=5, return_dict_in_generate=True, output_scores=True)
+ >>> transition_scores = model.compute_transition_scores(
+ ... outputs.sequences, outputs.scores, normalize_logits=True
+ ... )
+ >>> # input_length is the length of the input prompt for decoder-only models, like the GPT family, and 1 for
+ >>> # encoder-decoder models, like BART or T5.
+ >>> input_length = 1 if model.config.is_encoder_decoder else inputs.input_ids.shape[1]
+ >>> generated_tokens = outputs.sequences[:, input_length:]
+ >>> for tok, score in zip(generated_tokens[0], transition_scores[0]):
+ ... # | token | token string | log probability | probability
+ ... print(f"| {tok:5d} | {tokenizer.decode(tok):8s} | {score.numpy():.3f} | {np.exp(score.numpy()):.2%}")
+ | 262 | the | -1.414 | 24.33%
+ | 1110 | day | -2.609 | 7.36%
+ | 618 | when | -2.010 | 13.40%
+ | 356 | we | -1.859 | 15.58%
+ | 460 | can | -2.508 | 8.14%
+
+ >>> # Example 2: Reconstruct the sequence scores from Beam Search
+ >>> outputs = model.generate(
+ ... **inputs,
+ ... max_new_tokens=5,
+ ... num_beams=4,
+ ... num_return_sequences=4,
+ ... return_dict_in_generate=True,
+ ... output_scores=True,
+ ... )
+ >>> transition_scores = model.compute_transition_scores(
+ ... outputs.sequences, outputs.scores, outputs.beam_indices, normalize_logits=False
+ ... )
+ >>> # If you sum the generated tokens' scores and apply the length penalty, you'll get the sequence scores.
+ >>> # Tip 1: recomputing the scores is only guaranteed to match with `normalize_logits=False`. Depending on the
+ >>> # use case, you might want to recompute it with `normalize_logits=True`.
+ >>> # Tip 2: the output length does NOT include the input length
+ >>> output_length = np.sum(transition_scores.numpy() < 0, axis=1)
+ >>> length_penalty = model.generation_config.length_penalty
+ >>> reconstructed_scores = transition_scores.sum(axis=1) / (output_length**length_penalty)
+ >>> print(np.allclose(outputs.sequences_scores, reconstructed_scores))
+ True
+ ```"""
+ # 1. In absence of `beam_indices`, we can assume that we come from e.g. greedy search, which is equivalent
+ # to a beam search approach were the first (and only) beam is always selected
+ if beam_indices is None:
+ beam_indices = torch.arange(scores[0].shape[0]).view(-1, 1).to(sequences.device)
+ beam_indices = beam_indices.expand(-1, len(scores))
+
+ # 2. reshape scores as [batch_size*vocab_size, # generation steps] with # generation steps being
+ # seq_len - input_length
+ scores = torch.stack(scores).reshape(len(scores), -1).transpose(0, 1)
+
+ # 3. Optionally normalize the logits (across the vocab dimension)
+ if normalize_logits:
+ scores = scores.reshape(-1, self.config.vocab_size, scores.shape[-1])
+ scores = torch.nn.functional.log_softmax(scores, dim=1)
+ scores = scores.reshape(-1, scores.shape[-1])
+
+ # 4. cut beam_indices to longest beam length
+ beam_indices_mask = beam_indices < 0
+ max_beam_length = (1 - beam_indices_mask.long()).sum(-1).max()
+ beam_indices = beam_indices.clone()[:, :max_beam_length]
+ beam_indices_mask = beam_indices_mask[:, :max_beam_length]
+
+ # 5. Set indices of beams that finished early to 0; such indices will be masked correctly afterwards
+ beam_indices[beam_indices_mask] = 0
+
+ # 6. multiply beam_indices with vocab size to gather correctly from scores
+ beam_sequence_indices = beam_indices * self.config.vocab_size
+
+ # 7. Define which indices contributed to scores
+ cut_idx = sequences.shape[-1] - max_beam_length
+ indices = sequences[:, cut_idx:] + beam_sequence_indices
+
+ # 8. Compute scores
+ transition_scores = scores.gather(0, indices)
+
+ # 9. Mask out transition_scores of beams that stopped early
+ transition_scores[beam_indices_mask] = 0
+
+ return transition_scores
+
+ def _validate_model_class(self):
+ """
+ Confirms that the model class is compatible with generation. If not, raises an exception that points to the
+ right class to use.
+ """
+ # TODO(joao): remove this function in v4.50, i.e. when we remove the inheritance of `GenerationMixin` from
+ # `PreTrainedModel`. With that inheritance removed, all model classes inheriting from `GenerationMixin` can
+ # safely call `GenerationMixin.generate`
+ if not is_torchdynamo_compiling() and not self.can_generate():
+ terminations_with_generation_support = [
+ "ForCausalLM",
+ "ForConditionalGeneration",
+ "ForSpeechSeq2Seq",
+ "ForVision2Seq",
+ ]
+ raise TypeError(
+ f"The current model class ({self.__class__.__name__}) is not compatible with `.generate()`, as "
+ "it doesn't have a language model head. Classes that support generation often end in one of these "
+ f"names: {terminations_with_generation_support}."
+ )
+
+ def _validate_assistant(self, assistant_model, tokenizer, assistant_tokenizer):
+ if assistant_model is None:
+ return
+
+ if self.config.is_encoder_decoder and not assistant_model.config.is_encoder_decoder:
+ attributes_to_check = ["encoder_attention_heads", "encoder_ffn_dim", "encoder_layers"]
+ attributes_to_check = [attr for attr in dir(assistant_model.config) if attr in attributes_to_check]
+ are_equal = all(
+ getattr(self.config, attr) == getattr(assistant_model.config, attr) for attr in attributes_to_check
+ )
+ if not are_equal:
+ raise ValueError(
+ "The main model and the assistant don't have compatible encoder-dependent input shapes. "
+ "Ensure you load the assistant with the correct encoder-decoder class, e.g. `AutoModelForSpeechSeq2Seq` for Whisper."
+ )
+
+ doc_reference = (
+ "(see https://huggingface.co/docs/transformers/en/generation_strategies#universal-assisted-decoding)"
+ )
+ if self.config.get_text_config().vocab_size == assistant_model.config.get_text_config().vocab_size:
+ if assistant_tokenizer is not None:
+ raise ValueError(
+ f"`assistant_tokenizer` is not required when the main and assistant models use the same tokenizer. Please omit `assistant_tokenizer` from `generate()` {doc_reference}."
+ )
+ else:
+ if tokenizer is None or assistant_tokenizer is None:
+ raise ValueError(
+ f"The main and assistant moedels have different tokenizers. Please provide `tokenizer` and `assistant_tokenizer` to `generate()` {doc_reference}."
+ )
+
+ def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]):
+ """Validates model kwargs for generation. Generate argument typos will also be caught here."""
+ # If a `Cache` instance is passed, checks whether the model is compatible with it
+ if isinstance(model_kwargs.get("past_key_values", None), Cache) and not self._supports_cache_class:
+ raise ValueError(
+ f"{self.__class__.__name__} does not support an instance of `Cache` as `past_key_values`. Please "
+ "check the model documentation for supported cache formats."
+ )
+
+ # Excludes arguments that are handled before calling any model function
+ if self.config.is_encoder_decoder:
+ for key in ["decoder_input_ids"]:
+ model_kwargs.pop(key, None)
+
+ unused_model_args = []
+ model_args = set(inspect.signature(self.prepare_inputs_for_generation).parameters)
+ # `kwargs`/`model_kwargs` is often used to handle optional forward pass inputs like `attention_mask`. If
+ # `prepare_inputs_for_generation` doesn't accept them, then a stricter check can be made ;)
+ if "kwargs" in model_args or "model_kwargs" in model_args:
+ model_args |= set(inspect.signature(self.forward).parameters)
+
+ # Encoder-Decoder models may also need Encoder arguments from `model_kwargs`
+ if self.config.is_encoder_decoder:
+ base_model = getattr(self, self.base_model_prefix, None)
+
+ # allow encoder kwargs
+ encoder = getattr(self, "encoder", None)
+ # `MusicgenForConditionalGeneration` has `text_encoder` and `audio_encoder`.
+ # Also, it has `base_model_prefix = "encoder_decoder"` but there is no `self.encoder_decoder`
+ # TODO: A better way to handle this.
+ if encoder is None and base_model is not None:
+ encoder = getattr(base_model, "encoder", None)
+
+ if encoder is not None:
+ encoder_model_args = set(inspect.signature(encoder.forward).parameters)
+ model_args |= encoder_model_args
+
+ # allow decoder kwargs
+ decoder = getattr(self, "decoder", None)
+ if decoder is None and base_model is not None:
+ decoder = getattr(base_model, "decoder", None)
+
+ if decoder is not None:
+ decoder_model_args = set(inspect.signature(decoder.forward).parameters)
+ model_args |= {f"decoder_{x}" for x in decoder_model_args}
+
+ for key, value in model_kwargs.items():
+ if value is not None and key not in model_args:
+ unused_model_args.append(key)
+
+ if unused_model_args:
+ raise ValueError(
+ f"The following `model_kwargs` are not used by the model: {unused_model_args} (note: typos in the"
+ " generate arguments will also show up in this list)"
+ )
+
+ def _validate_generated_length(self, generation_config, input_ids_length, has_default_max_length):
+ """Performs validation related to the resulting generated length"""
+
+ # Can't throw warnings/exceptions during compilation
+ if is_torchdynamo_compiling():
+ return
+
+ # 1. Max length warnings related to poor parameterization
+ if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length == 20:
+ # 20 is the default max_length of the generation config
+ warnings.warn(
+ f"Using the model-agnostic default `max_length` (={generation_config.max_length}) to control the "
+ "generation length. We recommend setting `max_new_tokens` to control the maximum length of the "
+ "generation.",
+ UserWarning,
+ )
+ if input_ids_length >= generation_config.max_length:
+ input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
+ raise ValueError(
+ f"Input length of {input_ids_string} is {input_ids_length}, but `max_length` is set to"
+ f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
+ " increasing `max_length` or, better yet, setting `max_new_tokens`."
+ )
+
+ # 2. Min length warnings due to unfeasible parameter combinations
+ min_length_error_suffix = (
+ " Generation will stop at the defined maximum length. You should decrease the minimum length and/or "
+ "increase the maximum length."
+ )
+ if has_default_max_length:
+ min_length_error_suffix += (
+ f" Note that `max_length` is set to {generation_config.max_length}, its default value."
+ )
+ if generation_config.min_length is not None and generation_config.min_length > generation_config.max_length:
+ warnings.warn(
+ f"Unfeasible length constraints: `min_length` ({generation_config.min_length}) is larger than"
+ f" the maximum possible length ({generation_config.max_length})." + min_length_error_suffix,
+ UserWarning,
+ )
+ if generation_config.min_new_tokens is not None:
+ min_length = generation_config.min_new_tokens + input_ids_length
+ if min_length > generation_config.max_length:
+ warnings.warn(
+ f"Unfeasible length constraints: `min_new_tokens` ({generation_config.min_new_tokens}), when "
+ f"added to the prompt length ({input_ids_length}), is larger than"
+ f" the maximum possible length ({generation_config.max_length})." + min_length_error_suffix,
+ UserWarning,
+ )
+
+ def _prepare_generated_length(
+ self,
+ generation_config,
+ has_default_max_length,
+ has_default_min_length,
+ model_input_name,
+ input_ids_length,
+ inputs_tensor,
+ ):
+ """Prepared max and min length in generation configs to avoid clashes between similar attributes"""
+
+ if generation_config.max_new_tokens is not None:
+ if not has_default_max_length and generation_config.max_length is not None:
+ logger.warning(
+ f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
+ f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
+ "Please refer to the documentation for more information. "
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
+ )
+ generation_config.max_length = generation_config.max_new_tokens + input_ids_length
+
+ # if both `inputs_embeds` and `input_ids` are passed, we do not correct the length
+ # otherwise we need total length [inputs-embeds-len + new-tokens-len] to not go beyond indicated `max_length``
+ elif (
+ model_input_name == "inputs_embeds"
+ and input_ids_length != inputs_tensor.shape[1]
+ and not self.config.is_encoder_decoder
+ ):
+ generation_config.max_length -= inputs_tensor.shape[1]
+ elif has_default_max_length: # by default let's always generate 20 new tokens
+ if generation_config.max_length == GenerationConfig().max_length:
+ generation_config.max_length = generation_config.max_length + input_ids_length
+ max_position_embeddings = getattr(self.config, "max_position_embeddings", None)
+ if max_position_embeddings is not None:
+ generation_config.max_length = min(generation_config.max_length, max_position_embeddings)
+
+ # same for min length
+ if generation_config.min_new_tokens is not None:
+ if not has_default_min_length:
+ logger.warning(
+ f"Both `min_new_tokens` (={generation_config.min_new_tokens}) and `min_length`(="
+ f"{generation_config.min_length}) seem to have been set. `min_new_tokens` will take precedence. "
+ "Please refer to the documentation for more information. "
+ "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
+ )
+ generation_config.min_length = generation_config.min_new_tokens + input_ids_length
+
+ elif (
+ model_input_name == "inputs_embeds"
+ and input_ids_length != inputs_tensor.shape[1]
+ and not self.config.is_encoder_decoder
+ ):
+ generation_config.min_length = max(generation_config.min_length - inputs_tensor.shape[1], 0)
+
+ return generation_config
+
+ def _prepare_generation_config(
+ self, generation_config: Optional[GenerationConfig], **kwargs: Dict
+ ) -> Tuple[GenerationConfig, Dict]:
+ """
+ Prepares the base generation config, then applies any generation configuration options from kwargs. This
+ function handles retrocompatibility with respect to configuration files.
+ """
+ # TODO joao: when we can detect `fullgraph=True` in `torch.compile` (https://github.com/pytorch/pytorch/pull/120400)
+ # replace `is_torchdynamo_compiling` by the corresponding check. As it is, we are being too restrictive with
+ # the parameterization in `fullgraph=False` so as to enable `fullgraph=True`.
+
+ # priority: `generation_config` argument > `model.generation_config` (the default generation config)
+ using_model_generation_config = False
+ if generation_config is None:
+ # legacy: users may modify the model configuration to control generation. To trigger this legacy behavior,
+ # the following conditions must be met
+ # 1) the generation config must have been created from the model config (`_from_model_config` field);
+ # 2) the generation config must have seen no modification since its creation (the hash is the same);
+ # 3) there are non-default generation parameters in the model config.
+ # 4) the user must have set new generation parameters in the model config.
+ # NOTE: `torch.compile` can't compile `hash`, this legacy support is disabled with compilation.
+ if (
+ not is_torchdynamo_compiling()
+ and self.generation_config._from_model_config # 1)
+ and self.generation_config._original_object_hash == hash(self.generation_config) # 2)
+ and len(self.config._get_non_default_generation_parameters()) > 0 # 3)
+ ):
+ new_generation_config = GenerationConfig.from_model_config(self.config)
+ if new_generation_config != self.generation_config: # 4)
+ warnings.warn(
+ "You have modified the pretrained model configuration to control generation. This is a"
+ " deprecated strategy to control generation and will be removed in v5."
+ " Please use and modify the model generation configuration (see"
+ " https://huggingface.co/docs/transformers/generation_strategies#default-text-generation-configuration )",
+ UserWarning,
+ )
+ self.generation_config = new_generation_config
+
+ generation_config = self.generation_config
+ using_model_generation_config = True
+
+ # `torch.compile` can't compile `copy.deepcopy`, arguments in `kwargs` that are part of `generation_config`
+ # will mutate the object with `.update`. As such, passing these arguments through `kwargs` is disabled -- an
+ # exception will be raised in `_validate_model_kwargs`
+ if not is_torchdynamo_compiling():
+ generation_config = copy.deepcopy(generation_config)
+ model_kwargs = generation_config.update(**kwargs)
+ # If `generation_config` is provided, let's fallback ALL special tokens to the default values for the model
+ if not using_model_generation_config:
+ if generation_config.bos_token_id is None:
+ generation_config.bos_token_id = self.generation_config.bos_token_id
+ if generation_config.eos_token_id is None:
+ generation_config.eos_token_id = self.generation_config.eos_token_id
+ if generation_config.pad_token_id is None:
+ generation_config.pad_token_id = self.generation_config.pad_token_id
+ if generation_config.decoder_start_token_id is None:
+ generation_config.decoder_start_token_id = self.generation_config.decoder_start_token_id
+ else:
+ model_kwargs = kwargs
+
+ return generation_config, model_kwargs
+
+ def _get_initial_cache_position(self, input_ids, model_kwargs):
+ """Calculates `cache_position` for the pre-fill stage based on `input_ids` and optionally past length"""
+ # `torch.compile`-friendly `torch.arange` from a shape -- the lines below are equivalent to `torch.arange`
+ if "inputs_embeds" in model_kwargs and not self.config.is_encoder_decoder:
+ cache_position = torch.ones_like(model_kwargs["inputs_embeds"][0, :, 0], dtype=torch.int64).cumsum(0) - 1
+ elif "decoder_inputs_embeds" in model_kwargs and self.config.is_encoder_decoder:
+ cache_position = (
+ torch.ones_like(model_kwargs["decoder_inputs_embeds"][0, :, 0], dtype=torch.int64).cumsum(0) - 1
+ )
+ else:
+ cache_position = torch.ones_like(input_ids[0, :], dtype=torch.int64).cumsum(0) - 1
+
+ past_length = 0
+ if model_kwargs.get("past_key_values") is not None:
+ cache = model_kwargs["past_key_values"]
+ past_length = 0
+ if not isinstance(cache, Cache):
+ past_length = cache[0][0].shape[2]
+ elif hasattr(cache, "get_seq_length") and cache.get_seq_length() is not None:
+ past_length = cache.get_seq_length()
+
+ # TODO(joao): this is not torch.compile-friendly, find a work-around. If the cache is not empty,
+ # end-to-end compilation will yield bad results because `cache_position` will be incorrect.
+ if not is_torchdynamo_compiling():
+ cache_position = cache_position[past_length:]
+
+ model_kwargs["cache_position"] = cache_position
+ return model_kwargs
+
+ def _get_layer_device_map_for_cache_init(self):
+ """
+ Taken from `dispatch_model` from accelerate.
+ This is needed here if we don't want to make changes in accelerate in order to save execution_device
+ For offloaded case, we need to get the execution device, not just the device where it is offloaded
+ """
+ execution_device_map = None
+
+ if hasattr(self, "hf_device_map"):
+ if set(self.hf_device_map.values()) == {"cpu"} or set(self.hf_device_map.values()) == {"cpu", "disk"}:
+ main_device = "cpu"
+ else:
+ main_device = [d for d in self.hf_device_map.values() if d not in ["cpu", "disk"]][0]
+ execution_device_map = {
+ name: main_device if device in ["cpu", "disk"] else device
+ for name, device in self.hf_device_map.items()
+ }
+
+ num_hidden_layers = self.config.get_text_config().num_hidden_layers
+ if execution_device_map is None:
+ return None
+ elif len(execution_device_map) == 1 and "" in execution_device_map:
+ return {idx: execution_device_map[""] for idx in range(num_hidden_layers)}
+ layer_device_map = {}
+ for layer in execution_device_map:
+ for idx in range(num_hidden_layers):
+ if f".{idx}." in f"{layer}.":
+ layer_device_map[idx] = execution_device_map[layer]
+ break
+ for idx in range(num_hidden_layers):
+ if idx not in layer_device_map:
+ raise RuntimeError(f"layer {idx} has not been mapped to a device.")
+ return layer_device_map
+
+ def _get_cache(
+ self, cache_implementation: str, batch_size: int, max_cache_len: int, device: torch.device, model_kwargs
+ ) -> Cache:
+ """
+ Sets a cache for `generate`, that will persist across calls. A new cache will only be initialized a
+ new `generate` call requires a larger cache or uses a different batch size.
+
+ Returns the resulting cache object.
+ """
+ cache_cls: Cache = NEED_SETUP_CACHE_CLASSES_MAPPING[cache_implementation]
+ requires_cross_attention_cache = (
+ self.config.is_encoder_decoder or model_kwargs.get("encoder_outputs") is not None
+ )
+
+ if hasattr(self, "_cache"):
+ cache_to_check = self._cache.self_attention_cache if requires_cross_attention_cache else self._cache
+
+ if cache_implementation == "sliding_window":
+ max_cache_len = min(self.config.sliding_window, max_cache_len)
+
+ need_new_cache = (
+ not hasattr(self, "_cache")
+ or (not isinstance(cache_to_check, cache_cls))
+ or cache_to_check.max_batch_size != batch_size
+ )
+ if cache_implementation != "mamba":
+ need_new_cache = need_new_cache or cache_to_check.max_cache_len < max_cache_len
+
+ if requires_cross_attention_cache and hasattr(self, "_cache"):
+ need_new_cache = (
+ need_new_cache
+ or self._cache.cross_attention_cache.max_cache_len != model_kwargs["encoder_outputs"][0].shape[1]
+ )
+
+ if need_new_cache:
+ if hasattr(self.config, "_pre_quantization_dtype"):
+ cache_dtype = self.config._pre_quantization_dtype
+ else:
+ if not is_torchdynamo_compiling():
+ cache_dtype = self.dtype
+ else:
+ # NOTE: self.dtype is not compatible with torch.compile, as it calls `self.parameters()`.
+ # Workaround: trust the lm_head, whose attribute name is somewhat consistent across generative
+ # models. May cause trobles with non-text modalities.
+ cache_dtype = self.get_output_embeddings().weight.dtype
+
+ layer_device_map = self._get_layer_device_map_for_cache_init()
+ cache_kwargs = {
+ "config": self.config.get_text_config(),
+ "max_batch_size": batch_size,
+ "max_cache_len": max_cache_len,
+ "dtype": cache_dtype,
+ "device": device,
+ "layer_device_map": layer_device_map,
+ }
+ self._cache = cache_cls(**cache_kwargs)
+ if requires_cross_attention_cache:
+ encoder_kwargs = cache_kwargs.copy()
+ encoder_kwargs["max_cache_len"] = model_kwargs["encoder_outputs"][0].shape[1]
+ self._cache = EncoderDecoderCache(self._cache, cache_cls(**encoder_kwargs))
+ else:
+ self._cache.reset()
+ return self._cache
+
+ def _supports_default_dynamic_cache(self) -> bool:
+ """
+ Return `True` if current model can use a `DynamicCache` instance when initializing the `past_key_values`.
+ This is mostly the same as `_supports_cache_class` attribute, but add exception for `Jamba` model which
+ uses its own `HybridMambaAttentionDynamicCache` and do not need to initialize the Cache in advance in
+ order to save memory (because no back and forth `to_legacy_cache` and `from_legacy_cache` will be performed
+ for `HybridMambaAttentionDynamicCache`).
+ """
+ return (
+ self._supports_cache_class
+ and "jamba" not in self.__class__.__name__.lower()
+ and "zamba" not in self.__class__.__name__.lower()
+ and "bamba" not in self.__class__.__name__.lower()
+ )
+
+ def _prepare_cache_for_generation(
+ self,
+ generation_config: GenerationConfig,
+ model_kwargs: Dict,
+ assistant_model: "PreTrainedModel",
+ batch_size: int,
+ max_cache_length: int,
+ device: torch.device,
+ ) -> bool:
+ """
+ Prepares the cache for generation (if applicable), given `generate`'s parameterization. If a cache is
+ instantiated, writes it to `model_kwargs`, under the name expected by the model.
+ """
+
+ cache_name = "past_key_values" if "mamba" not in self.__class__.__name__.lower() else "cache_params"
+ requires_cross_attention_cache = (
+ self.config.is_encoder_decoder or model_kwargs.get("encoder_outputs") is not None
+ )
+
+ # Quick escape route 1: if the user specifies a cache, we only need to:
+ # a) check for conflicting `generate` arguments
+ # b) convert to the new cache format (if the user passes a legacy cache and model supports it)
+ user_defined_cache = model_kwargs.get(cache_name)
+ if user_defined_cache is not None:
+ if generation_config.cache_implementation is not None:
+ raise ValueError(
+ f"Passing both `cache_implementation` (used to initialize certain caches) and `{cache_name}` (a "
+ "Cache object) is unsupported. Please use only one of the two."
+ )
+ if isinstance(user_defined_cache, tuple) and self._supports_default_dynamic_cache():
+ model_kwargs[cache_name] = (
+ DynamicCache.from_legacy_cache(user_defined_cache)
+ if not requires_cross_attention_cache
+ else EncoderDecoderCache.from_legacy_cache(user_defined_cache)
+ )
+ return
+
+ # Quick escape route 2: if the user specifies no cache is to be used. (conflicting arguments are handled in
+ # `generation_config.validate()`)
+ if generation_config.use_cache is False:
+ return
+
+ # Quick escape route 3: model that only supports legacy caches = nothing to prepare
+ if not self._supports_default_dynamic_cache():
+ if generation_config.cache_implementation is not None:
+ warnings.warn(
+ "This model does not support `Cache` instances, it only supports the legacy cache format (tuple "
+ f"of tuples). `cache_implementation` (set to {generation_config.cache_implementation}) will be "
+ "ignored.",
+ UserWarning,
+ )
+ return
+
+ # Otherwise we NEED to prepare a cache, based on `generation_config.cache_implementation`
+
+ # TODO(joao): support static caches in assisted generation. assisted generation needs to roll back caches,
+ # which is only supported in dynamic caches atm
+ if assistant_model is not None and generation_config.cache_implementation is not None:
+ logger.warning_once(
+ "An assistant model is provided, using a dynamic cache instead of a cache of type="
+ f"'{generation_config.cache_implementation}'."
+ )
+ generation_config.cache_implementation = None
+
+ if generation_config.cache_implementation is not None:
+ if generation_config.cache_implementation in NEED_SETUP_CACHE_CLASSES_MAPPING:
+ if generation_config.cache_implementation == "static" and not self._supports_static_cache:
+ raise ValueError(
+ "This model does not support `cache_implementation='static'`. Please check the following "
+ "issue: https://github.com/huggingface/transformers/issues/28981"
+ )
+ model_kwargs[cache_name] = self._get_cache(
+ cache_implementation=generation_config.cache_implementation,
+ batch_size=max(generation_config.num_beams, generation_config.num_return_sequences) * batch_size,
+ max_cache_len=max_cache_length,
+ device=device,
+ model_kwargs=model_kwargs,
+ )
+ elif generation_config.cache_implementation == "quantized":
+ if not self._supports_quantized_cache:
+ raise ValueError(
+ "This model does not support the quantized cache. If you want your model to support quantized "
+ "cache, please open an issue and tag @zucchini-nlp."
+ )
+
+ cache_config = (
+ generation_config.cache_config
+ if generation_config.cache_config is not None
+ else QuantizedCacheConfig()
+ )
+ cache_class = QUANT_BACKEND_CLASSES_MAPPING[cache_config.backend]
+
+ if cache_config.backend == "quanto" and not is_optimum_quanto_available():
+ raise ImportError(
+ "You need to install optimum-quanto in order to use KV cache quantization with optimum-quanto backend. "
+ "Please install it via with `pip install optimum-quanto`"
+ )
+ elif cache_config.backend == "HQQ" and not is_hqq_available():
+ raise ImportError(
+ "You need to install `HQQ` in order to use KV cache quantization with HQQ backend. "
+ "Please install it via with `pip install hqq`"
+ )
+
+ model_kwargs[cache_name] = cache_class(cache_config)
+ elif generation_config.cache_implementation == "offloaded":
+ model_kwargs[cache_name] = OffloadedCache()
+
+ # Use DynamicCache() instance by default. This will avoid back and forth from legacy format that
+ # keeps copying the cache thus using much more memory
+ else:
+ model_kwargs[cache_name] = (
+ DynamicCache()
+ if not requires_cross_attention_cache
+ else EncoderDecoderCache(DynamicCache(), DynamicCache())
+ )
+
+ def _supports_logits_to_keep(self) -> bool:
+ """
+ Return True if the current model supports the keyword argument `logits_to_keep` in forward()
+ to save memory. Checking it in this way allows to avoid using a new model attribute.
+ """
+ return "logits_to_keep" in set(inspect.signature(self.forward).parameters.keys())
+
+ def _prepare_special_tokens(
+ self,
+ generation_config: GenerationConfig,
+ kwargs_has_attention_mask: Optional[bool] = None,
+ device: Optional[Union[torch.device, str]] = None,
+ ):
+ """
+ Prepares the special tokens for generation, overwriting the generation config with their processed versions
+ converted to tensor.
+
+ Note that `generation_config` is changed in place and stops being serializable after this method is called.
+ That is no problem if called within `generate` (`generation_config` is a local copy that doesn't leave the
+ function). However, if called outside `generate`, consider creating a copy of `generation_config` first.
+ """
+
+ # Convert special tokens to tensors
+ def _tensor_or_none(token, device=None):
+ if token is None:
+ return token
+
+ device = device if device is not None else self.device
+ if isinstance(token, torch.Tensor):
+ return token.to(device)
+ return torch.tensor(token, device=device, dtype=torch.long)
+
+ bos_token_tensor = _tensor_or_none(generation_config.bos_token_id, device=device)
+ eos_token_tensor = _tensor_or_none(generation_config.eos_token_id, device=device)
+ pad_token_tensor = _tensor_or_none(generation_config.pad_token_id, device=device)
+ decoder_start_token_tensor = _tensor_or_none(generation_config.decoder_start_token_id, device=device)
+
+ # for BC we also try to get `decoder_start_token_id` or `bos_token_id` (#30892)
+ if self.config.is_encoder_decoder:
+ decoder_start_token_tensor = (
+ decoder_start_token_tensor if decoder_start_token_tensor is not None else bos_token_tensor
+ )
+
+ # We can have more than one eos token. Always treat it as a 1D tensor (when it exists).
+ if eos_token_tensor is not None and eos_token_tensor.ndim == 0:
+ eos_token_tensor = eos_token_tensor.unsqueeze(0)
+
+ # Set pad token if unset (and there are conditions to do so)
+ if pad_token_tensor is None and eos_token_tensor is not None:
+ if not is_torchdynamo_compiling():
+ if kwargs_has_attention_mask is not None and not kwargs_has_attention_mask:
+ logger.warning(
+ "The attention mask and the pad token id were not set. As a consequence, you may observe "
+ "unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results."
+ )
+ pad_token_tensor = eos_token_tensor[0]
+ logger.warning(f"Setting `pad_token_id` to `eos_token_id`:{pad_token_tensor} for open-end generation.")
+
+ # Sanity checks/warnings
+ if self.config.is_encoder_decoder and decoder_start_token_tensor is None:
+ raise ValueError(
+ "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation."
+ )
+ if not is_torchdynamo_compiling(): # Checks that depend on tensor-dependent control flow
+ if (
+ eos_token_tensor is not None
+ and isin_mps_friendly(elements=eos_token_tensor, test_elements=pad_token_tensor).any()
+ ):
+ if kwargs_has_attention_mask is not None and not kwargs_has_attention_mask:
+ logger.warning_once(
+ "The attention mask is not set and cannot be inferred from input because pad token is same as "
+ "eos token. As a consequence, you may observe unexpected behavior. Please pass your input's "
+ "`attention_mask` to obtain reliable results."
+ )
+ if eos_token_tensor is not None and (
+ torch.is_floating_point(eos_token_tensor) or (eos_token_tensor < 0).any()
+ ):
+ logger.warning(
+ f"`eos_token_id` should consist of positive integers, but is {eos_token_tensor}. Your generation "
+ "will not stop until the maximum length is reached. Depending on other flags, it may even crash."
+ )
+
+ # Update generation config with the updated special tokens tensors
+ # NOTE: this must be written into a different attribute name than the one holding the original special tokens
+ # (in their non-tensor form), in order to enable end-to-end compilation. See
+ # https://pytorch.org/docs/stable/torch.compiler_cudagraph_trees.html#limitations
+ generation_config._bos_token_tensor = bos_token_tensor
+ generation_config._eos_token_tensor = eos_token_tensor
+ generation_config._pad_token_tensor = pad_token_tensor
+ generation_config._decoder_start_token_tensor = decoder_start_token_tensor
+
+ @torch.no_grad()
+ def generate(
+ self,
+ inputs: Optional[torch.Tensor] = None,
+ generation_config: Optional[GenerationConfig] = None,
+ logits_processor: Optional[LogitsProcessorList] = None,
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
+ synced_gpus: Optional[bool] = None,
+ assistant_model: Optional["PreTrainedModel"] = None,
+ streamer: Optional["BaseStreamer"] = None,
+ negative_prompt_ids: Optional[torch.Tensor] = None,
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> Union[GenerateOutput, torch.LongTensor]:
+ r"""
+
+ Generates sequences of token ids for models with a language modeling head.
+
+
+
+ Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the
+ model's default generation configuration. You can override any `generation_config` by passing the corresponding
+ parameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`.
+
+ For an overview of generation strategies and code examples, check out the [following
+ guide](../generation_strategies).
+
+
+
+ Parameters:
+ inputs (`torch.Tensor` of varying shape depending on the modality, *optional*):
+ The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the
+ method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs`
+ should be in the format of `input_ids`. For encoder-decoder models *inputs* can represent any of
+ `input_ids`, `input_values`, `input_features`, or `pixel_values`.
+ generation_config ([`~generation.GenerationConfig`], *optional*):
+ The generation configuration to be used as base parametrization for the generation call. `**kwargs`
+ passed to generate matching the attributes of `generation_config` will override them. If
+ `generation_config` is not provided, the default will be used, which has the following loading
+ priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
+ configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
+ default values, whose documentation should be checked to parameterize generation.
+ logits_processor (`LogitsProcessorList`, *optional*):
+ Custom logits processors that complement the default logits processors built from arguments and
+ generation config. If a logit processor is passed that is already created with the arguments or a
+ generation config an error is thrown. This feature is intended for advanced users.
+ stopping_criteria (`StoppingCriteriaList`, *optional*):
+ Custom stopping criteria that complements the default stopping criteria built from arguments and a
+ generation config. If a stopping criteria is passed that is already created with the arguments or a
+ generation config an error is thrown. If your stopping criteria depends on the `scores` input, make
+ sure you pass `return_dict_in_generate=True, output_scores=True` to `generate`. This feature is
+ intended for advanced users.
+ prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`, *optional*):
+ If provided, this function constraints the beam search to allowed tokens only at each step. If not
+ provided no constraint is applied. This function takes 2 arguments: the batch ID `batch_id` and
+ `input_ids`. It has to return a list with the allowed tokens for the next generation step conditioned
+ on the batch ID `batch_id` and the previously generated tokens `inputs_ids`. This argument is useful
+ for constrained generation conditioned on the prefix, as described in [Autoregressive Entity
+ Retrieval](https://arxiv.org/abs/2010.00904).
+ synced_gpus (`bool`, *optional*):
+ Whether to continue running the while loop until max_length. Unless overridden, this flag will be set
+ to `True` if using `FullyShardedDataParallel` or DeepSpeed ZeRO Stage 3 with multiple GPUs to avoid
+ deadlocking if one GPU finishes generating before other GPUs. Otherwise, defaults to `False`.
+ assistant_model (`PreTrainedModel`, *optional*):
+ An assistant model that can be used to accelerate generation. The assistant model must have the exact
+ same tokenizer. The acceleration is achieved when forecasting candidate tokens with the assistant model
+ is much faster than running generation with the model you're calling generate from. As such, the
+ assistant model should be much smaller.
+ streamer (`BaseStreamer`, *optional*):
+ Streamer object that will be used to stream the generated sequences. Generated tokens are passed
+ through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
+ negative_prompt_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ The negative prompt needed for some processors such as CFG. The batch size must match the input batch
+ size. This is an experimental feature, subject to breaking API changes in future versions.
+ negative_prompt_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Attention_mask for `negative_prompt_ids`.
+ kwargs (`Dict[str, Any]`, *optional*):
+ Ad hoc parametrization of `generation_config` and/or additional model-specific kwargs that will be
+ forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
+ specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.
+
+ Return:
+ [`~utils.ModelOutput`] or `torch.LongTensor`: A [`~utils.ModelOutput`] (if `return_dict_in_generate=True`
+ or when `config.return_dict_in_generate=True`) or a `torch.LongTensor`.
+
+ If the model is *not* an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible
+ [`~utils.ModelOutput`] types are:
+
+ - [`~generation.GenerateDecoderOnlyOutput`],
+ - [`~generation.GenerateBeamDecoderOnlyOutput`]
+
+ If the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible
+ [`~utils.ModelOutput`] types are:
+
+ - [`~generation.GenerateEncoderDecoderOutput`],
+ - [`~generation.GenerateBeamEncoderDecoderOutput`]
+ """
+
+ # 1. Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call
+ self._validate_model_class()
+ tokenizer = kwargs.pop("tokenizer", None) # Pull this out first, we only use it for stopping criteria
+ assistant_tokenizer = kwargs.pop("assistant_tokenizer", None) # only used for assisted generation
+
+ generation_config, model_kwargs = self._prepare_generation_config(generation_config, **kwargs)
+ self._validate_model_kwargs(model_kwargs.copy())
+ self._validate_assistant(assistant_model, tokenizer, assistant_tokenizer)
+
+ # 2. Set generation parameters if not already defined
+ if synced_gpus is None:
+ synced_gpus = (is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)) and dist.get_world_size() > 1
+
+ logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
+ stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
+
+ accepts_attention_mask = "attention_mask" in set(inspect.signature(self.forward).parameters.keys())
+ requires_attention_mask = "encoder_outputs" not in model_kwargs
+ kwargs_has_attention_mask = model_kwargs.get("attention_mask", None) is not None
+
+ # 3. Define model inputs
+ inputs_tensor, model_input_name, model_kwargs = self._prepare_model_inputs(
+ inputs, generation_config.bos_token_id, model_kwargs
+ )
+ batch_size = inputs_tensor.shape[0]
+
+ device = inputs_tensor.device
+ self._prepare_special_tokens(generation_config, kwargs_has_attention_mask, device=device)
+
+ # decoder-only models must use left-padding for batched generation.
+ if not self.config.is_encoder_decoder and not is_torchdynamo_compiling():
+ # If `input_ids` was given, check if the last id in any sequence is `pad_token_id`
+ # Note: If using, `inputs_embeds` this check does not work, because we want to be more hands-off.
+ if (
+ generation_config._pad_token_tensor is not None
+ and batch_size > 1
+ and len(inputs_tensor.shape) == 2
+ and torch.sum(inputs_tensor[:, -1] == generation_config._pad_token_tensor) > 0
+ ):
+ logger.warning(
+ "A decoder-only architecture is being used, but right-padding was detected! For correct "
+ "generation results, please set `padding_side='left'` when initializing the tokenizer."
+ )
+
+ # 4. Define other model kwargs
+ # decoder-only models with inputs_embeds forwarding must use caching (otherwise we can't detect whether we are
+ # generating the first new token or not, and we only want to use the embeddings for the first new token)
+ if not self.config.is_encoder_decoder and model_input_name == "inputs_embeds":
+ generation_config.use_cache = True
+
+ if not kwargs_has_attention_mask and requires_attention_mask and accepts_attention_mask:
+ model_kwargs["attention_mask"] = self._prepare_attention_mask_for_generation(
+ inputs_tensor, generation_config, model_kwargs
+ )
+ elif kwargs_has_attention_mask:
+ # TODO (joao): generalize this check with other types of inputs
+ if model_input_name == "input_ids" and len(model_kwargs["attention_mask"].shape) > 2:
+ raise ValueError("`attention_mask` passed to `generate` must be 2D.")
+
+ if self.config.is_encoder_decoder and "encoder_outputs" not in model_kwargs:
+ # if model is encoder decoder encoder_outputs are created and added to `model_kwargs`
+ model_kwargs = self._prepare_encoder_decoder_kwargs_for_generation(
+ inputs_tensor, model_kwargs, model_input_name, generation_config
+ )
+
+ # 5. Prepare `input_ids` which will be used for auto-regressive generation
+ if self.config.is_encoder_decoder:
+ input_ids, model_kwargs = self._prepare_decoder_input_ids_for_generation(
+ batch_size=batch_size,
+ model_input_name=model_input_name,
+ model_kwargs=model_kwargs,
+ decoder_start_token_id=generation_config._decoder_start_token_tensor,
+ device=inputs_tensor.device,
+ )
+ else:
+ input_ids = inputs_tensor if model_input_name == "input_ids" else model_kwargs.pop("input_ids")
+
+ if generation_config.token_healing:
+ input_ids = self.heal_tokens(input_ids, tokenizer)
+
+ if streamer is not None:
+ streamer.put(input_ids.cpu())
+
+ # 6. Prepare `max_length` depending on other stopping criteria.
+ input_ids_length = input_ids.shape[-1]
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
+ has_default_min_length = kwargs.get("min_length") is None and generation_config.min_length is not None
+ generation_config = self._prepare_generated_length(
+ generation_config=generation_config,
+ has_default_max_length=has_default_max_length,
+ has_default_min_length=has_default_min_length,
+ model_input_name=model_input_name,
+ inputs_tensor=inputs_tensor,
+ input_ids_length=input_ids_length,
+ )
+
+ # If the model supports `logits_to_keep` in forward(), set it to 1 to avoid computing the whole
+ # logit matrix. This can save a lot of memory during the first forward pass. Note that assisted decoding
+ # dynamically overrides this value as it can need more than the last token logits
+ if self._supports_logits_to_keep() and "logits_to_keep" not in model_kwargs:
+ model_kwargs["logits_to_keep"] = 1
+
+ self._validate_generated_length(generation_config, input_ids_length, has_default_max_length)
+
+ # 7. Prepare the cache.
+ # - `model_kwargs` may be updated in place with a cache as defined by the parameters in `generation_config`.
+ # - different models have a different cache name expected by the model (default = "past_key_values")
+ # - `max_length`, prepared above, is used to determine the maximum cache length
+ max_cache_length = generation_config.max_length - 1
+ if (
+ inputs_tensor.shape[1] != input_ids_length
+ and model_input_name == "inputs_embeds"
+ and not self.config.is_encoder_decoder
+ ):
+ max_cache_length += inputs_tensor.shape[1]
+ self._prepare_cache_for_generation(
+ generation_config, model_kwargs, assistant_model, batch_size, max_cache_length, device
+ )
+
+ # 8. determine generation mode
+ generation_mode = generation_config.get_generation_mode(assistant_model)
+
+ if streamer is not None and (generation_config.num_beams > 1):
+ raise ValueError(
+ "`streamer` cannot be used with beam search (yet!). Make sure that `num_beams` is set to 1."
+ )
+
+ if not is_torchdynamo_compiling() and self.device.type != input_ids.device.type:
+ warnings.warn(
+ "You are calling .generate() with the `input_ids` being on a device type different"
+ f" than your model's device. `input_ids` is on {input_ids.device.type}, whereas the model"
+ f" is on {self.device.type}. You may experience unexpected behaviors or slower generation."
+ " Please make sure that you have put `input_ids` to the"
+ f" correct device by calling for example input_ids = input_ids.to('{self.device.type}') before"
+ " running `.generate()`.",
+ UserWarning,
+ )
+
+ # 9. prepare logits processors and stopping criteria
+ prepared_logits_processor = self._get_logits_processor(
+ generation_config=generation_config,
+ input_ids_seq_length=input_ids_length,
+ encoder_input_ids=inputs_tensor,
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
+ logits_processor=logits_processor,
+ device=inputs_tensor.device,
+ model_kwargs=model_kwargs,
+ negative_prompt_ids=negative_prompt_ids,
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
+ )
+ prepared_stopping_criteria = self._get_stopping_criteria(
+ generation_config=generation_config, stopping_criteria=stopping_criteria, tokenizer=tokenizer, **kwargs
+ )
+
+ # Set model_kwargs `use_cache` so we can use it later in forward runs
+ model_kwargs["use_cache"] = generation_config.use_cache
+
+ # 10. go into different generation modes
+ if generation_mode == GenerationMode.ASSISTED_GENERATION:
+ if generation_config.num_return_sequences > 1:
+ raise ValueError(
+ "num_return_sequences has to be 1 when doing assisted generate, "
+ f"but is {generation_config.num_return_sequences}."
+ )
+ if batch_size > 1:
+ raise ValueError("assisted generate is only supported for batch_size = 1")
+ if not model_kwargs["use_cache"]:
+ raise ValueError("assisted generate requires `use_cache=True`")
+ if generation_config.cache_implementation in ["static", "hybrid", "sliding_window"]:
+ raise ValueError("assisted generate is not supported with Static cache classes`")
+ if self._is_stateful:
+ # In assisted generation we need the ability to confirm whether the model would pick certain tokens,
+ # which is not possible with stateful models (they can't reset to a previous subset of generated text)
+ raise ValueError(
+ f"assisted generation is not supported with stateful models, such as {self.__class__.__name__}"
+ )
+
+ # 11. Get the candidate generator, given the parameterization
+ candidate_generator = self._get_candidate_generator(
+ generation_config=generation_config,
+ input_ids=input_ids,
+ inputs_tensor=inputs_tensor,
+ assistant_model=assistant_model,
+ logits_processor=logits_processor,
+ target_tokenizer=tokenizer,
+ assistant_tokenizer=assistant_tokenizer,
+ model_kwargs=model_kwargs,
+ )
+
+ # 12. run assisted generate
+ result = self._assisted_decoding(
+ input_ids,
+ candidate_generator=candidate_generator,
+ logits_processor=prepared_logits_processor,
+ stopping_criteria=prepared_stopping_criteria,
+ generation_config=generation_config,
+ synced_gpus=synced_gpus,
+ streamer=streamer,
+ **model_kwargs,
+ )
+ elif generation_mode == GenerationMode.DOLA_GENERATION:
+ if self._is_stateful:
+ # DoLa decoding was not designed for stateful models, and would require some changes
+ raise ValueError(
+ f"dola decoding is not supported with stateful models, such as {self.__class__.__name__}"
+ )
+ result = self._dola_decoding(
+ input_ids,
+ dola_layers=generation_config.dola_layers,
+ logits_processor=prepared_logits_processor,
+ stopping_criteria=prepared_stopping_criteria,
+ generation_config=generation_config,
+ synced_gpus=synced_gpus,
+ streamer=streamer,
+ **model_kwargs,
+ )
+
+ elif generation_mode == GenerationMode.CONTRASTIVE_SEARCH:
+ if not model_kwargs["use_cache"]:
+ raise ValueError("Contrastive search requires `use_cache=True`")
+ if self._is_stateful:
+ # Just like assisted generation, we need to be able to rollback to a previous state (see comment above)
+ raise ValueError(
+ f"contrastive search is not supported with stateful models, such as {self.__class__.__name__}"
+ )
+
+ result = self._contrastive_search(
+ input_ids,
+ logits_processor=prepared_logits_processor,
+ stopping_criteria=prepared_stopping_criteria,
+ generation_config=generation_config,
+ synced_gpus=synced_gpus,
+ streamer=streamer,
+ **model_kwargs,
+ )
+
+ elif generation_mode in (GenerationMode.SAMPLE, GenerationMode.GREEDY_SEARCH):
+ # 11. expand input_ids with `num_return_sequences` additional sequences per batch
+ input_ids, model_kwargs = self._expand_inputs_for_generation(
+ input_ids=input_ids,
+ expand_size=generation_config.num_return_sequences,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ **model_kwargs,
+ )
+
+ # 12. run sample (it degenerates to greedy search when `generation_config.do_sample=False`)
+ result = self._sample(
+ input_ids,
+ logits_processor=prepared_logits_processor,
+ stopping_criteria=prepared_stopping_criteria,
+ generation_config=generation_config,
+ synced_gpus=synced_gpus,
+ streamer=streamer,
+ **model_kwargs,
+ )
+
+ elif generation_mode in (GenerationMode.BEAM_SAMPLE, GenerationMode.BEAM_SEARCH):
+ # 11. prepare beam search scorer
+ beam_scorer = BeamSearchScorer(
+ batch_size=batch_size,
+ num_beams=generation_config.num_beams,
+ device=inputs_tensor.device,
+ length_penalty=generation_config.length_penalty,
+ do_early_stopping=generation_config.early_stopping,
+ num_beam_hyps_to_keep=generation_config.num_return_sequences,
+ max_length=generation_config.max_length,
+ )
+
+ # 12. interleave input_ids with `num_beams` additional sequences per batch
+ input_ids, model_kwargs = self._expand_inputs_for_generation(
+ input_ids=input_ids,
+ expand_size=generation_config.num_beams,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ **model_kwargs,
+ )
+
+ # 13. run beam sample
+ result = self._beam_search(
+ input_ids,
+ beam_scorer,
+ logits_processor=prepared_logits_processor,
+ stopping_criteria=prepared_stopping_criteria,
+ generation_config=generation_config,
+ synced_gpus=synced_gpus,
+ **model_kwargs,
+ )
+
+ elif generation_mode == GenerationMode.GROUP_BEAM_SEARCH:
+ # 11. prepare beam search scorer
+ beam_scorer = BeamSearchScorer(
+ batch_size=batch_size,
+ num_beams=generation_config.num_beams,
+ device=inputs_tensor.device,
+ length_penalty=generation_config.length_penalty,
+ do_early_stopping=generation_config.early_stopping,
+ num_beam_hyps_to_keep=generation_config.num_return_sequences,
+ num_beam_groups=generation_config.num_beam_groups,
+ max_length=generation_config.max_length,
+ )
+ # 12. interleave input_ids with `num_beams` additional sequences per batch
+ input_ids, model_kwargs = self._expand_inputs_for_generation(
+ input_ids=input_ids,
+ expand_size=generation_config.num_beams,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ **model_kwargs,
+ )
+ # 13. run beam search
+ result = self._group_beam_search(
+ input_ids,
+ beam_scorer,
+ logits_processor=prepared_logits_processor,
+ stopping_criteria=prepared_stopping_criteria,
+ generation_config=generation_config,
+ synced_gpus=synced_gpus,
+ **model_kwargs,
+ )
+
+ elif generation_mode == GenerationMode.CONSTRAINED_BEAM_SEARCH:
+ final_constraints = []
+ if generation_config.constraints is not None:
+ final_constraints = generation_config.constraints
+
+ if generation_config.force_words_ids is not None:
+
+ def typeerror():
+ raise ValueError(
+ "`force_words_ids` has to either be a `List[List[List[int]]]` or `List[List[int]]` "
+ f"of positive integers, but is {generation_config.force_words_ids}."
+ )
+
+ if (
+ not isinstance(generation_config.force_words_ids, list)
+ or len(generation_config.force_words_ids) == 0
+ ):
+ typeerror()
+
+ for word_ids in generation_config.force_words_ids:
+ if isinstance(word_ids[0], list):
+ if not isinstance(word_ids, list) or len(word_ids) == 0:
+ typeerror()
+ if any(not isinstance(token_ids, list) for token_ids in word_ids):
+ typeerror()
+ if any(
+ any((not isinstance(token_id, int) or token_id < 0) for token_id in token_ids)
+ for token_ids in word_ids
+ ):
+ typeerror()
+
+ constraint = DisjunctiveConstraint(word_ids)
+ else:
+ if not isinstance(word_ids, list) or len(word_ids) == 0:
+ typeerror()
+ if any((not isinstance(token_id, int) or token_id < 0) for token_id in word_ids):
+ typeerror()
+
+ constraint = PhrasalConstraint(word_ids)
+ final_constraints.append(constraint)
+
+ # 11. prepare beam search scorer
+ constrained_beam_scorer = ConstrainedBeamSearchScorer(
+ constraints=final_constraints,
+ batch_size=batch_size,
+ num_beams=generation_config.num_beams,
+ device=inputs_tensor.device,
+ length_penalty=generation_config.length_penalty,
+ do_early_stopping=generation_config.early_stopping,
+ num_beam_hyps_to_keep=generation_config.num_return_sequences,
+ max_length=generation_config.max_length,
+ )
+ # 12. interleave input_ids with `num_beams` additional sequences per batch
+ input_ids, model_kwargs = self._expand_inputs_for_generation(
+ input_ids=input_ids,
+ expand_size=generation_config.num_beams,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ **model_kwargs,
+ )
+ # 13. run beam search
+ result = self._constrained_beam_search(
+ input_ids,
+ constrained_beam_scorer=constrained_beam_scorer,
+ logits_processor=prepared_logits_processor,
+ stopping_criteria=prepared_stopping_criteria,
+ generation_config=generation_config,
+ synced_gpus=synced_gpus,
+ **model_kwargs,
+ )
+
+ # Convert to legacy cache format if requested
+ if (
+ generation_config.return_legacy_cache is True
+ and not is_torchdynamo_compiling()
+ and hasattr(result, "past_key_values")
+ and getattr(result.past_key_values, "to_legacy_cache") is not None
+ ):
+ result.past_key_values = result.past_key_values.to_legacy_cache()
+ return result
+
+ def _has_unfinished_sequences(
+ self,
+ this_peer_finished: bool,
+ synced_gpus: bool,
+ device: torch.device,
+ cur_len: Optional[int] = None,
+ max_length: Optional[int] = None,
+ ) -> bool:
+ """
+ Returns whether there are still unfinished sequences in the device. The existence of unfinished sequences is
+ fed through `this_peer_finished`. ZeRO stage 3-friendly.
+ """
+ # torch.compile does not support data-dependent control flow. This is a workaround to allow torch.compile,
+ # although we lose the ability to stop when all sequences return an EOS token (and other stopping criteria)
+ # TODO (joao): remove this when torch's support for control flow is not experimental (https://pytorch.org/docs/stable/generated/torch.cond.html)
+ if is_torchdynamo_compiling():
+ return cur_len < max_length
+ else:
+ if synced_gpus:
+ # Under synced_gpus the `forward` call must continue until all gpus complete their sequence.
+ # The following logic allows an early break if all peers finished generating their sequence
+ this_peer_finished_flag = torch.tensor(0.0 if this_peer_finished else 1.0).to(device)
+ # send 0.0 if we finished, 1.0 otherwise
+ dist.all_reduce(this_peer_finished_flag, op=dist.ReduceOp.SUM)
+ # did all peers finish? the reduced sum will be 0.0 then
+ if this_peer_finished_flag.item() == 0.0:
+ return False
+ elif this_peer_finished:
+ return False
+ return True
+
+ def heal_tokens(
+ self, input_ids: torch.LongTensor, tokenizer: Optional["PreTrainedTokenizerBase"] = None
+ ) -> torch.LongTensor:
+ r"""
+ Generates sequences of token ids for models with a language modeling head.
+ Parameters:
+ input_ids (`torch.LongTensor`): The sequence used as a prompt for the generation.
+ tokenizer (`PreTrainedTokenizerBase`, *optional*): The tokenizer used to decode the input ids.
+ Return:
+ `torch.LongTensor` where each sequence has its tail token replaced with its appropriate extension.
+ """
+ if tokenizer is None:
+ raise ValueError(
+ " When generating with token healing, you must pass the model's tokenizer to the `tokenizer` "
+ "argument of `generate`."
+ )
+
+ bos_token_id, pad_token_id = tokenizer.bos_token_id, tokenizer.pad_token_id
+ vocab_trie = ExtensionsTrie(tokenizer.get_vocab())
+ generation_config = GenerationConfig(max_new_tokens=1, pad_token_id=pad_token_id)
+
+ # assumption: leading/trailing whitespace is not meaningful, so the prompts are
+ # stripped before re-tokenizing to desensitize generation to whitespace artefacts
+ prompts = [p.strip() for p in tokenizer.batch_decode(input_ids, skip_special_tokens=True)]
+ input_ids = tokenizer(
+ prompts,
+ return_tensors="pt",
+ padding=True,
+ ).input_ids.to(input_ids.device)
+
+ # replace bos with pad to not condition healing on it
+ input_ids = torch.where(input_ids == bos_token_id, pad_token_id, input_ids)
+
+ """
+ the latter code assumes the input_ids is not empty,
+ input_id has to be checked if contains elements
+ """
+ if input_ids.numel() == 0:
+ return input_ids
+
+ tail_ids = input_ids[:, -1].tolist()
+
+ space_tok = tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids(" "))[0]
+ # tail tokens are used for a prefix search, thus, whitespaces are replaced with
+ # their tokenization (e.g. 'Ġ') to enable search for tokens prefixed with a whitespace
+ tail_toks = (tokenizer.decode(t).replace(" ", space_tok) for t in tail_ids)
+
+ for batch_idx, (tail_id, tail_tok) in enumerate(zip(tail_ids, tail_toks)):
+ batch_ids = input_ids[batch_idx]
+ if torch.all(batch_ids == pad_token_id).item():
+ continue # skip empty sequences (all pad ids)
+
+ # apply bias for alternatives (extensions) to the tail token
+ """
+ seq_bias key has to be tuple with int so have to use
+ tokenizer function to convert str to int
+ """
+ seq_bias = {
+ (tokenizer.convert_tokens_to_ids(alt_tok),): 10.0 for alt_tok in vocab_trie.extensions(prefix=tail_tok)
+ }
+
+ if len(seq_bias) == 1:
+ continue # skip if there are no token alternatives to heal with
+
+ # slightly favor original token to limit aggressive healing e.g. 'http' -> 'https'
+ seq_bias[(tail_id,)] += 1.0
+ generation_config.update(sequence_bias=seq_bias)
+
+ trimmed_ids = batch_ids[:-1]
+
+ """
+ the latter code assumes trimmed_ids is not empty
+ so have to check the its element count
+ """
+ if trimmed_ids.numel() == 0:
+ continue
+
+ # if the prompt is a single (non-pad) token, regenerate from bos
+ if len(batch_ids[batch_ids != pad_token_id]) == 1:
+ trimmed_ids[-1] = bos_token_id
+
+ input_ids[batch_idx] = self.generate(trimmed_ids.unsqueeze(0), generation_config=generation_config)
+
+ return input_ids
+
+ def _dola_decoding(
+ self,
+ input_ids: torch.LongTensor,
+ dola_layers: Union[str, List[int]],
+ logits_processor: LogitsProcessorList,
+ stopping_criteria: StoppingCriteriaList,
+ generation_config: GenerationConfig,
+ synced_gpus: bool,
+ streamer: "BaseStreamer",
+ **model_kwargs,
+ ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
+ r"""
+ Generates sequences of token ids for models with a language modeling head using **dola decoding** and can be
+ used for decoder-only text models.
+ The method is based on the paper "DoLa: Decoding by Contrasting Layers Improves Factuality in Large Language
+ Models" (https://arxiv.org/abs/2309.03883) in ICLR 2024.
+
+ Parameters:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ The sequence used as a prompt for the generation.
+ dola_layers (`Union[str, List[int]]`):
+ The candidate layers used in contrasting layers of DoLa. It can be either 1) 'low' or 'high', which
+ means the lower part or higher part of the model layers, respectively, or 2) a list of layer indices
+ to be used for candidate layers. The 0-th layer is the word embedding layer of the model.
+ logits_processor (`LogitsProcessorList`):
+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ stopping_criteria (`StoppingCriteriaList`, *optional*):
+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
+ used to tell if the generation loop should stop.
+ generation_config ([`~generation.GenerationConfig`]):
+ The generation configuration to be used as parametrization of the decoding method.
+ synced_gpus (`bool`):
+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with
+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
+ streamer (`BaseStreamer`, *optional*):
+ Streamer object that will be used to stream the generated sequences. Generated tokens are passed
+ through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
+ model_kwargs:
+ Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
+ If model is an encoder-decoder model the kwargs should include `encoder_outputs`.
+
+ Return:
+ [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`]
+ or `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
+ [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
+ `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
+ `model.config.is_encoder_decoder=True`.
+ """
+
+ if self.config.is_encoder_decoder:
+ raise ValueError("DoLa decoding is only available for decoder-only models.")
+ # init values
+
+ pad_token_id = generation_config._pad_token_tensor
+ output_attentions = generation_config.output_attentions
+ output_hidden_states = generation_config.output_hidden_states
+ output_scores = generation_config.output_scores
+ output_logits = generation_config.output_logits
+ return_dict_in_generate = generation_config.return_dict_in_generate
+ has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)
+ do_sample = generation_config.do_sample
+
+ # init attention / hidden states / scores tuples
+ scores = () if (return_dict_in_generate and output_scores) else None
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
+
+ # keep track of which sequences are already finished
+ batch_size = input_ids.shape[0]
+ unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
+
+ this_peer_finished = False
+
+ # prepare layers for DoLa decoding
+ final_layer = self.config.get_text_config().num_hidden_layers
+ # if the model has tied word embeddings, we skip the word embeddings (0-th) layer and start from the 2nd layer,
+ # as the early exit from word embeddings will become identity function
+ # if the model is really shallow (<=2 layers), we use the 1st layer if it's not the final layer and the 0-th
+ # layer otherwise. Notice that DoLa does not help shallow models much.
+ if not self.config.tie_word_embeddings:
+ start_layer = 0
+ elif final_layer > 2:
+ start_layer = 2
+ elif final_layer == 2:
+ start_layer = 1
+ else:
+ start_layer = 0
+
+ # For `N`-layer models with `N <= 40` layers, the layers of `range(0, N // 2, 2)` and `range(N // 2, N, 2)`
+ # are used for `'low'` and `'high'` layers, respectively.
+ # For models with `N > 40` layers, the layers of `range(0, 20, 2)` and `range(N - 20, N, 2)` are used for
+ # `'low'` and `'high'` layers, respectively.
+ if isinstance(dola_layers, str) and dola_layers == "low":
+ if start_layer == final_layer // 2:
+ candidate_premature_layers = [start_layer]
+ else:
+ candidate_premature_layers = (
+ list(range(start_layer, final_layer // 2, 2))
+ if final_layer <= 40
+ else list(range(start_layer, 20, 2))
+ )
+ elif isinstance(dola_layers, str) and dola_layers == "high":
+ candidate_premature_layers = (
+ list(range(final_layer // 2, final_layer, 2))
+ if final_layer <= 40
+ else list(range(final_layer - 20, final_layer, 2))
+ )
+ # Set the `dola_layers` to a list of integers for layer indices to contrast manually specified layers.
+ elif isinstance(dola_layers, list):
+ candidate_premature_layers = [i for i in dola_layers if i < final_layer]
+ else:
+ raise ValueError("dola_layers must be either 'low', 'high' or a list of integers.")
+
+ lm_head = self.get_output_embeddings()
+ if lm_head is None:
+ raise ValueError("DoLa is not supported for models that don't have output embeddings.")
+
+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
+ # prepare model inputs
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
+
+ # forward pass to get next token
+ outputs = self(
+ **model_inputs,
+ return_dict=True,
+ output_attentions=output_attentions,
+ output_hidden_states=True,
+ )
+
+ # .float() is needed to retain precision for later logits manipulations
+ final_layer_next_token_logits = outputs.logits[:, -1, :].detach().clone().float()
+ final_logits = outputs.logits[:, -1, :].float()
+ candidate_premature_logits = {}
+ for candidate_premature_layer in candidate_premature_layers:
+ candidate_premature_logits[candidate_premature_layer] = lm_head(
+ outputs.hidden_states[candidate_premature_layer][:, -1, :]
+ ).to(final_logits.device)
+
+ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs,
+ model_kwargs,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ )
+ if synced_gpus and this_peer_finished:
+ continue
+
+ next_token_logits = _dola_select_contrast(
+ candidate_premature_layers, candidate_premature_logits, final_logits
+ )
+ next_token_logits = next_token_logits.to(input_ids.device)
+ # pre-process distribution
+ next_token_scores = logits_processor(input_ids, next_token_logits)
+
+ # Store scores, attentions and hidden_states when required
+ if return_dict_in_generate:
+ if output_scores:
+ scores += (next_token_scores,)
+ if output_logits:
+ raw_logits += (final_layer_next_token_logits,)
+ if output_attentions:
+ decoder_attentions += (
+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
+ )
+ if self.config.is_encoder_decoder:
+ cross_attentions += (outputs.cross_attentions,)
+
+ if output_hidden_states:
+ decoder_hidden_states += (
+ (outputs.decoder_hidden_states,)
+ if self.config.is_encoder_decoder
+ else (outputs.hidden_states,)
+ )
+
+ if do_sample: # sample
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
+ else: # argmax
+ next_tokens = torch.argmax(next_token_scores, dim=-1)
+
+ # finished sentences should have their next token be a padding token
+ if has_eos_stopping_criteria:
+ next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
+
+ # update generated ids, model inputs, and length for next step
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
+ if streamer is not None:
+ streamer.put(next_tokens.cpu())
+
+ # stop when each sentence is finished
+ unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
+ this_peer_finished = unfinished_sequences.max() == 0
+
+ if streamer is not None:
+ streamer.end()
+
+ if return_dict_in_generate:
+ return GenerateDecoderOnlyOutput(
+ sequences=input_ids,
+ scores=scores,
+ logits=raw_logits,
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return input_ids
+
+ @torch.no_grad()
+ def _contrastive_search(
+ self,
+ input_ids: torch.LongTensor,
+ logits_processor: LogitsProcessorList,
+ stopping_criteria: StoppingCriteriaList,
+ generation_config: GenerationConfig,
+ synced_gpus: bool,
+ streamer: Optional["BaseStreamer"],
+ **model_kwargs,
+ ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
+ r"""
+ Generates sequences of token ids for models with a language modeling head using **contrastive search** and can
+ be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
+
+ Parameters:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ The sequence used as a prompt for the generation.
+ logits_processor (`LogitsProcessorList`):
+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ stopping_criteria (`StoppingCriteriaList`):
+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
+ used to tell if the generation loop should stop.
+ generation_config ([`~generation.GenerationConfig`]):
+ The generation configuration to be used as parametrization of the decoding method.
+ synced_gpus (`bool`):
+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with
+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
+ streamer (`BaseStreamer`, *optional*):
+ Streamer object that will be used to stream the generated sequences. Generated tokens are passed
+ through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
+ model_kwargs:
+ Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
+ If model is an encoder-decoder model the kwargs should include `encoder_outputs`.
+
+ Return:
+ [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`]
+ or `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
+ [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
+ `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
+ `model.config.is_encoder_decoder=True`.
+ """
+ # init values
+ has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)
+ top_k = generation_config.top_k
+ penalty_alpha = generation_config.penalty_alpha
+ pad_token_id = generation_config._pad_token_tensor
+ output_attentions = generation_config.output_attentions
+ output_hidden_states = generation_config.output_hidden_states
+ output_scores = generation_config.output_scores
+ output_logits = generation_config.output_logits
+ return_dict_in_generate = generation_config.return_dict_in_generate
+ sequential = generation_config.low_memory
+
+ # init attention / hidden states / scores tuples
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
+ scores = () if (return_dict_in_generate and output_scores) else None
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
+
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
+ if return_dict_in_generate and self.config.is_encoder_decoder:
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
+ encoder_hidden_states = (
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
+ )
+
+ # keep track of which sequences are already finished
+ batch_size = input_ids.shape[0]
+ unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
+
+ # Create cosine_matrix_mask based on the attention_mask
+ cosine_matrix_mask = torch.ones_like(input_ids, dtype=torch.long)
+ if self.config.is_encoder_decoder:
+ if "decoder_attention_mask" in model_kwargs and model_kwargs["decoder_attention_mask"] is not None:
+ cosine_matrix_mask = model_kwargs["decoder_attention_mask"]
+ else:
+ cosine_matrix_mask = model_kwargs["attention_mask"]
+ cosine_matrix_mask = cosine_matrix_mask.repeat_interleave(top_k, dim=0)
+
+ this_peer_finished = False
+
+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
+ # if the first step in the loop, encode all the prefix and obtain: (1) past_key_values;
+ # (2) last_hidden_states; (3) logit_for_next_step; (4) update model kwargs for the next step
+ if model_kwargs.get("past_key_values") is None or (
+ isinstance(model_kwargs["past_key_values"], (Cache, EncoderDecoderCache))
+ and model_kwargs["past_key_values"].get_seq_length() == 0
+ ):
+ # prepare inputs
+ model_kwargs["use_cache"] = True
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
+
+ # encode the given prefix and prepare model inputs; encoder-decoder model process the prefix and save
+ # the `encoder_outputs`
+ outputs = self(
+ **model_inputs, return_dict=True, output_hidden_states=True, output_attentions=output_attentions
+ )
+
+ # last decoder hidden states will be used to compute the degeneration penalty (cosine similarity with
+ # previous tokens)
+ if self.config.is_encoder_decoder:
+ last_hidden_states = outputs.decoder_hidden_states[-1]
+ else:
+ last_hidden_states = outputs.hidden_states[-1]
+
+ # next logit for contrastive search to select top-k candidate tokens
+ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for this first iteration
+ # (the clone itself is always small)
+ # .float() is needed to retain precision for later logits manipulations
+ logit_for_next_step = outputs.logits[:, -1, :].clone().float()
+ logit_for_next_step = logit_for_next_step.to(input_ids.device)
+
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs,
+ model_kwargs,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ )
+
+ if not sequential:
+ # Expands model inputs top_k times, for batched forward passes (akin to beam search).
+ # input_ids is required for expanding visual inputs in qwen2vl
+ _, model_kwargs = self._expand_inputs_for_generation(
+ input_ids=input_ids,
+ expand_size=top_k,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ **model_kwargs,
+ )
+
+ past_key_values = model_kwargs.get("past_key_values")
+ if past_key_values is None:
+ raise ValueError(
+ f"{self.__class__.__name__} does not support caching and therefore **can't** be used "
+ "for contrastive search."
+ )
+ elif (
+ not isinstance(past_key_values[0], (tuple, torch.Tensor))
+ or past_key_values[0][0].shape[0] != batch_size
+ ):
+ raise ValueError(
+ f"{self.__class__.__name__} does not have a standard cache format and therefore **can't** be "
+ "used for contrastive search without further modifications."
+ )
+
+ # contrastive_search main logic start:
+ # contrastive search decoding consists of two steps: (1) candidate tokens recall; (2) candidate re-rank by
+ # degeneration penalty
+ processed_logit_for_next_step = logits_processor(input_ids, logit_for_next_step)
+ next_probs = nn.functional.softmax(processed_logit_for_next_step, dim=-1)
+
+ top_k_probs, top_k_ids = torch.topk(next_probs, dim=-1, k=top_k)
+
+ # Store scores, attentions and hidden_states when required
+ if return_dict_in_generate:
+ if output_logits:
+ raw_logits += (logit_for_next_step,)
+ if output_scores:
+ scores += (processed_logit_for_next_step,)
+ if output_attentions:
+ decoder_attentions += (
+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
+ )
+ if self.config.is_encoder_decoder:
+ cross_attentions += (outputs.cross_attentions,)
+
+ if output_hidden_states:
+ decoder_hidden_states += (
+ (outputs.decoder_hidden_states,)
+ if self.config.is_encoder_decoder
+ else (outputs.hidden_states,)
+ )
+
+ # This is needed to properly delete outputs.logits which may be very large for this first iteration
+ # Otherwise a reference to outputs.logits is kept all along until after the next call to self.forward()
+ del outputs
+
+ if not sequential:
+ # Replicates the new past_key_values to match the `top_k` candidates
+ past = model_kwargs["past_key_values"]
+ # If it is a static cache, modify it in-place layer after layer to save memory
+ if isinstance(past, DynamicCache) or (
+ isinstance(past, EncoderDecoderCache) and isinstance(past.self_attention_cache, DynamicCache)
+ ):
+ past.batch_repeat_interleave(top_k)
+ else:
+ new_key_values = []
+ for layer in past:
+ items = []
+ # item is either the key or the value matrix
+ for item in layer:
+ items.append(item.repeat_interleave(top_k, dim=0))
+ new_key_values.append(tuple(items))
+
+ past = tuple(new_key_values)
+
+ model_kwargs["past_key_values"] = past
+
+ if sequential:
+ all_outputs = []
+ for i in range(top_k):
+ # compute the candidate tokens by the language model and collect their hidden_states
+ next_model_inputs = self.prepare_inputs_for_generation(top_k_ids[:, i].view(-1, 1), **model_kwargs)
+
+ outputs = self(
+ **next_model_inputs,
+ return_dict=True,
+ output_hidden_states=True,
+ output_attentions=output_attentions,
+ )
+ if isinstance(outputs["past_key_values"], DynamicCache) or (
+ isinstance(outputs["past_key_values"], EncoderDecoderCache)
+ and isinstance(outputs["past_key_values"].self_attention_cache, DynamicCache)
+ ):
+ # Remove past K-V from output since we don't need to stack later
+ outputs["past_key_values"] = None
+ # Remove last token from past K-V since we don't want to append it at this point
+ model_kwargs["past_key_values"].crop(-1)
+
+ all_outputs.append(outputs)
+ outputs = stack_model_outputs(all_outputs, self.config.get_text_config())
+
+ else:
+ # compute the candidate tokens by the language model and collect their hidden_states
+ # assembles top_k_ids into batch of size k
+ next_model_inputs = self.prepare_inputs_for_generation(top_k_ids.view(-1, 1), **model_kwargs)
+
+ outputs = self(
+ **next_model_inputs,
+ return_dict=True,
+ output_hidden_states=True,
+ output_attentions=output_attentions,
+ )
+
+ # This is essential to avoid having a last reference to the big past K-V and double the necessary memory
+ # in the next loop
+ del next_model_inputs
+
+ # name is different for encoder-decoder and decoder-only models
+ if self.config.is_encoder_decoder:
+ next_hidden = outputs.decoder_hidden_states[-1]
+ full_hidden_states = outputs.decoder_hidden_states
+ else:
+ next_hidden = outputs.hidden_states[-1]
+ full_hidden_states = outputs.hidden_states
+
+ # .float() is needed to retain precision for later logits manipulations
+ logits = outputs.logits[:, -1, :].float()
+ context_hidden = last_hidden_states.repeat_interleave(top_k, dim=0)
+
+ # compute the degeneration penalty and re-rank the candidates based on the degeneration penalty and the
+ # model confidence. Keeping `selected_idx` on CPU enables multi-device contrastive search and doesn't
+ # introduce (noticeable) slowdowns on single-device runs.
+ selected_idx = _ranking_fast(
+ context_hidden, next_hidden, top_k_probs, cosine_matrix_mask, penalty_alpha, top_k
+ )
+ cosine_matrix_mask = torch.cat(
+ [cosine_matrix_mask, cosine_matrix_mask.new_ones((cosine_matrix_mask.shape[0], 1))], dim=-1
+ )
+ selected_idx = selected_idx.to("cpu")
+
+ # This will be used instead of the previous inneficient torch.stack(torch.split())
+ augmented_idx = torch.tensor([x + i * top_k for i, x in enumerate(selected_idx)])
+
+ # prepare for the next step: (1) next token_id; (2) past_key_values; (3) last_hidden_states for computing
+ # the degeneration penalty; (4) logits for selecting next top-k candidates; (5) selected tokens scores
+ # (model confidence minus degeneration penalty); (6) decoder hidden_states
+ next_tokens = top_k_ids[range(len(top_k_ids)), selected_idx]
+ next_hidden = torch.stack(torch.split(next_hidden.squeeze(dim=1), top_k))
+ next_hidden = next_hidden[range(batch_size), selected_idx, :]
+ last_hidden_states = torch.cat([last_hidden_states, next_hidden.unsqueeze(1)], dim=1)
+
+ next_decoder_hidden_states = ()
+ for layer in full_hidden_states:
+ layer = torch.stack(torch.split(layer, top_k))[range(batch_size), selected_idx, :]
+ next_decoder_hidden_states += (layer,)
+
+ # generate past_key_values cache of only the selected token
+ if sequential:
+ next_model_input = self.prepare_inputs_for_generation(
+ top_k_ids[:, selected_idx].view(-1, 1), **model_kwargs
+ )
+
+ selected_outputs = self(
+ **next_model_input,
+ return_dict=True,
+ output_hidden_states=False,
+ output_attentions=False,
+ )
+ next_past_key_values = selected_outputs["past_key_values"]
+
+ else:
+ next_past_key_values = None
+ for possible_cache_name in ALL_CACHE_NAMES:
+ next_past_key_values = next_past_key_values or getattr(outputs, possible_cache_name, None)
+ # Do it in-place layer per layer to save memory
+ if isinstance(next_past_key_values, DynamicCache) or (
+ isinstance(next_past_key_values, EncoderDecoderCache)
+ and isinstance(next_past_key_values.self_attention_cache, DynamicCache)
+ ):
+ next_past_key_values.batch_select_indices(augmented_idx)
+ else:
+ new_key_values = []
+ for layer in next_past_key_values:
+ items = []
+ # item is either the key or the value matrix
+ for item in layer:
+ items.append(item[augmented_idx, ...])
+ new_key_values.append(tuple(items))
+
+ next_past_key_values = tuple(new_key_values)
+
+ logit_for_next_step = torch.stack(torch.split(logits, top_k))[range(batch_size), selected_idx, :]
+ logit_for_next_step = logit_for_next_step.to(input_ids.device)
+
+ # Rebuilds the relevant parts of the model output for the selected token, for use in the next iteration
+ if self.config.is_encoder_decoder:
+ next_step_cross_attentions = ()
+ next_step_decoder_attentions = ()
+ if output_attentions:
+ for layer in outputs.cross_attentions:
+ layer = torch.stack(torch.split(layer, top_k, dim=0))[range(batch_size), selected_idx, ...]
+ next_step_cross_attentions += (layer,)
+ for layer in outputs.decoder_attentions:
+ layer = torch.stack(torch.split(layer, top_k, dim=0))[range(batch_size), selected_idx, ...]
+ next_step_decoder_attentions += (layer,)
+ outputs = Seq2SeqLMOutput(
+ past_key_values=next_past_key_values,
+ decoder_hidden_states=next_decoder_hidden_states,
+ decoder_attentions=next_step_decoder_attentions or None,
+ cross_attentions=next_step_cross_attentions or None,
+ )
+ else:
+ next_step_attentions = ()
+ if output_attentions:
+ for layer in outputs.attentions:
+ layer = torch.stack(torch.split(layer, top_k, dim=0))[range(batch_size), selected_idx, ...]
+ next_step_attentions += (layer,)
+ outputs = CausalLMOutputWithPast(
+ past_key_values=next_past_key_values,
+ hidden_states=next_decoder_hidden_states,
+ attentions=next_step_attentions or None,
+ )
+ # contrastive_search main logic end
+
+ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs,
+ model_kwargs,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ )
+ if synced_gpus and this_peer_finished:
+ continue
+
+ # finished sentences should have their next token be a padding token
+ if has_eos_stopping_criteria:
+ next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
+
+ # update generated ids, model inputs, and length for next step
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
+ if streamer is not None:
+ streamer.put(next_tokens.cpu())
+
+ # stop when each sentence is finished
+ unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
+ this_peer_finished = unfinished_sequences.max() == 0
+
+ if streamer is not None:
+ streamer.end()
+
+ if return_dict_in_generate:
+ # Contrastive search works by forward looking at the next token, so we need to exclude it from
+ # `past_key_values` to be consistent with the other decoding methods
+ if model_kwargs.get("past_key_values") is not None:
+ if isinstance(model_kwargs["past_key_values"], DynamicCache) or (
+ isinstance(model_kwargs["past_key_values"], EncoderDecoderCache)
+ and isinstance(model_kwargs["past_key_values"].self_attention_cache, DynamicCache)
+ ):
+ model_kwargs["past_key_values"].crop(-1)
+ else:
+ past_key_values = []
+ for layer in model_kwargs["past_key_values"]:
+ layer_past_key_values = []
+ for item in layer:
+ layer_past_key_values.append(item[..., :-1, :])
+ past_key_values.append(tuple(layer_past_key_values))
+ model_kwargs["past_key_values"] = tuple(past_key_values)
+
+ if self.config.is_encoder_decoder:
+ return GenerateEncoderDecoderOutput(
+ sequences=input_ids,
+ scores=scores,
+ logits=raw_logits,
+ encoder_attentions=encoder_attentions,
+ encoder_hidden_states=encoder_hidden_states,
+ decoder_attentions=decoder_attentions,
+ cross_attentions=cross_attentions,
+ decoder_hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return GenerateDecoderOnlyOutput(
+ sequences=input_ids,
+ scores=scores,
+ logits=raw_logits,
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return input_ids
+
+ def _sample(
+ self,
+ input_ids: torch.LongTensor,
+ logits_processor: LogitsProcessorList,
+ stopping_criteria: StoppingCriteriaList,
+ generation_config: GenerationConfig,
+ synced_gpus: bool,
+ streamer: Optional["BaseStreamer"],
+ **model_kwargs,
+ ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
+ r"""
+ Generates sequences of token ids for models with a language modeling head using **multinomial sampling** and
+ can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
+
+ Parameters:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ The sequence used as a prompt for the generation.
+ logits_processor (`LogitsProcessorList`):
+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ stopping_criteria (`StoppingCriteriaList`):
+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
+ used to tell if the generation loop should stop.
+ generation_config ([`~generation.GenerationConfig`]):
+ The generation configuration to be used as parametrization of the decoding method.
+ synced_gpus (`bool`):
+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with
+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
+ streamer (`BaseStreamer`, *optional*):
+ Streamer object that will be used to stream the generated sequences. Generated tokens are passed
+ through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
+ model_kwargs:
+ Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
+ an encoder-decoder model the kwargs should include `encoder_outputs`.
+
+ Return:
+ [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`] or `torch.LongTensor`:
+ A `torch.LongTensor` containing the generated tokens (default behaviour) or a
+ [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
+ `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
+ `model.config.is_encoder_decoder=True`.
+ """
+ # init values
+ pad_token_id = generation_config._pad_token_tensor
+ output_attentions = generation_config.output_attentions
+ output_hidden_states = generation_config.output_hidden_states
+ output_scores = generation_config.output_scores
+ output_logits = generation_config.output_logits
+ return_dict_in_generate = generation_config.return_dict_in_generate
+ max_length = generation_config.max_length
+ has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)
+ do_sample = generation_config.do_sample
+
+ # init attention / hidden states / scores tuples
+ scores = () if (return_dict_in_generate and output_scores) else None
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
+
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
+ if return_dict_in_generate and self.config.is_encoder_decoder:
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
+ encoder_hidden_states = (
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
+ )
+
+ # keep track of which sequences are already finished
+ batch_size, cur_len = input_ids.shape
+ this_peer_finished = False
+ unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
+
+ model_forward = self.__call__
+ if isinstance(model_kwargs.get("past_key_values"), Cache):
+ is_compileable = model_kwargs["past_key_values"].is_compileable and self._supports_static_cache
+ is_compileable = is_compileable and not self.generation_config.disable_compile
+ if is_compileable and (
+ self.device.type == "cuda" or generation_config.compile_config._compile_all_devices
+ ):
+ os.environ["TOKENIZERS_PARALLELISM"] = "0"
+ model_forward = self.get_compiled_call(generation_config.compile_config)
+
+ is_prefill = True
+ while self._has_unfinished_sequences(
+ this_peer_finished, synced_gpus, device=input_ids.device, cur_len=cur_len, max_length=max_length
+ ):
+ # prepare model inputs
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
+
+ # prepare variable output controls (note: some models won't accept all output controls)
+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
+ model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
+
+ if is_prefill:
+ outputs = self(**model_inputs, return_dict=True)
+ is_prefill = False
+ else:
+ outputs = model_forward(**model_inputs, return_dict=True)
+
+ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs,
+ model_kwargs,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ )
+ if synced_gpus and this_peer_finished:
+ continue
+
+ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
+ # (the clone itself is always small)
+ next_token_logits = outputs.logits[:, -1, :].clone().float()
+ next_token_logits = next_token_logits.to(input_ids.device)
+
+ # pre-process distribution
+ next_token_scores = logits_processor(input_ids, next_token_logits)
+
+ # Store scores, attentions and hidden_states when required
+ if return_dict_in_generate:
+ if output_scores:
+ scores += (next_token_scores,)
+ if output_logits:
+ raw_logits += (next_token_logits,)
+ if output_attentions:
+ decoder_attentions += (
+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
+ )
+ if self.config.is_encoder_decoder:
+ cross_attentions += (outputs.cross_attentions,)
+
+ if output_hidden_states:
+ decoder_hidden_states += (
+ (outputs.decoder_hidden_states,)
+ if self.config.is_encoder_decoder
+ else (outputs.hidden_states,)
+ )
+
+ # token selection
+ if do_sample:
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
+ # TODO (joao): this OP throws "skipping cudagraphs due to ['incompatible ops']", find solution
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
+ else:
+ next_tokens = torch.argmax(next_token_scores, dim=-1)
+
+ # finished sentences should have their next token be a padding token
+ if has_eos_stopping_criteria:
+ next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
+
+ # update generated ids, model inputs, and length for next step
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
+ if streamer is not None:
+ streamer.put(next_tokens.cpu())
+
+ unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
+ this_peer_finished = unfinished_sequences.max() == 0
+ cur_len += 1
+
+ # This is needed to properly delete outputs.logits which may be very large for first iteration
+ # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
+ del outputs
+
+ if streamer is not None:
+ streamer.end()
+
+ if return_dict_in_generate:
+ if self.config.is_encoder_decoder:
+ return GenerateEncoderDecoderOutput(
+ sequences=input_ids,
+ scores=scores,
+ logits=raw_logits,
+ encoder_attentions=encoder_attentions,
+ encoder_hidden_states=encoder_hidden_states,
+ decoder_attentions=decoder_attentions,
+ cross_attentions=cross_attentions,
+ decoder_hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return GenerateDecoderOnlyOutput(
+ sequences=input_ids,
+ scores=scores,
+ logits=raw_logits,
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return input_ids
+
+ def _temporary_reorder_cache(self, past_key_values, beam_idx):
+ """
+ Temporary function to handle the different types of cache reordering processes while we roll out `Cache`.
+
+ TODO: standardize cache formats and make all models compatible with `Cache`. It would remove the need
+ for this function, with `Cache.reorder_cache` being the sole remaining code path
+ """
+ model_class = self.__class__.__name__.lower()
+ # Exception 1: code path for models using the legacy cache format
+ if isinstance(past_key_values, (tuple, list)):
+ past_key_values = self._reorder_cache(past_key_values, beam_idx)
+ # Exception 2: models with different cache formats. These are limited to `DynamicCache` until their
+ # cache format is standardized, to avoid adding complexity to the codebase.
+ elif "gptbigcode" in model_class:
+ if not isinstance(past_key_values, (DynamicCache, EncoderDecoderCache)):
+ raise ValueError(
+ f"Using an unsupported cache format with {model_class}. Currently, it only supports the "
+ "legacy tuple format or `DynamicCache`"
+ )
+ past_key_values = self._reorder_cache(past_key_values, beam_idx)
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
+ # Standard code path: use the `Cache.reorder_cache`
+ else:
+ past_key_values.reorder_cache(beam_idx)
+ return past_key_values
+
+ def _beam_search(
+ self,
+ input_ids: torch.LongTensor,
+ beam_scorer: BeamScorer,
+ logits_processor: LogitsProcessorList,
+ stopping_criteria: StoppingCriteriaList,
+ generation_config: GenerationConfig,
+ synced_gpus: bool,
+ **model_kwargs,
+ ) -> Union[GenerateBeamOutput, torch.LongTensor]:
+ r"""
+ Generates sequences of token ids for models with a language modeling head using **beam search decoding** and
+ can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
+
+ Parameters:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ The sequence used as a prompt for the generation.
+ beam_scorer (`BeamScorer`):
+ An derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and
+ sorted during generation. For more information, the documentation of [`BeamScorer`] should be read.
+ logits_processor (`LogitsProcessorList`):
+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ stopping_criteria (`StoppingCriteriaList`:
+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
+ used to tell if the generation loop should stop.
+ generation_config ([`~generation.GenerationConfig`]):
+ The generation configuration to be used as parametrization of the decoding method.
+ synced_gpus (`bool`):
+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with
+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
+ model_kwargs:
+ Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
+ an encoder-decoder model the kwargs should include `encoder_outputs`.
+
+ Return:
+ [`generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
+ `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
+ [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
+ `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
+ `model.config.is_encoder_decoder=True`.
+ """
+ # init values
+ pad_token_id = generation_config._pad_token_tensor
+ eos_token_id = generation_config._eos_token_tensor
+ output_attentions = generation_config.output_attentions
+ output_hidden_states = generation_config.output_hidden_states
+ output_scores = generation_config.output_scores
+ output_logits = generation_config.output_logits
+ return_dict_in_generate = generation_config.return_dict_in_generate
+ sequential = generation_config.low_memory
+ do_sample = generation_config.do_sample
+
+ batch_size = len(beam_scorer._beam_hyps)
+ num_beams = beam_scorer.num_beams
+
+ batch_beam_size, cur_len = input_ids.shape
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
+
+ if num_beams * batch_size != batch_beam_size:
+ raise ValueError(
+ f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."
+ )
+
+ # init attention / hidden states / scores tuples
+ scores = () if (return_dict_in_generate and output_scores) else None
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
+ beam_indices = (
+ tuple(() for _ in range(batch_beam_size)) if (return_dict_in_generate and output_scores) else None
+ )
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
+
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
+ if return_dict_in_generate and self.config.is_encoder_decoder:
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
+ encoder_hidden_states = (
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
+ )
+
+ # initialise score of first beam with 0 and the rest with -1e9. This makes sure that only tokens
+ # of the first beam are considered to avoid sampling the exact same tokens across all beams.
+ beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device)
+ beam_scores[:, 1:] = -1e9
+ beam_scores = beam_scores.view((batch_size * num_beams,))
+
+ this_peer_finished = False
+
+ decoder_prompt_len = input_ids.shape[-1] # record the prompt length of decoder
+
+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
+
+ # prepare variable output controls (note: some models won't accept all output controls)
+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
+ model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
+
+ # if sequential is True, split the input to batches of batch_size and run sequentially
+ if sequential:
+ if any(
+ model_name in self.__class__.__name__.lower()
+ for model_name in [
+ "fsmt",
+ "reformer",
+ "ctrl",
+ "gpt_bigcode",
+ "transo_xl",
+ "xlnet",
+ "cpm",
+ "jamba",
+ ]
+ ):
+ raise RuntimeError(
+ f"Currently generation for {self.__class__.__name__} is not supported "
+ f"for `low_memory beam_search`. Please open an issue on GitHub if you need this feature."
+ )
+
+ inputs_per_sub_batches = _split_model_inputs(
+ model_inputs,
+ split_size=batch_size,
+ full_batch_size=batch_beam_size,
+ config=self.config.get_text_config(),
+ )
+ outputs_per_sub_batch = [
+ self(**inputs_per_sub_batch, return_dict=True) for inputs_per_sub_batch in inputs_per_sub_batches
+ ]
+
+ outputs = stack_model_outputs(outputs_per_sub_batch, self.config.get_text_config())
+
+ else: # Unchanged original behavior
+ outputs = self(**model_inputs, return_dict=True)
+
+ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs,
+ model_kwargs,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ )
+ if synced_gpus and this_peer_finished:
+ cur_len = cur_len + 1
+ continue
+
+ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
+ # (the clone itself is always small)
+ # .float() is needed to retain precision for later logits manipulations
+ next_token_logits = outputs.logits[:, -1, :].clone().float()
+ next_token_logits = next_token_logits.to(input_ids.device)
+ next_token_scores = nn.functional.log_softmax(
+ next_token_logits, dim=-1
+ ) # (batch_size * num_beams, vocab_size)
+
+ next_token_scores_processed = logits_processor(input_ids, next_token_scores)
+ next_token_scores = next_token_scores_processed + beam_scores[:, None].expand_as(
+ next_token_scores_processed
+ )
+
+ # Store scores, attentions and hidden_states when required
+ if return_dict_in_generate:
+ if output_scores:
+ scores += (next_token_scores_processed,)
+ if output_logits:
+ raw_logits += (next_token_logits,)
+ if output_attentions:
+ decoder_attentions += (
+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
+ )
+ if self.config.is_encoder_decoder:
+ cross_attentions += (outputs.cross_attentions,)
+ if output_hidden_states:
+ decoder_hidden_states += (
+ (outputs.decoder_hidden_states,)
+ if self.config.is_encoder_decoder
+ else (outputs.hidden_states,)
+ )
+
+ # reshape for beam search
+ vocab_size = next_token_scores.shape[-1]
+ next_token_scores = next_token_scores.view(batch_size, num_beams * vocab_size)
+
+ # Beam token selection: pick 1 + eos_token_id.shape[0] next tokens for each beam so we have at least 1
+ # non eos token per beam.
+ n_eos_tokens = eos_token_id.shape[0] if eos_token_id is not None else 0
+ n_tokens_to_keep = max(2, 1 + n_eos_tokens) * num_beams
+ if do_sample:
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
+ next_tokens = torch.multinomial(probs, num_samples=n_tokens_to_keep)
+ next_token_scores = torch.gather(next_token_scores, -1, next_tokens)
+ next_token_scores, _indices = torch.sort(next_token_scores, descending=True, dim=1)
+ next_tokens = torch.gather(next_tokens, -1, _indices)
+ else:
+ next_token_scores, next_tokens = torch.topk(
+ next_token_scores, n_tokens_to_keep, dim=1, largest=True, sorted=True
+ )
+
+ next_indices = torch.div(next_tokens, vocab_size, rounding_mode="floor")
+ next_tokens = next_tokens % vocab_size
+
+ # stateless
+ beam_outputs = beam_scorer.process(
+ input_ids,
+ next_token_scores,
+ next_tokens,
+ next_indices,
+ pad_token_id=pad_token_id,
+ eos_token_id=eos_token_id,
+ beam_indices=beam_indices,
+ decoder_prompt_len=decoder_prompt_len,
+ )
+
+ beam_scores = beam_outputs["next_beam_scores"]
+ beam_next_tokens = beam_outputs["next_beam_tokens"]
+ beam_idx = beam_outputs["next_beam_indices"]
+
+ input_ids = torch.cat([input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)
+
+ # This is needed to properly delete outputs.logits which may be very large for first iteration
+ # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
+ # IMPORTANT: Note that this should appear BEFORE the call to _reorder_cache() to save the maximum memory
+ # (that way the memory peak does not include outputs.logits)
+ del outputs
+
+ if model_kwargs.get("past_key_values", None) is not None:
+ model_kwargs["past_key_values"] = self._temporary_reorder_cache(
+ model_kwargs["past_key_values"], beam_idx
+ )
+
+ if return_dict_in_generate and output_scores:
+ beam_indices = tuple((beam_indices[beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices))))
+
+ # increase cur_len
+ cur_len = cur_len + 1
+
+ if beam_scorer.is_done or all(stopping_criteria(input_ids, scores)):
+ this_peer_finished = True
+
+ sequence_outputs = beam_scorer.finalize(
+ input_ids,
+ beam_scores,
+ next_tokens,
+ next_indices,
+ pad_token_id=pad_token_id,
+ eos_token_id=eos_token_id,
+ max_length=stopping_criteria.max_length,
+ beam_indices=beam_indices,
+ decoder_prompt_len=decoder_prompt_len,
+ )
+
+ if return_dict_in_generate:
+ if not output_scores:
+ sequence_outputs["sequence_scores"] = None
+
+ if self.config.is_encoder_decoder:
+ return GenerateBeamEncoderDecoderOutput(
+ sequences=sequence_outputs["sequences"],
+ sequences_scores=sequence_outputs["sequence_scores"],
+ scores=scores,
+ logits=raw_logits,
+ beam_indices=sequence_outputs["beam_indices"],
+ encoder_attentions=encoder_attentions,
+ encoder_hidden_states=encoder_hidden_states,
+ decoder_attentions=decoder_attentions,
+ cross_attentions=cross_attentions,
+ decoder_hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return GenerateBeamDecoderOnlyOutput(
+ sequences=sequence_outputs["sequences"],
+ sequences_scores=sequence_outputs["sequence_scores"],
+ scores=scores,
+ logits=raw_logits,
+ beam_indices=sequence_outputs["beam_indices"],
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return sequence_outputs["sequences"]
+
+ def _group_beam_search(
+ self,
+ input_ids: torch.LongTensor,
+ beam_scorer: BeamScorer,
+ logits_processor: LogitsProcessorList,
+ stopping_criteria: StoppingCriteriaList,
+ generation_config: GenerationConfig,
+ synced_gpus: bool,
+ **model_kwargs,
+ ):
+ r"""
+ Generates sequences of token ids for models with a language modeling head using **diverse beam search
+ decoding** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
+
+ Parameters:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ The sequence used as a prompt for the generation.
+ beam_scorer (`BeamScorer`):
+ An derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and
+ sorted during generation. For more information, the documentation of [`BeamScorer`] should be read.
+ logits_processor (`LogitsProcessorList`):
+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ stopping_criteria (`StoppingCriteriaList`):
+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
+ used to tell if the generation loop should stop.
+ generation_config ([`~generation.GenerationConfig`]):
+ The generation configuration to be used as parametrization of the decoding method.
+ synced_gpus (`bool`):
+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with
+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
+ model_kwargs:
+ Additional model specific kwargs that will be forwarded to the `forward` function of the model. If
+ model is an encoder-decoder model the kwargs should include `encoder_outputs`.
+
+ Return:
+ [`~generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
+ `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
+ [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
+ `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
+ `model.config.is_encoder_decoder=True`.
+ """
+ # init values
+ pad_token_id = generation_config._pad_token_tensor
+ eos_token_id = generation_config._eos_token_tensor
+ output_attentions = generation_config.output_attentions
+ output_hidden_states = generation_config.output_hidden_states
+ output_scores = generation_config.output_scores
+ output_logits = generation_config.output_logits
+ return_dict_in_generate = generation_config.return_dict_in_generate
+
+ num_beams = beam_scorer.num_beams
+ num_beam_groups = beam_scorer.num_beam_groups
+ num_sub_beams = num_beams // num_beam_groups
+ batch_size = len(beam_scorer._beam_hyps) // num_beam_groups
+ device = input_ids.device
+
+ batch_beam_size, cur_len = input_ids.shape
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
+
+ if return_dict_in_generate and output_scores:
+ beam_indices = [tuple(() for _ in range(num_sub_beams * batch_size)) for _ in range(num_beam_groups)]
+ else:
+ beam_indices = None
+
+ if num_beams * batch_size != batch_beam_size:
+ raise ValueError(
+ f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."
+ )
+
+ # init attention / hidden states / scores tuples
+ scores = () if (return_dict_in_generate and output_scores) else None
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
+
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
+ if return_dict_in_generate and self.config.is_encoder_decoder:
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
+ encoder_hidden_states = (
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
+ )
+
+ # initialise score of first beam of each group with 0 and the rest with -1e9. This ensures that the beams in
+ # the same group don't produce same tokens every time.
+ beam_scores = torch.full((batch_size, num_beams), -1e9, dtype=torch.float, device=device)
+ beam_scores[:, ::num_sub_beams] = 0
+ beam_scores = beam_scores.view((batch_size * num_beams,))
+
+ this_peer_finished = False
+
+ decoder_prompt_len = input_ids.shape[-1] # record the prompt length of decoder
+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
+ # predicted tokens in cur_len step
+ current_tokens = torch.zeros(batch_size * num_beams, dtype=input_ids.dtype, device=device)
+
+ # indices which will form the beams in the next time step
+ reordering_indices = torch.zeros(batch_size * num_beams, dtype=torch.long, device=device)
+
+ # do one decoder step on all beams of all sentences in batch
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
+
+ # prepare variable output controls (note: some models won't accept all output controls)
+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
+ model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
+
+ outputs = self(**model_inputs, return_dict=True)
+
+ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs,
+ model_kwargs,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ )
+ if synced_gpus and this_peer_finished:
+ cur_len = cur_len + 1
+ continue
+
+ if output_scores:
+ processed_score = torch.zeros_like(outputs.logits[:, -1, :])
+ if output_logits:
+ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
+ # (the clone itself is always small)
+ raw_logit_score = outputs.logits[:, -1, :].clone()
+ raw_logit_score = raw_logit_score.to(input_ids.device)
+
+ for beam_group_idx in range(num_beam_groups):
+ group_start_idx = beam_group_idx * num_sub_beams
+ group_end_idx = min(group_start_idx + num_sub_beams, num_beams)
+ group_size = group_end_idx - group_start_idx
+
+ # indices of beams of current group among all sentences in batch
+ batch_group_indices = []
+
+ for batch_idx in range(batch_size):
+ batch_group_indices.extend(
+ [batch_idx * num_beams + idx for idx in range(group_start_idx, group_end_idx)]
+ )
+ group_input_ids = input_ids[batch_group_indices]
+
+ # select outputs of beams of current group only
+ # No need to clone() the logits here as they will not retain outputs.logits at the end of the loop
+ # .float() is needed to retain precision for later logits manipulations
+ next_token_logits = outputs.logits[batch_group_indices, -1, :].float()
+ next_token_logits = next_token_logits.to(input_ids.device)
+
+ next_token_scores = nn.functional.log_softmax(
+ next_token_logits, dim=-1
+ ) # (batch_size * group_size, vocab_size)
+ vocab_size = next_token_scores.shape[-1]
+
+ next_token_scores_processed = logits_processor(
+ group_input_ids, next_token_scores, current_tokens=current_tokens, beam_group_idx=beam_group_idx
+ )
+ next_token_scores = next_token_scores_processed + beam_scores[batch_group_indices].unsqueeze(-1)
+ next_token_scores = next_token_scores.expand_as(next_token_scores_processed)
+
+ if output_scores:
+ processed_score[batch_group_indices] = next_token_scores_processed
+
+ # reshape for beam search
+ next_token_scores = next_token_scores.view(batch_size, group_size * vocab_size)
+
+ # Sample 1 + len(eos_token_id) next tokens for each beam so we have at least 1 non eos token per beam.
+ n_eos_tokens = eos_token_id.shape[0] if eos_token_id is not None else 0
+ next_token_scores, next_tokens = torch.topk(
+ next_token_scores, max(2, 1 + n_eos_tokens) * group_size, dim=1, largest=True, sorted=True
+ )
+
+ next_indices = torch.div(next_tokens, vocab_size, rounding_mode="floor")
+ next_tokens = next_tokens % vocab_size
+
+ # stateless
+ process_beam_indices = sum(beam_indices, ()) if beam_indices is not None else None
+ beam_outputs = beam_scorer.process(
+ group_input_ids,
+ next_token_scores,
+ next_tokens,
+ next_indices,
+ pad_token_id=pad_token_id,
+ eos_token_id=eos_token_id,
+ beam_indices=process_beam_indices,
+ group_index=beam_group_idx,
+ decoder_prompt_len=decoder_prompt_len,
+ )
+ beam_scores[batch_group_indices] = beam_outputs["next_beam_scores"]
+ beam_next_tokens = beam_outputs["next_beam_tokens"]
+ beam_idx = beam_outputs["next_beam_indices"]
+
+ if return_dict_in_generate and output_scores:
+ beam_indices[beam_group_idx] = tuple(
+ beam_indices[beam_group_idx][beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices[0]))
+ )
+
+ input_ids[batch_group_indices] = group_input_ids[beam_idx]
+ group_input_ids = torch.cat([group_input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)
+ current_tokens[batch_group_indices] = group_input_ids[:, -1]
+
+ # (beam_idx // group_size) -> batch_idx
+ # (beam_idx % group_size) -> offset of idx inside the group
+ reordering_indices[batch_group_indices] = (
+ num_beams * torch.div(beam_idx, group_size, rounding_mode="floor")
+ + group_start_idx
+ + (beam_idx % group_size)
+ )
+
+ # Store scores, attentions and hidden_states when required
+ if return_dict_in_generate:
+ if output_scores:
+ scores += (processed_score,)
+ if output_logits:
+ raw_logits += (raw_logit_score,)
+ if output_attentions:
+ decoder_attentions += (
+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
+ )
+ if self.config.is_encoder_decoder:
+ cross_attentions += (outputs.cross_attentions,)
+
+ if output_hidden_states:
+ decoder_hidden_states += (
+ (outputs.decoder_hidden_states,)
+ if self.config.is_encoder_decoder
+ else (outputs.hidden_states,)
+ )
+
+ input_ids = torch.cat([input_ids, current_tokens.unsqueeze(-1)], dim=-1)
+
+ # This is needed to properly delete outputs.logits which may be very large for first iteration
+ # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
+ # IMPORTANT: Note that this should appear BEFORE the call to _reorder_cache() to save the maximum memory
+ # (that way the memory peak does not include outputs.logits)
+ del outputs
+
+ if model_kwargs.get("past_key_values", None) is not None:
+ model_kwargs["past_key_values"] = self._temporary_reorder_cache(
+ model_kwargs["past_key_values"], reordering_indices
+ )
+
+ # increase cur_len
+ cur_len = cur_len + 1
+
+ if beam_scorer.is_done or all(stopping_criteria(input_ids, scores)):
+ this_peer_finished = True
+
+ final_beam_indices = sum(beam_indices, ()) if beam_indices is not None else None
+ sequence_outputs = beam_scorer.finalize(
+ input_ids,
+ beam_scores,
+ next_tokens,
+ next_indices,
+ pad_token_id=pad_token_id,
+ eos_token_id=eos_token_id,
+ max_length=stopping_criteria.max_length,
+ beam_indices=final_beam_indices,
+ decoder_prompt_len=decoder_prompt_len,
+ )
+
+ if return_dict_in_generate:
+ if not output_scores:
+ sequence_outputs["sequence_scores"] = None
+
+ if self.config.is_encoder_decoder:
+ return GenerateBeamEncoderDecoderOutput(
+ sequences=sequence_outputs["sequences"],
+ sequences_scores=sequence_outputs["sequence_scores"],
+ scores=scores,
+ logits=raw_logits,
+ beam_indices=sequence_outputs["beam_indices"],
+ encoder_attentions=encoder_attentions,
+ encoder_hidden_states=encoder_hidden_states,
+ decoder_attentions=decoder_attentions,
+ cross_attentions=cross_attentions,
+ decoder_hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return GenerateBeamDecoderOnlyOutput(
+ sequences=sequence_outputs["sequences"],
+ sequences_scores=sequence_outputs["sequence_scores"],
+ scores=scores,
+ logits=raw_logits,
+ beam_indices=sequence_outputs["beam_indices"],
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return sequence_outputs["sequences"]
+
+ def _constrained_beam_search(
+ self,
+ input_ids: torch.LongTensor,
+ constrained_beam_scorer: ConstrainedBeamSearchScorer,
+ logits_processor: LogitsProcessorList,
+ stopping_criteria: StoppingCriteriaList,
+ generation_config: GenerationConfig,
+ synced_gpus: bool,
+ **model_kwargs,
+ ) -> Union[GenerateBeamOutput, torch.LongTensor]:
+ r"""
+ Generates sequences of token ids for models with a language modeling head using **constrained beam search
+ decoding** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
+
+ Parameters:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ The sequence used as a prompt for the generation.
+ constrained_beam_scorer (`ConstrainedBeamSearchScorer`):
+ A derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and
+ sorted during generation, while satisfying a list of positive constraints. For more information, the
+ documentation of [`ConstrainedBeamSearchScorer`] should be read.
+ logits_processor (`LogitsProcessorList`):
+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ stopping_criteria (`StoppingCriteriaList`):
+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
+ used to tell if the generation loop should stop.
+ generation_config ([`~generation.GenerationConfig`]):
+ The generation configuration to be used as parametrization of the decoding method.
+ synced_gpus (`bool`):
+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with
+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
+ model_kwargs:
+ Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
+ an encoder-decoder model the kwargs should include `encoder_outputs`.
+
+ Return:
+ [`~generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
+ `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
+ [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
+ `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
+ `model.config.is_encoder_decoder=True`.
+ """
+ # init values
+ pad_token_id = generation_config._pad_token_tensor
+ eos_token_id = generation_config._eos_token_tensor
+ output_attentions = generation_config.output_attentions
+ output_hidden_states = generation_config.output_hidden_states
+ output_scores = generation_config.output_scores
+ output_logits = generation_config.output_logits
+ return_dict_in_generate = generation_config.return_dict_in_generate
+
+ batch_size = len(constrained_beam_scorer._beam_hyps)
+ num_beams = constrained_beam_scorer.num_beams
+
+ batch_beam_size, cur_len = input_ids.shape
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
+
+ if num_beams * batch_size != batch_beam_size:
+ raise ValueError(
+ f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."
+ )
+
+ # init attention / hidden states / scores tuples
+ scores = () if (return_dict_in_generate and output_scores) else None
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
+ beam_indices = (
+ tuple(() for _ in range(batch_beam_size)) if (return_dict_in_generate and output_scores) else None
+ )
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
+
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
+ if return_dict_in_generate and self.config.is_encoder_decoder:
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
+ encoder_hidden_states = (
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
+ )
+
+ # initialise score of first beam with 0 and the rest with -1e9. This makes sure that only tokens
+ # of the first beam are considered to avoid sampling the exact same tokens across all beams.
+ beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device)
+ beam_scores[:, 1:] = -1e9
+ beam_scores = beam_scores.view((batch_size * num_beams,))
+
+ this_peer_finished = False
+
+ decoder_prompt_len = input_ids.shape[-1] # record the prompt length of decoder
+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
+
+ # prepare variable output controls (note: some models won't accept all output controls)
+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
+ model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
+
+ outputs = self(**model_inputs, return_dict=True)
+
+ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs,
+ model_kwargs,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ )
+ if synced_gpus and this_peer_finished:
+ cur_len = cur_len + 1
+ continue
+
+ # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration
+ # (the clone itself is always small)
+ # .float() is needed to retain precision for later logits manipulations
+ next_token_logits = outputs.logits[:, -1, :].clone().float()
+ next_token_logits = next_token_logits.to(input_ids.device)
+ next_token_scores = nn.functional.log_softmax(
+ next_token_logits, dim=-1
+ ) # (batch_size * num_beams, vocab_size)
+
+ next_token_scores_processed = logits_processor(input_ids, next_token_scores)
+
+ next_token_scores = next_token_scores_processed + beam_scores[:, None].expand_as(
+ next_token_scores_processed
+ )
+
+ scores_for_all_vocab = next_token_scores.clone()
+
+ # Store scores, attentions and hidden_states when required
+ if return_dict_in_generate:
+ if output_scores:
+ scores += (next_token_scores,)
+ if output_logits:
+ raw_logits += (next_token_logits,)
+ if output_attentions:
+ decoder_attentions += (
+ (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
+ )
+ if self.config.is_encoder_decoder:
+ cross_attentions += (outputs.cross_attentions,)
+
+ if output_hidden_states:
+ decoder_hidden_states += (
+ (outputs.decoder_hidden_states,)
+ if self.config.is_encoder_decoder
+ else (outputs.hidden_states,)
+ )
+
+ # reshape for beam search
+ vocab_size = next_token_scores.shape[-1]
+ next_token_scores = next_token_scores.view(batch_size, num_beams * vocab_size)
+
+ # Sample 1 + len(eos_token_id) next tokens for each beam so we have at least 1 non eos token per beam.
+ n_eos_tokens = eos_token_id.shape[0] if eos_token_id is not None else 0
+ next_token_scores, next_tokens = torch.topk(
+ next_token_scores, max(2, 1 + n_eos_tokens) * num_beams, dim=1, largest=True, sorted=True
+ )
+
+ next_indices = (next_tokens / vocab_size).long()
+ next_tokens = next_tokens % vocab_size
+
+ # stateless
+ beam_outputs = constrained_beam_scorer.process(
+ input_ids,
+ next_token_scores,
+ next_tokens,
+ next_indices,
+ scores_for_all_vocab,
+ pad_token_id=pad_token_id,
+ eos_token_id=eos_token_id,
+ beam_indices=beam_indices,
+ decoder_prompt_len=decoder_prompt_len,
+ )
+ beam_scores = beam_outputs["next_beam_scores"]
+ beam_next_tokens = beam_outputs["next_beam_tokens"]
+ beam_idx = beam_outputs["next_beam_indices"]
+
+ input_ids = torch.cat([input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)
+
+ # This is needed to properly delete outputs.logits which may be very large for first iteration
+ # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration
+ # IMPORTANT: Note that this should appear BEFORE the call to _reorder_cache() to save the maximum memory
+ # (that way the memory peak does not include outputs.logits)
+ del outputs
+
+ if model_kwargs.get("past_key_values", None) is not None:
+ model_kwargs["past_key_values"] = self._temporary_reorder_cache(
+ model_kwargs["past_key_values"], beam_idx
+ )
+
+ if return_dict_in_generate and output_scores:
+ beam_indices = tuple((beam_indices[beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices))))
+
+ # increase cur_len
+ cur_len = cur_len + 1
+
+ if constrained_beam_scorer.is_done or all(stopping_criteria(input_ids, scores)):
+ this_peer_finished = True
+
+ sequence_outputs = constrained_beam_scorer.finalize(
+ input_ids,
+ beam_scores,
+ next_tokens,
+ next_indices,
+ pad_token_id=pad_token_id,
+ eos_token_id=eos_token_id,
+ max_length=stopping_criteria.max_length,
+ beam_indices=beam_indices,
+ decoder_prompt_len=decoder_prompt_len,
+ )
+
+ if return_dict_in_generate:
+ if not output_scores:
+ sequence_outputs["sequence_scores"] = None
+ if self.config.is_encoder_decoder:
+ return GenerateBeamEncoderDecoderOutput(
+ sequences=sequence_outputs["sequences"],
+ sequences_scores=sequence_outputs["sequence_scores"],
+ scores=scores,
+ logits=raw_logits,
+ beam_indices=sequence_outputs["beam_indices"],
+ encoder_attentions=encoder_attentions,
+ encoder_hidden_states=encoder_hidden_states,
+ decoder_attentions=decoder_attentions,
+ cross_attentions=cross_attentions,
+ decoder_hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return GenerateBeamDecoderOnlyOutput(
+ sequences=sequence_outputs["sequences"],
+ sequences_scores=sequence_outputs["sequence_scores"],
+ scores=scores,
+ logits=raw_logits,
+ beam_indices=sequence_outputs["beam_indices"],
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return sequence_outputs["sequences"]
+
+ def _assisted_decoding(
+ self,
+ input_ids: torch.LongTensor,
+ candidate_generator: CandidateGenerator,
+ logits_processor: LogitsProcessorList,
+ stopping_criteria: StoppingCriteriaList,
+ generation_config: GenerationConfig,
+ synced_gpus: bool,
+ streamer: Optional["BaseStreamer"],
+ **model_kwargs,
+ ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
+ r"""
+ Generates sequences of token ids for models with a language modeling head using **greedy decoding** or
+ **sample** (depending on `do_sample`), assisted by candidate sequences. Assisted generation is an example of a
+ candidate decoding strategy. Can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text
+ models.
+
+ Parameters:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ The sequence used as a prompt for the generation.
+ candidate_generator (`CandidateGenerator`):
+ A derived instance of [`CandidateGenerator`] that defines how candidate sequences are generated. For
+ more information, the documentation of [`CandidateGenerator`] should be read.
+ logits_processor (`LogitsProcessorList`):
+ An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
+ used to modify the prediction scores of the language modeling head applied at each generation step.
+ stopping_criteria (`StoppingCriteriaList`):
+ An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
+ used to tell if the generation loop should stop.
+ generation_config ([`~generation.GenerationConfig`]):
+ The generation configuration to be used as parametrization of the decoding method.
+ synced_gpus (`bool`):
+ Whether to continue running the while loop until max_length (needed to avoid deadlocking with
+ `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).
+ streamer (`BaseStreamer`, *optional*):
+ Streamer object that will be used to stream the generated sequences. Generated tokens are passed
+ through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
+ model_kwargs:
+ Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
+ If model is an encoder-decoder model the kwargs should include `encoder_outputs`.
+
+ Return:
+ [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`] or
+ `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
+ [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
+ `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
+ `model.config.is_encoder_decoder=True`.
+ """
+ # init values
+ do_sample = generation_config.do_sample
+ output_attentions = generation_config.output_attentions
+ output_hidden_states = generation_config.output_hidden_states
+ output_scores = generation_config.output_scores
+ output_logits = generation_config.output_logits
+ return_dict_in_generate = generation_config.return_dict_in_generate
+
+ # init attention / hidden states / scores tuples
+ scores = () if (return_dict_in_generate and output_scores) else None
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
+
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
+ if return_dict_in_generate and self.config.is_encoder_decoder:
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
+ encoder_hidden_states = (
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
+ )
+
+ # keep track of which sequences are already finished
+ batch_size = input_ids.shape[0]
+ unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
+ model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
+
+ this_peer_finished = False
+ is_first_iteration = True # to preserve the same API in the output as other generation methods
+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
+ cur_len = input_ids.shape[-1]
+
+ # 1. Fetch candidate sequences from a `CandidateGenerator` and move to the correct device
+ candidate_input_ids, candidate_logits = candidate_generator.get_candidates(input_ids)
+ candidate_input_ids = candidate_input_ids.to(self.device)
+ if candidate_logits is not None:
+ candidate_logits = candidate_logits.to(self.device)
+
+ candidate_length = candidate_input_ids.shape[1] - input_ids.shape[1]
+ is_done_candidate = stopping_criteria(candidate_input_ids, None)
+
+ # 2. Use the original model to obtain the next token logits given the candidate sequence. We obtain
+ # `candidate_length + 1` relevant logits from this process: in the event that all candidates are correct,
+ # we use this forward pass to also pick the subsequent logits in the original model.
+
+ # 2.1. Prepare the model inputs
+ candidate_kwargs = copy.copy(model_kwargs)
+ candidate_kwargs = _prepare_attention_mask(
+ candidate_kwargs, candidate_input_ids.shape[1], self.config.is_encoder_decoder
+ )
+ candidate_kwargs = _prepare_token_type_ids(candidate_kwargs, candidate_input_ids.shape[1])
+ if "cache_position" in candidate_kwargs:
+ candidate_kwargs["cache_position"] = torch.cat(
+ (
+ candidate_kwargs["cache_position"],
+ torch.arange(cur_len, cur_len + candidate_length, device=input_ids.device, dtype=torch.long),
+ ),
+ dim=0,
+ )
+
+ model_inputs = self.prepare_inputs_for_generation(candidate_input_ids, **candidate_kwargs)
+ if "logits_to_keep" in model_inputs:
+ model_inputs["logits_to_keep"] = candidate_length + 1
+
+ # 2.2. Run a forward pass on the candidate sequence
+ # prepare variable output controls (note: some models won't accept all output controls)
+ model_inputs.update({"output_attentions": output_attentions} if output_attentions else {})
+ model_inputs.update({"output_hidden_states": output_hidden_states} if output_hidden_states else {})
+
+ outputs = self(**model_inputs)
+
+ # 2.3. Process the new logits
+ # .float() is needed to retain precision for later logits manipulations
+ new_logits = outputs.logits[:, -candidate_length - 1 :].float() # excludes the input prompt if present
+ new_logits = new_logits.to(input_ids.device)
+ next_token_logits = new_logits.clone()
+ if len(logits_processor) > 0:
+ for i in range(candidate_length + 1):
+ new_logits[:, i, :] = logits_processor(candidate_input_ids[:, : cur_len + i], new_logits[:, i, :])
+
+ # 3. Select the accepted tokens. There are two possible cases:
+ # Case 1: `do_sample=True` and we have logits for the candidates (originally from speculative decoding)
+ # 👉 Apply algorithm 1 from the speculative decoding paper (https://arxiv.org/pdf/2211.17192.pdf).
+ if do_sample and candidate_logits is not None:
+ valid_tokens, n_matches = _speculative_sampling(
+ candidate_input_ids,
+ candidate_logits,
+ candidate_length,
+ new_logits,
+ is_done_candidate,
+ )
+
+ # Case 2: all other cases (originally from assisted generation) 👉 Compare the tokens selected from the
+ # original model logits with the candidate tokens. We can keep the candidate tokens until the first
+ # mismatch, or until the max length is reached.
+ else:
+ if do_sample:
+ probs = new_logits.softmax(dim=-1)
+ selected_tokens = torch.multinomial(probs[0, :, :], num_samples=1).squeeze(1)[None, :]
+ else:
+ selected_tokens = new_logits.argmax(dim=-1)
+
+ candidate_new_tokens = candidate_input_ids[:, cur_len:]
+ n_matches = ((~(candidate_new_tokens == selected_tokens[:, :-1])).cumsum(dim=-1) < 1).sum()
+
+ # Ensure we don't generate beyond max_len or an EOS token
+ if is_done_candidate and n_matches == candidate_length:
+ n_matches -= 1
+ valid_tokens = selected_tokens[:, : n_matches + 1]
+
+ # 4. Update variables according to the number of matching assistant tokens. Remember: the token generated
+ # by the model after the last candidate match is also valid, as it is generated from a correct sequence.
+ # Because of this last token, assisted generation search reduces to a normal greedy search/sample if there
+ # is no match.
+
+ # 4.1. Get the valid continuation, after the matching tokens
+ input_ids = torch.cat((input_ids, valid_tokens), dim=-1)
+ if streamer is not None:
+ streamer.put(valid_tokens.cpu())
+ new_cur_len = input_ids.shape[-1]
+
+ # 4.2. Discard past key values relative to unused assistant tokens
+ new_cache_size = new_cur_len - 1
+ outputs.past_key_values = _crop_past_key_values(self, outputs.past_key_values, new_cache_size)
+
+ # 5. Update the candidate generation strategy if needed
+ candidate_generator.update_candidate_strategy(input_ids, new_logits, n_matches)
+
+ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
+ model_kwargs = self._update_model_kwargs_for_generation(
+ outputs,
+ model_kwargs,
+ is_encoder_decoder=self.config.is_encoder_decoder,
+ num_new_tokens=n_matches + 1,
+ )
+ if synced_gpus and this_peer_finished:
+ continue
+
+ # Store scores, attentions and hidden_states when required
+ # Assistant: modified to append one tuple element per token, as in the other generation methods.
+ if return_dict_in_generate:
+ newly_added_length = n_matches + 1
+ if output_scores:
+ scores += tuple(new_logits[:, i, :] for i in range(newly_added_length))
+ if output_logits:
+ raw_logits += tuple(next_token_logits[:, i, :] for i in range(newly_added_length))
+
+ newly_added_length = new_cur_len if is_first_iteration else newly_added_length
+ if output_attentions:
+ if self.config.is_encoder_decoder:
+ cross_attentions = _split_model_outputs(
+ cross_attentions, outputs.cross_attentions, cur_len, newly_added_length
+ )
+ decoder_attentions = _split_model_outputs(
+ decoder_attentions,
+ outputs.decoder_attentions,
+ cur_len,
+ newly_added_length,
+ is_decoder_attention=True,
+ )
+ # some (V)LLMs have hard requirement on SDPA and thus never return attn
+ elif outputs.attentions[0] is not None:
+ decoder_attentions = _split_model_outputs(
+ decoder_attentions,
+ outputs.attentions,
+ cur_len,
+ newly_added_length,
+ is_decoder_attention=True,
+ )
+ if output_hidden_states:
+ if self.config.is_encoder_decoder:
+ decoder_hidden_states = _split_model_outputs(
+ decoder_hidden_states, outputs.decoder_hidden_states, cur_len, newly_added_length
+ )
+ else:
+ decoder_hidden_states = _split_model_outputs(
+ decoder_hidden_states, outputs.hidden_states, cur_len, newly_added_length
+ )
+
+ unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
+ this_peer_finished = unfinished_sequences.max() == 0
+ is_first_iteration = False
+
+ if streamer is not None:
+ streamer.end()
+
+ if (
+ hasattr(candidate_generator, "assistant_model")
+ and candidate_generator.assistant_model.generation_config.num_assistant_tokens_schedule == "heuristic"
+ ):
+ candidate_generator.assistant_model.generation_config.num_assistant_tokens = (
+ candidate_generator.num_assistant_tokens
+ )
+ if return_dict_in_generate:
+ if self.config.is_encoder_decoder:
+ return GenerateEncoderDecoderOutput(
+ sequences=input_ids,
+ scores=scores,
+ logits=raw_logits,
+ encoder_attentions=encoder_attentions,
+ encoder_hidden_states=encoder_hidden_states,
+ decoder_attentions=decoder_attentions,
+ cross_attentions=cross_attentions,
+ decoder_hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return GenerateDecoderOnlyOutput(
+ sequences=input_ids,
+ scores=scores,
+ logits=raw_logits,
+ attentions=decoder_attentions,
+ hidden_states=decoder_hidden_states,
+ past_key_values=model_kwargs.get("past_key_values"),
+ )
+ else:
+ return input_ids
+
+
+def _speculative_sampling(
+ candidate_input_ids,
+ candidate_logits,
+ candidate_length,
+ new_logits,
+ is_done_candidate,
+):
+ """
+ Applies sampling as in the speculative decoding paper (https://arxiv.org/pdf/2211.17192.pdf, algorithm 1). Returns
+ the selected tokens, as well as the number of candidate matches.
+
+ NOTE: Unless otherwise stated, the variable names match those in the paper.
+ """
+ new_candidate_input_ids = candidate_input_ids[:, -candidate_length:]
+ # Gets the probabilities from the logits. q_i and p_i denote the assistant and model probabilities of the tokens
+ # selected by the assistant, respectively.
+ q = candidate_logits.softmax(dim=-1)
+ q_i = q[:, torch.arange(candidate_length), new_candidate_input_ids].squeeze(0, 1)
+ p = new_logits.softmax(dim=-1)
+ p_i = p[:, torch.arange(candidate_length), new_candidate_input_ids].squeeze(0, 1)
+ probability_ratio = p_i / q_i
+
+ # When probability_ratio > 1 (i.e. q_i(x) < p_i(x), or "assistant probability of the candidate token is smaller
+ # than the model probability for the same token"), keep the token. Otherwise reject with p = 1 - probability_ratio
+ # (= keep with p = probability_ratio). Keep all the tokens until the first rejection
+ r_i = torch.rand_like(probability_ratio)
+ is_accepted = r_i <= probability_ratio
+ n_matches = ((~is_accepted).cumsum(dim=-1) < 1).sum() # this is `n` in algorithm 1
+
+ # Ensure we don't generate beyond max_len or an EOS token (not in algorithm 1, but needed for correct behavior)
+ if is_done_candidate and n_matches == candidate_length:
+ # Output length is assumed to be `n_matches + 1`. Since we won't generate another token with the target model
+ # due to acceptance on EOS we fix `n_matches`
+ n_matches -= 1
+ valid_tokens = new_candidate_input_ids[:, : n_matches + 1]
+ else:
+ # Next token selection: if there is a rejection, adjust the distribution from the main model before sampling.
+ gamma = candidate_logits.shape[1]
+ p_n_plus_1 = p[:, n_matches, :]
+ if n_matches < gamma:
+ q_n_plus_1 = q[:, n_matches, :]
+ p_prime = torch.clamp((p_n_plus_1 - q_n_plus_1), min=0)
+ p_prime.div_(p_prime.sum())
+ else:
+ p_prime = p_n_plus_1
+ t = torch.multinomial(p_prime, num_samples=1).squeeze(1)[None, :]
+
+ # The selected tokens include the matches (if any) plus the next sampled tokens
+ if n_matches > 0:
+ valid_tokens = torch.cat((new_candidate_input_ids[:, :n_matches], t), dim=-1)
+ else:
+ valid_tokens = t
+
+ return valid_tokens, n_matches
+
+
+def _split_model_outputs(outputs, new_outputs, cur_len, added_len, is_decoder_attention=False):
+ """
+ Given the (decoder/cross attentions)/(decoder hidden states) for multiple generated tokens, splits it into a tuple
+ where each member corresponds to a single generated token.
+ """
+ # Retrocompatibility: in our generation functions, the first iteration includes the attention/hidden states for the
+ # prompt.
+ if len(outputs) == 0:
+ new_tuple = ()
+ for layer in new_outputs:
+ last_dim_size = cur_len if is_decoder_attention else layer.shape[-1]
+ new_tuple += (layer[..., :cur_len, :last_dim_size],)
+ outputs += (new_tuple,)
+ # The first iteration contains the prompt + 1 generated token, let's update the length variables accordingly
+ cur_len += 1
+ added_len -= cur_len
+
+ for i in range(added_len):
+ new_tuple = ()
+ for layer in new_outputs:
+ last_dim_size = cur_len + i if is_decoder_attention else layer.shape[-1]
+ new_tuple += (layer[..., i : i + 1, :last_dim_size],)
+ outputs += (new_tuple,)
+ return outputs
+
+
+def _ranking_fast(
+ context_hidden: torch.FloatTensor,
+ next_hidden: torch.FloatTensor,
+ next_top_k_probs: torch.FloatTensor,
+ cosine_matrix_mask: torch.LongTensor,
+ alpha: float,
+ beam_width: int,
+) -> torch.FloatTensor:
+ """
+ Reranks the top_k candidates based on a degeneration penalty (cosine similarity with previous tokens), as described
+ in the paper "A Contrastive Framework for Neural Text Generation". Returns the index of the best candidate for each
+ row in the batch.
+ """
+ norm_context_hidden = context_hidden / context_hidden.norm(dim=2, keepdim=True)
+ norm_next_hidden = next_hidden / next_hidden.norm(dim=2, keepdim=True)
+ cosine_matrix = torch.matmul(norm_context_hidden, norm_next_hidden.transpose(1, 2)).squeeze(-1) # [B*K, S]
+
+ # Penalize cosine_matrix based on the cosine_matrix_mask (ignore padding positions)
+ # Using a large negative value for masked positions
+ cosine_matrix_mask = cosine_matrix_mask.to(dtype=cosine_matrix.dtype)
+ cosine_matrix_mask = (1 - cosine_matrix_mask) * torch.finfo(cosine_matrix.dtype).min
+ cosine_matrix = cosine_matrix + cosine_matrix_mask
+
+ degeneration_penalty, _ = torch.max(cosine_matrix, dim=-1) # [B*K]
+ next_top_k_probs = next_top_k_probs.view(-1) # [B*K]
+ contrastive_score = (1.0 - alpha) * next_top_k_probs - alpha * degeneration_penalty
+ contrastive_score = torch.stack(torch.split(contrastive_score, beam_width)) # [B, K]
+ _, selected_idx = contrastive_score.max(dim=-1) # [B]
+ return selected_idx
+
+
+def _split(data, full_batch_size: int, split_size: int = None):
+ """
+ Takes care of three cases:
+ 1. data is a tensor: e.g. last_hidden_state, pooler_output etc. split them on the batch_size dim
+ 2. data is a tuple: e.g. hidden_states, attentions etc. Keep the tuple as it is and split each tensor in it and
+ return a list of tuples
+ 3. data is a tuple of tuples, e.g. past_key_values. Keep the tuple as it is and split each tuple in it and
+ return a list of tuples of tuples
+ (see documentation of ModelOutput)
+ """
+ if data is None:
+ return [None] * (full_batch_size // split_size)
+ if isinstance(data, torch.Tensor):
+ return [data[i : i + split_size] for i in range(0, full_batch_size, split_size)]
+ # New cache format
+ elif isinstance(data, DynamicCache) or (
+ isinstance(data, EncoderDecoderCache) and isinstance(data.self_attention_cache, DynamicCache)
+ ):
+ return data.batch_split(full_batch_size, split_size)
+ elif isinstance(data, tuple):
+ # If the elements of the tuple are also tuples (e.g., past_key_values in our earlier example)
+ if isinstance(data[0], tuple):
+ return [
+ tuple(tuple(tensor[i : i + split_size] for tensor in inner_tuple) for inner_tuple in data)
+ for i in range(0, full_batch_size, split_size)
+ ]
+
+ else:
+ return [
+ tuple(sub_tensor[i : i + split_size] for sub_tensor in data)
+ for i in range(0, full_batch_size, split_size)
+ ]
+ else:
+ raise TypeError(f"Unexpected attribute type: {type(data)}")
+
+
+def _split_model_inputs(
+ model_input: Union[ModelOutput, Dict], split_size: int, full_batch_size: int, config: PretrainedConfig
+) -> List[Union[ModelOutput, Dict]]:
+ """
+ Split a ModelOutput object (or its subclasses) or Dict into a list of same-class objects based on a specified split
+ size. The input object is dict when it was prepared for forward pass and ModelOutput when it was returned from
+ previous forward pass.
+ """
+ # Edge case: if model_input is None, return a list of Nones
+ # this happens with Whisper where encoder_outputs is None
+ if model_input is None:
+ return [model_input] * (full_batch_size // split_size)
+ # Infer the class from the object
+ model_output_cls = type(model_input)
+ if (full_batch_size % split_size) != 0:
+ raise ValueError("`full_batch_size` must be divisible by `split_size`")
+
+ if split_size > full_batch_size:
+ raise ValueError("`split_size` must be smaller or equal to `full_batch_size`")
+
+ # Helper function to split tensors or tuples of tensors
+
+ # Find all the dataclass fields (e.g., last_hidden_state, pooler_output etc.) and split them
+ keys = (
+ model_input.__dataclass_fields__.keys() if hasattr(model_input, "__dataclass_fields__") else model_input.keys()
+ )
+ # We only keep keys that are in the model_input
+ keys = [k for k in keys if k in model_input]
+ # Here we can have four types of values: tensors, tuples of tensors and booleans, and encoder_outputs which is a
+ # ModelOutput object.
+ # bool should not be split but replicated for each split
+ bool_keys = [k for k in keys if isinstance(model_input[k], bool) or k == "cache_position"]
+ keys_to_ignore = ["cache_position", "encoder_outputs", "logits_to_keep"]
+ non_bool_keys = [k for k in keys if not isinstance(model_input[k], bool) and k not in keys_to_ignore]
+
+ # we split the tensors and tuples of tensors
+ data_split_list = [
+ {k: _split(model_input[k], full_batch_size, split_size)[i] for k in non_bool_keys}
+ for i in range(full_batch_size // split_size)
+ ]
+ # bool values are the same and replicated for each split
+ bool_data = {k: model_input[k] for k in bool_keys}
+ # encoder_outputs is a ModelOutput object and should be split by its own
+ if "encoder_outputs" in model_input:
+ encoder_outputs_split = _split_model_inputs(
+ model_input["encoder_outputs"], split_size, full_batch_size, config.get_text_config()
+ )
+ data_split_list = [
+ {**data_split, "encoder_outputs": encoder_outputs_split[i]} for i, data_split in enumerate(data_split_list)
+ ]
+ # logits_to_keep should be replicated for each split, similar to bool values
+ if "logits_to_keep" in model_input:
+ data_split_list = [
+ {**data_split, "logits_to_keep": model_input["logits_to_keep"]} for data_split in data_split_list
+ ]
+
+ # Convert each dictionary in the list to an object of the inferred class
+ split_model_inputs: List[Union[ModelOutput, Dict]] = [
+ model_output_cls(**data_split, **bool_data) for data_split in data_split_list
+ ]
+
+ return split_model_inputs
+
+
+def stack_model_outputs(model_outputs: List[ModelOutput], config: PretrainedConfig) -> ModelOutput:
+ """
+ Stack a list of ModelOutput objects (or its subclasses) along the batch_size dimension. The function infers the
+ specific ModelOutput subclass from the list provided.
+ """
+ if not model_outputs:
+ raise ValueError("Input list is empty.")
+
+ # Infer the class from the first object in the list
+ model_output_cls = type(model_outputs[0])
+
+ # Ensure all objects are of the same type
+ if not all(isinstance(obj, model_output_cls) for obj in model_outputs):
+ raise ValueError("All elements in the list should be of the same type.")
+
+ # Helper function to concat tensors or tuples of tensors
+ def _concat(data):
+ """
+ Reverse of `_split` function above.
+ """
+ if any(data is None for data in data):
+ return None
+ if isinstance(data[0], torch.Tensor):
+ return torch.cat(data, dim=0)
+ # New cache format
+ elif isinstance(data[0], DynamicCache):
+ return DynamicCache.from_batch_splits(data)
+ elif isinstance(data[0], EncoderDecoderCache):
+ return EncoderDecoderCache.from_batch_splits(data)
+ elif isinstance(data[0], tuple):
+ # If the elements of the tuple are also tuples (e.g., past_key_values in our earlier example)
+ if isinstance(data[0][0], tuple):
+ return tuple(
+ tuple(torch.cat([attr[i][j] for attr in data], dim=0) for j in range(len(data[0][0])))
+ for i in range(len(data[0]))
+ )
+ else:
+ return tuple(torch.cat([attr[i] for attr in data], dim=0) for i in range(len(data[0])))
+ elif isinstance(data[0], (int, float)):
+ # If the elements are integers or floats, return a tensor
+ return torch.tensor(data)
+ else:
+ raise TypeError(f"Unexpected attribute type: {type(data[0])}")
+
+ # Use a dictionary comprehension to gather attributes from all objects and concatenate them
+ concatenated_data = {
+ k: _concat([getattr(model_output, k) for model_output in model_outputs])
+ for k in model_output_cls.__dataclass_fields__.keys()
+ }
+
+ # Return a new object of the inferred class with the concatenated attributes
+ return model_output_cls(**concatenated_data)
+
+
+def _relative_top_filter(
+ scores: torch.FloatTensor,
+ baseline_scores: torch.FloatTensor,
+ relative_top: float = 0.1,
+ filter_value: float = -float("Inf"),
+ base_filter_value=-1e-3,
+ min_tokens_to_keep: int = 1,
+) -> torch.FloatTensor:
+ """
+ Reference: https://github.com/XiangLi1999/ContrastiveDecoding/blob/170e9142e92159c1237d731e240f5eb14aabf428/transformers/src/transformers/generation_logits_process.py#L235
+ Apply filtering to only keep tokens with a probability above a certain threshold. The threshold is defined as `relative_top` * max probability in the distribution.
+ """
+ scores_normalized = scores.log_softmax(dim=-1)
+ baseline_scores_normalized = baseline_scores.log_softmax(dim=-1)
+ sorted_logits, sorted_indices = torch.sort(scores_normalized, descending=True)
+ min_thresh = sorted_logits[..., min_tokens_to_keep - 1]
+ probs_max = torch.max(scores_normalized, dim=-1).values
+ probs_thresh = probs_max + np.log(relative_top)
+ probs_thresh = torch.min(min_thresh, probs_thresh)
+ probs_thresh = probs_thresh.unsqueeze(-1)
+ baseline_scores_normalized[scores_normalized < probs_thresh] = base_filter_value
+ scores_normalized[scores_normalized < probs_thresh] = filter_value
+ return scores_normalized, baseline_scores_normalized
+
+
+def _dola_select_contrast(
+ candidate_premature_layers: List[int],
+ candidate_premature_logits: Dict[int, torch.FloatTensor],
+ final_logits: torch.FloatTensor,
+) -> torch.FloatTensor:
+ if len(candidate_premature_layers) == 1:
+ base_logits = candidate_premature_logits[candidate_premature_layers[0]]
+ final_logits, base_logits = _relative_top_filter(final_logits, base_logits)
+ logits = final_logits - base_logits
+ return logits
+
+ # 1. Stacking all premature_layers into a new dimension
+ stacked_premature_layers = torch.stack([candidate_premature_logits[i] for i in candidate_premature_layers], dim=0)
+
+ # 2. Calculate the softmax values for mature_layer and all premature_layers
+ # shape: (batch_size, vocab_size)
+ softmax_mature_layer = F.softmax(final_logits, dim=-1)
+ # shape: (num_premature_layers, batch_size, vocab_size)
+ softmax_premature_layers = F.softmax(stacked_premature_layers, dim=-1)
+
+ # 3. Calculate the average distribution
+ # shape: (num_premature_layers, batch_size, vocab_size)
+ avg_dist = 0.5 * (softmax_mature_layer[None, :, :] + softmax_premature_layers)
+
+ # 4. Calculate log-softmax for the KL divergence
+ # shape: (batch_size, vocab_size)
+ log_softmax_mature_layer = F.log_softmax(final_logits, dim=-1)
+ # shape: (num_premature_layers, batch_size, vocab_size)
+ log_softmax_premature_layers = F.log_softmax(stacked_premature_layers, dim=-1)
+
+ # 5. Calculate the KL divergences and then the JS divergences
+ # shape: (num_premature_layers, batch_size)
+ kl1 = F.kl_div(log_softmax_mature_layer[None, :, :], avg_dist, reduction="none").mean(-1)
+ # shape: (num_premature_layers, batch_size)
+ kl2 = F.kl_div(log_softmax_premature_layers, avg_dist, reduction="none").mean(-1)
+ js_divs = 0.5 * (kl1 + kl2) # shape: (num_premature_layers, batch_size)
+
+ # 6. Reduce the batchmean
+ js_divs = js_divs.mean(-1) # shape: (num_premature_layers,)
+ premature_layer = candidate_premature_layers[int(js_divs.argmax().cpu().item())]
+
+ base_logits = candidate_premature_logits[premature_layer]
+ final_logits, base_logits = _relative_top_filter(final_logits, base_logits)
+ logits = final_logits - base_logits
+ return logits
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/watermarking.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/watermarking.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c728a287b89792b8f33424a44c0b5d4b7ed651e
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/generation/watermarking.py
@@ -0,0 +1,549 @@
+# coding=utf-8
+# Copyright 2024 The HuggingFace Inc. team and Google DeepMind.
+#
+# 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 collections
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, Dict, Optional, Tuple, Union
+
+import numpy as np
+import torch
+from torch import nn
+from torch.nn import BCELoss
+
+from ..modeling_utils import PreTrainedModel
+from ..utils import ModelOutput, is_torch_available, logging
+from .configuration_utils import PretrainedConfig, WatermarkingConfig
+
+
+if is_torch_available():
+ import torch
+
+ from .logits_process import SynthIDTextWatermarkLogitsProcessor, WatermarkLogitsProcessor
+
+
+logger = logging.get_logger(__name__)
+
+
+@dataclass
+class WatermarkDetectorOutput:
+ """
+ Outputs of a watermark detector.
+
+ Args:
+ num_tokens_scored (np.array of shape (batch_size)):
+ Array containing the number of tokens scored for each element in the batch.
+ num_green_tokens (np.array of shape (batch_size)):
+ Array containing the number of green tokens for each element in the batch.
+ green_fraction (np.array of shape (batch_size)):
+ Array containing the fraction of green tokens for each element in the batch.
+ z_score (np.array of shape (batch_size)):
+ Array containing the z-score for each element in the batch. Z-score here shows
+ how many standard deviations away is the green token count in the input text
+ from the expected green token count for machine-generated text.
+ p_value (np.array of shape (batch_size)):
+ Array containing the p-value for each batch obtained from z-scores.
+ prediction (np.array of shape (batch_size)), *optional*:
+ Array containing boolean predictions whether a text is machine-generated for each element in the batch.
+ confidence (np.array of shape (batch_size)), *optional*:
+ Array containing confidence scores of a text being machine-generated for each element in the batch.
+ """
+
+ num_tokens_scored: np.array = None
+ num_green_tokens: np.array = None
+ green_fraction: np.array = None
+ z_score: np.array = None
+ p_value: np.array = None
+ prediction: Optional[np.array] = None
+ confidence: Optional[np.array] = None
+
+
+class WatermarkDetector:
+ r"""
+ Detector for detection of watermark generated text. The detector needs to be given the exact same settings that were
+ given during text generation to replicate the watermark greenlist generation and so detect the watermark. This includes
+ the correct device that was used during text generation, the correct watermarking arguments and the correct tokenizer vocab size.
+ The code was based on the [original repo](https://github.com/jwkirchenbauer/lm-watermarking/tree/main).
+
+ See [the paper](https://arxiv.org/abs/2306.04634) for more information.
+
+ Args:
+ model_config (`PretrainedConfig`):
+ The model config that will be used to get model specific arguments used when generating.
+ device (`str`):
+ The device which was used during watermarked text generation.
+ watermarking_config (Union[`WatermarkingConfig`, `Dict`]):
+ The exact same watermarking config and arguments used when generating text.
+ ignore_repeated_ngrams (`bool`, *optional*, defaults to `False`):
+ Whether to count every unique ngram only once or not.
+ max_cache_size (`int`, *optional*, defaults to 128):
+ The max size to be used for LRU caching of seeding/sampling algorithms called for every token.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM, WatermarkDetector, WatermarkingConfig
+
+ >>> model_id = "openai-community/gpt2"
+ >>> model = AutoModelForCausalLM.from_pretrained(model_id)
+ >>> tok = AutoTokenizer.from_pretrained(model_id)
+ >>> tok.pad_token_id = tok.eos_token_id
+ >>> tok.padding_side = "left"
+
+ >>> inputs = tok(["This is the beginning of a long story", "Alice and Bob are"], padding=True, return_tensors="pt")
+ >>> input_len = inputs["input_ids"].shape[-1]
+
+ >>> # first generate text with watermark and without
+ >>> watermarking_config = WatermarkingConfig(bias=2.5, seeding_scheme="selfhash")
+ >>> out_watermarked = model.generate(**inputs, watermarking_config=watermarking_config, do_sample=False, max_length=20)
+ >>> out = model.generate(**inputs, do_sample=False, max_length=20)
+
+ >>> # now we can instantiate the detector and check the generated text
+ >>> detector = WatermarkDetector(model_config=model.config, device="cpu", watermarking_config=watermarking_config)
+ >>> detection_out_watermarked = detector(out_watermarked, return_dict=True)
+ >>> detection_out = detector(out, return_dict=True)
+ >>> detection_out_watermarked.prediction
+ array([ True, True])
+
+ >>> detection_out.prediction
+ array([False, False])
+ ```
+ """
+
+ def __init__(
+ self,
+ model_config: PretrainedConfig,
+ device: str,
+ watermarking_config: Union[WatermarkingConfig, Dict],
+ ignore_repeated_ngrams: bool = False,
+ max_cache_size: int = 128,
+ ):
+ if isinstance(watermarking_config, WatermarkingConfig):
+ watermarking_config = watermarking_config.to_dict()
+
+ self.bos_token_id = (
+ model_config.bos_token_id if not model_config.is_encoder_decoder else model_config.decoder_start_token_id
+ )
+ self.greenlist_ratio = watermarking_config["greenlist_ratio"]
+ self.ignore_repeated_ngrams = ignore_repeated_ngrams
+ self.processor = WatermarkLogitsProcessor(
+ vocab_size=model_config.vocab_size, device=device, **watermarking_config
+ )
+
+ # Expensive re-seeding and sampling is cached.
+ self._get_ngram_score_cached = lru_cache(maxsize=max_cache_size)(self._get_ngram_score)
+
+ def _get_ngram_score(self, prefix: torch.LongTensor, target: int):
+ greenlist_ids = self.processor._get_greenlist_ids(prefix)
+ return target in greenlist_ids
+
+ def _score_ngrams_in_passage(self, input_ids: torch.LongTensor):
+ batch_size, seq_length = input_ids.shape
+ selfhash = int(self.processor.seeding_scheme == "selfhash")
+ n = self.processor.context_width + 1 - selfhash
+ indices = torch.arange(n).unsqueeze(0) + torch.arange(seq_length - n + 1).unsqueeze(1)
+ ngram_tensors = input_ids[:, indices]
+
+ num_tokens_scored_batch = np.zeros(batch_size)
+ green_token_count_batch = np.zeros(batch_size)
+ for batch_idx in range(ngram_tensors.shape[0]):
+ frequencies_table = collections.Counter(ngram_tensors[batch_idx])
+ ngram_to_watermark_lookup = {}
+ for ngram_example in frequencies_table.keys():
+ prefix = ngram_example if selfhash else ngram_example[:-1]
+ target = ngram_example[-1]
+ ngram_to_watermark_lookup[ngram_example] = self._get_ngram_score_cached(prefix, target)
+
+ if self.ignore_repeated_ngrams:
+ # counts a green/red hit once per unique ngram.
+ # num total tokens scored becomes the number unique ngrams.
+ num_tokens_scored_batch[batch_idx] = len(frequencies_table.keys())
+ green_token_count_batch[batch_idx] = sum(ngram_to_watermark_lookup.values())
+ else:
+ num_tokens_scored_batch[batch_idx] = sum(frequencies_table.values())
+ green_token_count_batch[batch_idx] = sum(
+ freq * outcome
+ for freq, outcome in zip(frequencies_table.values(), ngram_to_watermark_lookup.values())
+ )
+ return num_tokens_scored_batch, green_token_count_batch
+
+ def _compute_z_score(self, green_token_count: np.array, total_num_tokens: np.array) -> np.array:
+ expected_count = self.greenlist_ratio
+ numer = green_token_count - expected_count * total_num_tokens
+ denom = np.sqrt(total_num_tokens * expected_count * (1 - expected_count))
+ z = numer / denom
+ return z
+
+ def _compute_pval(self, x, loc=0, scale=1):
+ z = (x - loc) / scale
+ return 1 - (0.5 * (1 + np.sign(z) * (1 - np.exp(-2 * z**2 / np.pi))))
+
+ def __call__(
+ self,
+ input_ids: torch.LongTensor,
+ z_threshold: float = 3.0,
+ return_dict: bool = False,
+ ) -> Union[WatermarkDetectorOutput, np.array]:
+ """
+ Args:
+ input_ids (`torch.LongTensor`):
+ The watermark generated text. It is advised to remove the prompt, which can affect the detection.
+ z_threshold (`Dict`, *optional*, defaults to `3.0`):
+ Changing this threshold will change the sensitivity of the detector. Higher z threshold gives less
+ sensitivity and vice versa for lower z threshold.
+ return_dict (`bool`, *optional*, defaults to `False`):
+ Whether to return `~generation.WatermarkDetectorOutput` or not. If not it will return boolean predictions,
+ ma
+ Return:
+ [`~generation.WatermarkDetectorOutput`] or `np.array`: A [`~generation.WatermarkDetectorOutput`]
+ if `return_dict=True` otherwise a `np.array`.
+
+ """
+
+ # Let's assume that if one batch start with `bos`, all batched also do
+ if input_ids[0, 0] == self.bos_token_id:
+ input_ids = input_ids[:, 1:]
+
+ if input_ids.shape[-1] - self.processor.context_width < 1:
+ raise ValueError(
+ f"Must have at least `1` token to score after the first "
+ f"min_prefix_len={self.processor.context_width} tokens required by the seeding scheme."
+ )
+
+ num_tokens_scored, green_token_count = self._score_ngrams_in_passage(input_ids)
+ z_score = self._compute_z_score(green_token_count, num_tokens_scored)
+ prediction = z_score > z_threshold
+
+ if return_dict:
+ p_value = self._compute_pval(z_score)
+ confidence = 1 - p_value
+
+ return WatermarkDetectorOutput(
+ num_tokens_scored=num_tokens_scored,
+ num_green_tokens=green_token_count,
+ green_fraction=green_token_count / num_tokens_scored,
+ z_score=z_score,
+ p_value=p_value,
+ prediction=prediction,
+ confidence=confidence,
+ )
+ return prediction
+
+
+class BayesianDetectorConfig(PretrainedConfig):
+ """
+ This is the configuration class to store the configuration of a [`BayesianDetectorModel`]. It is used to
+ instantiate a Bayesian Detector model according to the specified arguments.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Args:
+ watermarking_depth (`int`, *optional*):
+ The number of tournament layers.
+ base_rate (`float1`, *optional*, defaults to 0.5):
+ Prior probability P(w) that a text is watermarked.
+ """
+
+ def __init__(self, watermarking_depth: int = None, base_rate: float = 0.5, **kwargs):
+ self.watermarking_depth = watermarking_depth
+ self.base_rate = base_rate
+ # These can be set later to store information about this detector.
+ self.model_name = None
+ self.watermarking_config = None
+
+ super().__init__(**kwargs)
+
+ def set_detector_information(self, model_name, watermarking_config):
+ self.model_name = model_name
+ self.watermarking_config = watermarking_config
+
+
+@dataclass
+class BayesianWatermarkDetectorModelOutput(ModelOutput):
+ """
+ Base class for outputs of models predicting if the text is watermarked.
+
+ Args:
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss.
+ posterior_probabilities (`torch.FloatTensor` of shape `(1,)`):
+ Multiple choice classification loss.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ posterior_probabilities: Optional[torch.FloatTensor] = None
+
+
+class BayesianDetectorWatermarkedLikelihood(nn.Module):
+ """Watermarked likelihood model for binary-valued g-values.
+
+ This takes in g-values and returns p(g_values|watermarked).
+ """
+
+ def __init__(self, watermarking_depth: int):
+ """Initializes the model parameters."""
+ super().__init__()
+ self.watermarking_depth = watermarking_depth
+ self.beta = torch.nn.Parameter(-2.5 + 0.001 * torch.randn(1, 1, watermarking_depth))
+ self.delta = torch.nn.Parameter(0.001 * torch.randn(1, 1, self.watermarking_depth, watermarking_depth))
+
+ def _compute_latents(self, g_values: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Computes the unique token probability distribution given g-values.
+
+ Args:
+ g_values (`torch.Tensor` of shape `(batch_size, seq_len, watermarking_depth)`):
+ PRF values.
+
+ Returns:
+ p_one_unique_token and p_two_unique_tokens, both of shape
+ [batch_size, seq_len, watermarking_depth]. p_one_unique_token[i,t,l]
+ gives the probability of there being one unique token in a tournament
+ match on layer l, on timestep t, for batch item i.
+ p_one_unique_token[i,t,l] + p_two_unique_token[i,t,l] = 1.
+ """
+ # Tile g-values to produce feature vectors for predicting the latents
+ # for each layer in the tournament; our model for the latents psi is a
+ # logistic regression model psi = sigmoid(delta * x + beta).
+
+ # [batch_size, seq_len, watermarking_depth, watermarking_depth]
+ x = torch.repeat_interleave(torch.unsqueeze(g_values, dim=-2), self.watermarking_depth, axis=-2)
+
+ # mask all elements above -1 diagonal for autoregressive factorization
+ x = torch.tril(x, diagonal=-1)
+
+ # [batch_size, seq_len, watermarking_depth]
+ # (i, j, k, l) x (i, j, k, l) -> (i, j, k) einsum equivalent
+ logits = (self.delta[..., None, :] @ x.type(self.delta.dtype)[..., None]).squeeze() + self.beta
+
+ p_two_unique_tokens = torch.sigmoid(logits)
+ p_one_unique_token = 1 - p_two_unique_tokens
+ return p_one_unique_token, p_two_unique_tokens
+
+ def forward(self, g_values: torch.Tensor) -> torch.Tensor:
+ """Computes the likelihoods P(g_values|watermarked).
+
+ Args:
+ g_values (`torch.Tensor` of shape `(batch_size, seq_len, watermarking_depth)`):
+ g-values (values 0 or 1)
+
+ Returns:
+ p(g_values|watermarked) of shape [batch_size, seq_len, watermarking_depth].
+ """
+ p_one_unique_token, p_two_unique_tokens = self._compute_latents(g_values)
+
+ # P(g_tl | watermarked) is equal to
+ # 0.5 * [ (g_tl+0.5) * p_two_unique_tokens + p_one_unique_token].
+ return 0.5 * ((g_values + 0.5) * p_two_unique_tokens + p_one_unique_token)
+
+
+class BayesianDetectorModel(PreTrainedModel):
+ r"""
+ Bayesian classifier for watermark detection.
+
+ This detector uses Bayes' rule to compute a watermarking score, which is the sigmoid of the log of ratio of the
+ posterior probabilities P(watermarked|g_values) and P(unwatermarked|g_values). Please see the section on
+ BayesianScore in the paper for further details.
+ Paper URL: https://www.nature.com/articles/s41586-024-08025-4
+
+ Note that this detector only works with non-distortionary Tournament-based watermarking using the Bernoulli(0.5)
+ g-value distribution.
+
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
+ and behavior.
+
+ Parameters:
+ config ([`BayesianDetectorConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+ """
+
+ config_class = BayesianDetectorConfig
+ base_model_prefix = "model"
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.watermarking_depth = config.watermarking_depth
+ self.base_rate = config.base_rate
+ self.likelihood_model_watermarked = BayesianDetectorWatermarkedLikelihood(
+ watermarking_depth=self.watermarking_depth
+ )
+ self.prior = torch.nn.Parameter(torch.tensor([self.base_rate]))
+
+ def _init_weights(self, module):
+ """Initialize the weights."""
+ if isinstance(module, nn.Parameter):
+ module.weight.data.normal_(mean=0.0, std=0.02)
+
+ def _compute_posterior(
+ self,
+ likelihoods_watermarked: torch.Tensor,
+ likelihoods_unwatermarked: torch.Tensor,
+ mask: torch.Tensor,
+ prior: float,
+ ) -> torch.Tensor:
+ """
+ Compute posterior P(w|g) given likelihoods, mask and prior.
+
+ Args:
+ likelihoods_watermarked (`torch.Tensor` of shape `(batch, length, depth)`):
+ Likelihoods P(g_values|watermarked) of g-values under watermarked model.
+ likelihoods_unwatermarked (`torch.Tensor` of shape `(batch, length, depth)`):
+ Likelihoods P(g_values|unwatermarked) of g-values under unwatermarked model.
+ mask (`torch.Tensor` of shape `(batch, length)`):
+ A binary array indicating which g-values should be used. g-values with mask value 0 are discarded.
+ prior (`float`):
+ the prior probability P(w) that the text is watermarked.
+
+ Returns:
+ Posterior probability P(watermarked|g_values), shape [batch].
+ """
+ mask = torch.unsqueeze(mask, dim=-1)
+ prior = torch.clamp(prior, min=1e-5, max=1 - 1e-5)
+ log_likelihoods_watermarked = torch.log(torch.clamp(likelihoods_watermarked, min=1e-30, max=float("inf")))
+ log_likelihoods_unwatermarked = torch.log(torch.clamp(likelihoods_unwatermarked, min=1e-30, max=float("inf")))
+ log_odds = log_likelihoods_watermarked - log_likelihoods_unwatermarked
+
+ # Sum relative surprisals (log odds) across all token positions and layers.
+ relative_surprisal_likelihood = torch.einsum("i...->i", log_odds * mask)
+
+ # Compute the relative surprisal prior
+ relative_surprisal_prior = torch.log(prior) - torch.log(1 - prior)
+
+ # Combine prior and likelihood.
+ # [batch_size]
+ relative_surprisal = relative_surprisal_prior + relative_surprisal_likelihood
+
+ # Compute the posterior probability P(w|g) = sigmoid(relative_surprisal).
+ return torch.sigmoid(relative_surprisal)
+
+ def forward(
+ self,
+ g_values: torch.Tensor,
+ mask: torch.Tensor,
+ labels: Optional[torch.Tensor] = None,
+ loss_batch_weight=1,
+ return_dict=False,
+ ) -> BayesianWatermarkDetectorModelOutput:
+ """
+ Computes the watermarked posterior P(watermarked|g_values).
+
+ Args:
+ g_values (`torch.Tensor` of shape `(batch_size, seq_len, watermarking_depth, ...)`):
+ g-values (with values 0 or 1)
+ mask:
+ A binary array shape [batch_size, seq_len] indicating which g-values should be used. g-values with mask
+ value 0 are discarded.
+
+ Returns:
+ p(watermarked | g_values), of shape [batch_size].
+ """
+
+ likelihoods_watermarked = self.likelihood_model_watermarked(g_values)
+ likelihoods_unwatermarked = 0.5 * torch.ones_like(g_values)
+ out = self._compute_posterior(
+ likelihoods_watermarked=likelihoods_watermarked,
+ likelihoods_unwatermarked=likelihoods_unwatermarked,
+ mask=mask,
+ prior=self.prior,
+ )
+
+ loss = None
+ if labels is not None:
+ loss_fct = BCELoss()
+ loss_unwweight = torch.sum(self.likelihood_model_watermarked.delta**2)
+ loss_weight = loss_unwweight * loss_batch_weight
+ loss = loss_fct(torch.clamp(out, 1e-5, 1 - 1e-5), labels) + loss_weight
+
+ if not return_dict:
+ return (out,) if loss is None else (out, loss)
+
+ return BayesianWatermarkDetectorModelOutput(loss=loss, posterior_probabilities=out)
+
+
+class SynthIDTextWatermarkDetector:
+ r"""
+ SynthID text watermark detector class.
+
+ This class has to be initialized with the trained bayesian detector module check script
+ in examples/synthid_text/detector_training.py for example in training/saving/loading this
+ detector module. The folder also showcases example use case of this detector.
+
+ Parameters:
+ detector_module ([`BayesianDetectorModel`]):
+ Bayesian detector module object initialized with parameters.
+ Check https://github.com/huggingface/transformers-research-projects/tree/main/synthid_text for usage.
+ logits_processor (`SynthIDTextWatermarkLogitsProcessor`):
+ The logits processor used for watermarking.
+ tokenizer (`Any`):
+ The tokenizer used for the model.
+
+ Examples:
+ ```python
+ >>> from transformers import (
+ ... AutoTokenizer, BayesianDetectorModel, SynthIDTextWatermarkLogitsProcessor, SynthIDTextWatermarkDetector
+ ... )
+
+ >>> # Load the detector. See https://github.com/huggingface/transformers-research-projects/tree/main/synthid_text for training a detector.
+ >>> detector_model = BayesianDetectorModel.from_pretrained("joaogante/dummy_synthid_detector")
+ >>> logits_processor = SynthIDTextWatermarkLogitsProcessor(
+ ... **detector_model.config.watermarking_config, device="cpu"
+ ... )
+ >>> tokenizer = AutoTokenizer.from_pretrained(detector_model.config.model_name)
+ >>> detector = SynthIDTextWatermarkDetector(detector_model, logits_processor, tokenizer)
+
+ >>> # Test whether a certain string is watermarked
+ >>> test_input = tokenizer(["This is a test input"], return_tensors="pt")
+ >>> is_watermarked = detector(test_input.input_ids)
+ ```
+ """
+
+ def __init__(
+ self,
+ detector_module: BayesianDetectorModel,
+ logits_processor: SynthIDTextWatermarkLogitsProcessor,
+ tokenizer: Any,
+ ):
+ self.detector_module = detector_module
+ self.logits_processor = logits_processor
+ self.tokenizer = tokenizer
+
+ def __call__(self, tokenized_outputs: torch.Tensor):
+ # eos mask is computed, skip first ngram_len - 1 tokens
+ # eos_mask will be of shape [batch_size, output_len]
+ eos_token_mask = self.logits_processor.compute_eos_token_mask(
+ input_ids=tokenized_outputs,
+ eos_token_id=self.tokenizer.eos_token_id,
+ )[:, self.logits_processor.ngram_len - 1 :]
+
+ # context repetition mask is computed
+ context_repetition_mask = self.logits_processor.compute_context_repetition_mask(
+ input_ids=tokenized_outputs,
+ )
+ # context repitition mask shape [batch_size, output_len - (ngram_len - 1)]
+
+ combined_mask = context_repetition_mask * eos_token_mask
+
+ g_values = self.logits_processor.compute_g_values(
+ input_ids=tokenized_outputs,
+ )
+ # g values shape [batch_size, output_len - (ngram_len - 1), depth]
+ return self.detector_module(g_values, combined_mask)
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/hf_argparser.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/hf_argparser.py
new file mode 100644
index 0000000000000000000000000000000000000000..627869551d482ec0f3b53e1dc7d8b61626ae87db
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/hf_argparser.py
@@ -0,0 +1,442 @@
+# 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 json
+import os
+import sys
+import types
+from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
+from copy import copy
+from enum import Enum
+from inspect import isclass
+from pathlib import Path
+from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints
+
+import yaml
+
+
+DataClass = NewType("DataClass", Any)
+DataClassType = NewType("DataClassType", Any)
+
+
+# From https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse
+def string_to_bool(v):
+ if isinstance(v, bool):
+ return v
+ if v.lower() in ("yes", "true", "t", "y", "1"):
+ return True
+ elif v.lower() in ("no", "false", "f", "n", "0"):
+ return False
+ else:
+ raise ArgumentTypeError(
+ f"Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive)."
+ )
+
+
+def make_choice_type_function(choices: list) -> Callable[[str], Any]:
+ """
+ Creates a mapping function from each choices string representation to the actual value. Used to support multiple
+ value types for a single argument.
+
+ Args:
+ choices (list): List of choices.
+
+ Returns:
+ Callable[[str], Any]: Mapping function from string representation to actual value for each choice.
+ """
+ str_to_choice = {str(choice): choice for choice in choices}
+ return lambda arg: str_to_choice.get(arg, arg)
+
+
+def HfArg(
+ *,
+ aliases: Union[str, List[str]] = None,
+ help: str = None,
+ default: Any = dataclasses.MISSING,
+ default_factory: Callable[[], Any] = dataclasses.MISSING,
+ metadata: dict = None,
+ **kwargs,
+) -> dataclasses.Field:
+ """Argument helper enabling a concise syntax to create dataclass fields for parsing with `HfArgumentParser`.
+
+ Example comparing the use of `HfArg` and `dataclasses.field`:
+ ```
+ @dataclass
+ class Args:
+ regular_arg: str = dataclasses.field(default="Huggingface", metadata={"aliases": ["--example", "-e"], "help": "This syntax could be better!"})
+ hf_arg: str = HfArg(default="Huggingface", aliases=["--example", "-e"], help="What a nice syntax!")
+ ```
+
+ Args:
+ aliases (Union[str, List[str]], optional):
+ Single string or list of strings of aliases to pass on to argparse, e.g. `aliases=["--example", "-e"]`.
+ Defaults to None.
+ help (str, optional): Help string to pass on to argparse that can be displayed with --help. Defaults to None.
+ default (Any, optional):
+ Default value for the argument. If not default or default_factory is specified, the argument is required.
+ Defaults to dataclasses.MISSING.
+ default_factory (Callable[[], Any], optional):
+ The default_factory is a 0-argument function called to initialize a field's value. It is useful to provide
+ default values for mutable types, e.g. lists: `default_factory=list`. Mutually exclusive with `default=`.
+ Defaults to dataclasses.MISSING.
+ metadata (dict, optional): Further metadata to pass on to `dataclasses.field`. Defaults to None.
+
+ Returns:
+ Field: A `dataclasses.Field` with the desired properties.
+ """
+ if metadata is None:
+ # Important, don't use as default param in function signature because dict is mutable and shared across function calls
+ metadata = {}
+ if aliases is not None:
+ metadata["aliases"] = aliases
+ if help is not None:
+ metadata["help"] = help
+
+ return dataclasses.field(metadata=metadata, default=default, default_factory=default_factory, **kwargs)
+
+
+class HfArgumentParser(ArgumentParser):
+ """
+ This subclass of `argparse.ArgumentParser` uses type hints on dataclasses to generate arguments.
+
+ The class is designed to play well with the native argparse. In particular, you can add more (non-dataclass backed)
+ arguments to the parser after initialization and you'll get the output back after parsing as an additional
+ namespace. Optional: To create sub argument groups use the `_argument_group_name` attribute in the dataclass.
+
+ Args:
+ dataclass_types (`DataClassType` or `Iterable[DataClassType]`, *optional*):
+ Dataclass type, or list of dataclass types for which we will "fill" instances with the parsed args.
+ kwargs (`Dict[str, Any]`, *optional*):
+ Passed to `argparse.ArgumentParser()` in the regular way.
+ """
+
+ dataclass_types: Iterable[DataClassType]
+
+ def __init__(self, dataclass_types: Optional[Union[DataClassType, Iterable[DataClassType]]] = None, **kwargs):
+ # Make sure dataclass_types is an iterable
+ if dataclass_types is None:
+ dataclass_types = []
+ elif not isinstance(dataclass_types, Iterable):
+ dataclass_types = [dataclass_types]
+
+ # To make the default appear when using --help
+ if "formatter_class" not in kwargs:
+ kwargs["formatter_class"] = ArgumentDefaultsHelpFormatter
+ super().__init__(**kwargs)
+ if dataclasses.is_dataclass(dataclass_types):
+ dataclass_types = [dataclass_types]
+ self.dataclass_types = list(dataclass_types)
+ for dtype in self.dataclass_types:
+ self._add_dataclass_arguments(dtype)
+
+ @staticmethod
+ def _parse_dataclass_field(parser: ArgumentParser, field: dataclasses.Field):
+ # Long-option strings are conventionlly separated by hyphens rather
+ # than underscores, e.g., "--long-format" rather than "--long_format".
+ # Argparse converts hyphens to underscores so that the destination
+ # string is a valid attribute name. Hf_argparser should do the same.
+ long_options = [f"--{field.name}"]
+ if "_" in field.name:
+ long_options.append(f"--{field.name.replace('_', '-')}")
+
+ kwargs = field.metadata.copy()
+ # field.metadata is not used at all by Data Classes,
+ # it is provided as a third-party extension mechanism.
+ if isinstance(field.type, str):
+ raise RuntimeError(
+ "Unresolved type detected, which should have been done with the help of "
+ "`typing.get_type_hints` method by default"
+ )
+
+ aliases = kwargs.pop("aliases", [])
+ if isinstance(aliases, str):
+ aliases = [aliases]
+
+ origin_type = getattr(field.type, "__origin__", field.type)
+ if origin_type is Union or (hasattr(types, "UnionType") and isinstance(origin_type, types.UnionType)):
+ if str not in field.type.__args__ and (
+ len(field.type.__args__) != 2 or type(None) not in field.type.__args__
+ ):
+ raise ValueError(
+ "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because"
+ " the argument parser only supports one type per argument."
+ f" Problem encountered in field '{field.name}'."
+ )
+ if type(None) not in field.type.__args__:
+ # filter `str` in Union
+ field.type = field.type.__args__[0] if field.type.__args__[1] is str else field.type.__args__[1]
+ origin_type = getattr(field.type, "__origin__", field.type)
+ elif bool not in field.type.__args__:
+ # filter `NoneType` in Union (except for `Union[bool, NoneType]`)
+ field.type = (
+ field.type.__args__[0] if isinstance(None, field.type.__args__[1]) else field.type.__args__[1]
+ )
+ origin_type = getattr(field.type, "__origin__", field.type)
+
+ # A variable to store kwargs for a boolean field, if needed
+ # so that we can init a `no_*` complement argument (see below)
+ bool_kwargs = {}
+ if origin_type is Literal or (isinstance(field.type, type) and issubclass(field.type, Enum)):
+ if origin_type is Literal:
+ kwargs["choices"] = field.type.__args__
+ else:
+ kwargs["choices"] = [x.value for x in field.type]
+
+ kwargs["type"] = make_choice_type_function(kwargs["choices"])
+
+ if field.default is not dataclasses.MISSING:
+ kwargs["default"] = field.default
+ else:
+ kwargs["required"] = True
+ elif field.type is bool or field.type == Optional[bool]:
+ # Copy the correct kwargs to use to instantiate a `no_*` complement argument below.
+ # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument
+ bool_kwargs = copy(kwargs)
+
+ # Hack because type=bool in argparse does not behave as we want.
+ kwargs["type"] = string_to_bool
+ if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
+ # Default value is False if we have no default when of type bool.
+ default = False if field.default is dataclasses.MISSING else field.default
+ # This is the value that will get picked if we don't include --{field.name} in any way
+ kwargs["default"] = default
+ # This tells argparse we accept 0 or 1 value after --{field.name}
+ kwargs["nargs"] = "?"
+ # This is the value that will get picked if we do --{field.name} (without value)
+ kwargs["const"] = True
+ elif isclass(origin_type) and issubclass(origin_type, list):
+ kwargs["type"] = field.type.__args__[0]
+ kwargs["nargs"] = "+"
+ if field.default_factory is not dataclasses.MISSING:
+ kwargs["default"] = field.default_factory()
+ elif field.default is dataclasses.MISSING:
+ kwargs["required"] = True
+ else:
+ kwargs["type"] = field.type
+ if field.default is not dataclasses.MISSING:
+ kwargs["default"] = field.default
+ elif field.default_factory is not dataclasses.MISSING:
+ kwargs["default"] = field.default_factory()
+ else:
+ kwargs["required"] = True
+ parser.add_argument(*long_options, *aliases, **kwargs)
+
+ # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
+ # Order is important for arguments with the same destination!
+ # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
+ # here and we do not need those changes/additional keys.
+ if field.default is True and (field.type is bool or field.type == Optional[bool]):
+ bool_kwargs["default"] = False
+ parser.add_argument(
+ f"--no_{field.name}",
+ f"--no-{field.name.replace('_', '-')}",
+ action="store_false",
+ dest=field.name,
+ **bool_kwargs,
+ )
+
+ def _add_dataclass_arguments(self, dtype: DataClassType):
+ if hasattr(dtype, "_argument_group_name"):
+ parser = self.add_argument_group(dtype._argument_group_name)
+ else:
+ parser = self
+
+ try:
+ type_hints: Dict[str, type] = get_type_hints(dtype)
+ except NameError:
+ raise RuntimeError(
+ f"Type resolution failed for {dtype}. Try declaring the class in global scope or "
+ "removing line of `from __future__ import annotations` which opts in Postponed "
+ "Evaluation of Annotations (PEP 563)"
+ )
+ except TypeError as ex:
+ # Remove this block when we drop Python 3.9 support
+ if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(ex):
+ python_version = ".".join(map(str, sys.version_info[:3]))
+ raise RuntimeError(
+ f"Type resolution failed for {dtype} on Python {python_version}. Try removing "
+ "line of `from __future__ import annotations` which opts in union types as "
+ "`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To "
+ "support Python versions that lower than 3.10, you need to use "
+ "`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of "
+ "`X | None`."
+ ) from ex
+ raise
+
+ for field in dataclasses.fields(dtype):
+ if not field.init:
+ continue
+ field.type = type_hints[field.name]
+ self._parse_dataclass_field(parser, field)
+
+ def parse_args_into_dataclasses(
+ self,
+ args=None,
+ return_remaining_strings=False,
+ look_for_args_file=True,
+ args_filename=None,
+ args_file_flag=None,
+ ) -> Tuple[DataClass, ...]:
+ """
+ Parse command-line args into instances of the specified dataclass types.
+
+ This relies on argparse's `ArgumentParser.parse_known_args`. See the doc at:
+ docs.python.org/3.7/library/argparse.html#argparse.ArgumentParser.parse_args
+
+ Args:
+ args:
+ List of strings to parse. The default is taken from sys.argv. (same as argparse.ArgumentParser)
+ return_remaining_strings:
+ If true, also return a list of remaining argument strings.
+ look_for_args_file:
+ If true, will look for a ".args" file with the same base name as the entry point script for this
+ process, and will append its potential content to the command line args.
+ args_filename:
+ If not None, will uses this file instead of the ".args" file specified in the previous argument.
+ args_file_flag:
+ If not None, will look for a file in the command-line args specified with this flag. The flag can be
+ specified multiple times and precedence is determined by the order (last one wins).
+
+ Returns:
+ Tuple consisting of:
+
+ - the dataclass instances in the same order as they were passed to the initializer.abspath
+ - if applicable, an additional namespace for more (non-dataclass backed) arguments added to the parser
+ after initialization.
+ - The potential list of remaining argument strings. (same as argparse.ArgumentParser.parse_known_args)
+ """
+
+ if args_file_flag or args_filename or (look_for_args_file and len(sys.argv)):
+ args_files = []
+
+ if args_filename:
+ args_files.append(Path(args_filename))
+ elif look_for_args_file and len(sys.argv):
+ args_files.append(Path(sys.argv[0]).with_suffix(".args"))
+
+ # args files specified via command line flag should overwrite default args files so we add them last
+ if args_file_flag:
+ # Create special parser just to extract the args_file_flag values
+ args_file_parser = ArgumentParser()
+ args_file_parser.add_argument(args_file_flag, type=str, action="append")
+
+ # Use only remaining args for further parsing (remove the args_file_flag)
+ cfg, args = args_file_parser.parse_known_args(args=args)
+ cmd_args_file_paths = vars(cfg).get(args_file_flag.lstrip("-"), None)
+
+ if cmd_args_file_paths:
+ args_files.extend([Path(p) for p in cmd_args_file_paths])
+
+ file_args = []
+ for args_file in args_files:
+ if args_file.exists():
+ file_args += args_file.read_text().split()
+
+ # in case of duplicate arguments the last one has precedence
+ # args specified via the command line should overwrite args from files, so we add them last
+ args = file_args + args if args is not None else file_args + sys.argv[1:]
+ namespace, remaining_args = self.parse_known_args(args=args)
+ outputs = []
+ for dtype in self.dataclass_types:
+ keys = {f.name for f in dataclasses.fields(dtype) if f.init}
+ inputs = {k: v for k, v in vars(namespace).items() if k in keys}
+ for k in keys:
+ delattr(namespace, k)
+ obj = dtype(**inputs)
+ outputs.append(obj)
+ if len(namespace.__dict__) > 0:
+ # additional namespace.
+ outputs.append(namespace)
+ if return_remaining_strings:
+ return (*outputs, remaining_args)
+ else:
+ if remaining_args:
+ raise ValueError(f"Some specified arguments are not used by the HfArgumentParser: {remaining_args}")
+
+ return (*outputs,)
+
+ def parse_dict(self, args: Dict[str, Any], allow_extra_keys: bool = False) -> Tuple[DataClass, ...]:
+ """
+ Alternative helper method that does not use `argparse` at all, instead uses a dict and populating the dataclass
+ types.
+
+ Args:
+ args (`dict`):
+ dict containing config values
+ allow_extra_keys (`bool`, *optional*, defaults to `False`):
+ Defaults to False. If False, will raise an exception if the dict contains keys that are not parsed.
+
+ Returns:
+ Tuple consisting of:
+
+ - the dataclass instances in the same order as they were passed to the initializer.
+ """
+ unused_keys = set(args.keys())
+ outputs = []
+ for dtype in self.dataclass_types:
+ keys = {f.name for f in dataclasses.fields(dtype) if f.init}
+ inputs = {k: v for k, v in args.items() if k in keys}
+ unused_keys.difference_update(inputs.keys())
+ obj = dtype(**inputs)
+ outputs.append(obj)
+ if not allow_extra_keys and unused_keys:
+ raise ValueError(f"Some keys are not used by the HfArgumentParser: {sorted(unused_keys)}")
+ return tuple(outputs)
+
+ def parse_json_file(
+ self, json_file: Union[str, os.PathLike], allow_extra_keys: bool = False
+ ) -> Tuple[DataClass, ...]:
+ """
+ Alternative helper method that does not use `argparse` at all, instead loading a json file and populating the
+ dataclass types.
+
+ Args:
+ json_file (`str` or `os.PathLike`):
+ File name of the json file to parse
+ allow_extra_keys (`bool`, *optional*, defaults to `False`):
+ Defaults to False. If False, will raise an exception if the json file contains keys that are not
+ parsed.
+
+ Returns:
+ Tuple consisting of:
+
+ - the dataclass instances in the same order as they were passed to the initializer.
+ """
+ with open(Path(json_file), encoding="utf-8") as open_json_file:
+ data = json.loads(open_json_file.read())
+ outputs = self.parse_dict(data, allow_extra_keys=allow_extra_keys)
+ return tuple(outputs)
+
+ def parse_yaml_file(
+ self, yaml_file: Union[str, os.PathLike], allow_extra_keys: bool = False
+ ) -> Tuple[DataClass, ...]:
+ """
+ Alternative helper method that does not use `argparse` at all, instead loading a yaml file and populating the
+ dataclass types.
+
+ Args:
+ yaml_file (`str` or `os.PathLike`):
+ File name of the yaml file to parse
+ allow_extra_keys (`bool`, *optional*, defaults to `False`):
+ Defaults to False. If False, will raise an exception if the json file contains keys that are not
+ parsed.
+
+ Returns:
+ Tuple consisting of:
+
+ - the dataclass instances in the same order as they were passed to the initializer.
+ """
+ outputs = self.parse_dict(yaml.safe_load(Path(yaml_file).read_text()), allow_extra_keys=allow_extra_keys)
+ return tuple(outputs)
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/hyperparameter_search.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/hyperparameter_search.py
new file mode 100644
index 0000000000000000000000000000000000000000..c14165165ca1f92fb28e27b718c8bd81e1bc3a93
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/hyperparameter_search.py
@@ -0,0 +1,141 @@
+# coding=utf-8
+# Copyright 2023-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.
+
+from .integrations import (
+ is_optuna_available,
+ is_ray_tune_available,
+ is_sigopt_available,
+ is_wandb_available,
+ run_hp_search_optuna,
+ run_hp_search_ray,
+ run_hp_search_sigopt,
+ run_hp_search_wandb,
+)
+from .trainer_utils import (
+ HPSearchBackend,
+ default_hp_space_optuna,
+ default_hp_space_ray,
+ default_hp_space_sigopt,
+ default_hp_space_wandb,
+)
+from .utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class HyperParamSearchBackendBase:
+ name: str
+ pip_package: str = None
+
+ @staticmethod
+ def is_available():
+ raise NotImplementedError
+
+ def run(self, trainer, n_trials: int, direction: str, **kwargs):
+ raise NotImplementedError
+
+ def default_hp_space(self, trial):
+ raise NotImplementedError
+
+ def ensure_available(self):
+ if not self.is_available():
+ raise RuntimeError(
+ f"You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}."
+ )
+
+ @classmethod
+ def pip_install(cls):
+ return f"`pip install {cls.pip_package or cls.name}`"
+
+
+class OptunaBackend(HyperParamSearchBackendBase):
+ name = "optuna"
+
+ @staticmethod
+ def is_available():
+ return is_optuna_available()
+
+ def run(self, trainer, n_trials: int, direction: str, **kwargs):
+ return run_hp_search_optuna(trainer, n_trials, direction, **kwargs)
+
+ def default_hp_space(self, trial):
+ return default_hp_space_optuna(trial)
+
+
+class RayTuneBackend(HyperParamSearchBackendBase):
+ name = "ray"
+ pip_package = "'ray[tune]'"
+
+ @staticmethod
+ def is_available():
+ return is_ray_tune_available()
+
+ def run(self, trainer, n_trials: int, direction: str, **kwargs):
+ return run_hp_search_ray(trainer, n_trials, direction, **kwargs)
+
+ def default_hp_space(self, trial):
+ return default_hp_space_ray(trial)
+
+
+class SigOptBackend(HyperParamSearchBackendBase):
+ name = "sigopt"
+
+ @staticmethod
+ def is_available():
+ return is_sigopt_available()
+
+ def run(self, trainer, n_trials: int, direction: str, **kwargs):
+ return run_hp_search_sigopt(trainer, n_trials, direction, **kwargs)
+
+ def default_hp_space(self, trial):
+ return default_hp_space_sigopt(trial)
+
+
+class WandbBackend(HyperParamSearchBackendBase):
+ name = "wandb"
+
+ @staticmethod
+ def is_available():
+ return is_wandb_available()
+
+ def run(self, trainer, n_trials: int, direction: str, **kwargs):
+ return run_hp_search_wandb(trainer, n_trials, direction, **kwargs)
+
+ def default_hp_space(self, trial):
+ return default_hp_space_wandb(trial)
+
+
+ALL_HYPERPARAMETER_SEARCH_BACKENDS = {
+ HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend]
+}
+
+
+def default_hp_search_backend() -> str:
+ available_backends = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()]
+ if len(available_backends) > 0:
+ name = available_backends[0].name
+ if len(available_backends) > 1:
+ logger.info(
+ f"{len(available_backends)} hyperparameter search backends available. Using {name} as the default."
+ )
+ return name
+ raise RuntimeError(
+ "No hyperparameter search backend available.\n"
+ + "\n".join(
+ f" - To install {backend.name} run {backend.pip_install()}"
+ for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values()
+ )
+ )
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/image_processing_base.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/image_processing_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6ce7af3fa8076958d4a4ac87ca3ab13716c7955
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/image_processing_base.py
@@ -0,0 +1,559 @@
+# coding=utf-8
+# Copyright 2020 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import copy
+import json
+import os
+import warnings
+from io import BytesIO
+from typing import Any, Dict, List, Optional, Tuple, Type, TypeVar, Union
+
+import numpy as np
+import requests
+
+from .dynamic_module_utils import custom_object_save
+from .feature_extraction_utils import BatchFeature as BaseBatchFeature
+from .utils import (
+ IMAGE_PROCESSOR_NAME,
+ PushToHubMixin,
+ add_model_info_to_auto_map,
+ add_model_info_to_custom_pipelines,
+ cached_file,
+ copy_func,
+ download_url,
+ is_offline_mode,
+ is_remote_url,
+ is_vision_available,
+ logging,
+)
+
+
+if is_vision_available():
+ from PIL import Image
+
+
+ImageProcessorType = TypeVar("ImageProcessorType", bound="ImageProcessingMixin")
+
+
+logger = logging.get_logger(__name__)
+
+
+# TODO: Move BatchFeature to be imported by both image_processing_utils and image_processing_utils
+# We override the class string here, but logic is the same.
+class BatchFeature(BaseBatchFeature):
+ r"""
+ Holds the output of the image processor specific `__call__` methods.
+
+ This class is derived from a python dictionary and can be used as a dictionary.
+
+ Args:
+ data (`dict`):
+ Dictionary of lists/arrays/tensors returned by the __call__ method ('pixel_values', etc.).
+ tensor_type (`Union[None, str, TensorType]`, *optional*):
+ You can give a tensor_type here to convert the lists of integers in PyTorch/TensorFlow/Numpy Tensors at
+ initialization.
+ """
+
+
+# TODO: (Amy) - factor out the common parts of this and the feature extractor
+class ImageProcessingMixin(PushToHubMixin):
+ """
+ This is an image processor mixin used to provide saving/loading functionality for sequential and image feature
+ extractors.
+ """
+
+ _auto_class = None
+
+ def __init__(self, **kwargs):
+ """Set elements of `kwargs` as attributes."""
+ # This key was saved while we still used `XXXFeatureExtractor` for image processing. Now we use
+ # `XXXImageProcessor`, this attribute and its value are misleading.
+ kwargs.pop("feature_extractor_type", None)
+ # Pop "processor_class" as it should be saved as private attribute
+ self._processor_class = kwargs.pop("processor_class", None)
+ # Additional attributes without default values
+ for key, value in kwargs.items():
+ try:
+ setattr(self, key, value)
+ except AttributeError as err:
+ logger.error(f"Can't set {key} with value {value} for {self}")
+ raise err
+
+ def _set_processor_class(self, processor_class: str):
+ """Sets processor class as an attribute."""
+ self._processor_class = processor_class
+
+ @classmethod
+ def from_pretrained(
+ cls: Type[ImageProcessorType],
+ pretrained_model_name_or_path: Union[str, os.PathLike],
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
+ force_download: bool = False,
+ local_files_only: bool = False,
+ token: Optional[Union[str, bool]] = None,
+ revision: str = "main",
+ **kwargs,
+ ) -> ImageProcessorType:
+ r"""
+ Instantiate a type of [`~image_processing_utils.ImageProcessingMixin`] from an image processor.
+
+ Args:
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
+ This can be either:
+
+ - a string, the *model id* of a pretrained image_processor hosted inside a model repo on
+ huggingface.co.
+ - a path to a *directory* containing a image processor file saved using the
+ [`~image_processing_utils.ImageProcessingMixin.save_pretrained`] method, e.g.,
+ `./my_model_directory/`.
+ - a path or url to a saved image processor JSON *file*, e.g.,
+ `./my_model_directory/preprocessor_config.json`.
+ cache_dir (`str` or `os.PathLike`, *optional*):
+ Path to a directory in which a downloaded pretrained model image processor should be cached if the
+ standard cache should not be used.
+ force_download (`bool`, *optional*, defaults to `False`):
+ Whether or not to force to (re-)download the image processor files and override the cached versions if
+ they exist.
+ resume_download:
+ Deprecated and ignored. All downloads are now resumed by default when possible.
+ Will be removed in v5 of Transformers.
+ proxies (`Dict[str, str]`, *optional*):
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
+ 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
+ token (`str` or `bool`, *optional*):
+ The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, 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/"`.
+
+
+
+ return_unused_kwargs (`bool`, *optional*, defaults to `False`):
+ If `False`, then this function returns just the final image processor object. If `True`, then this
+ functions returns a `Tuple(image_processor, unused_kwargs)` where *unused_kwargs* is a dictionary
+ consisting of the key/value pairs whose keys are not image processor attributes: i.e., the part of
+ `kwargs` which has not been used to update `image_processor` and is otherwise ignored.
+ 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.
+ kwargs (`Dict[str, Any]`, *optional*):
+ The values in kwargs of any keys which are image processor attributes will be used to override the
+ loaded values. Behavior concerning key/value pairs whose keys are *not* image processor attributes is
+ controlled by the `return_unused_kwargs` keyword parameter.
+
+ Returns:
+ A image processor of type [`~image_processing_utils.ImageProcessingMixin`].
+
+ Examples:
+
+ ```python
+ # We can't instantiate directly the base class *ImageProcessingMixin* so let's show the examples on a
+ # derived class: *CLIPImageProcessor*
+ image_processor = CLIPImageProcessor.from_pretrained(
+ "openai/clip-vit-base-patch32"
+ ) # Download image_processing_config from huggingface.co and cache.
+ image_processor = CLIPImageProcessor.from_pretrained(
+ "./test/saved_model/"
+ ) # E.g. image processor (or model) was saved using *save_pretrained('./test/saved_model/')*
+ image_processor = CLIPImageProcessor.from_pretrained("./test/saved_model/preprocessor_config.json")
+ image_processor = CLIPImageProcessor.from_pretrained(
+ "openai/clip-vit-base-patch32", do_normalize=False, foo=False
+ )
+ assert image_processor.do_normalize is False
+ image_processor, unused_kwargs = CLIPImageProcessor.from_pretrained(
+ "openai/clip-vit-base-patch32", do_normalize=False, foo=False, return_unused_kwargs=True
+ )
+ assert image_processor.do_normalize is False
+ assert unused_kwargs == {"foo": False}
+ ```"""
+ kwargs["cache_dir"] = cache_dir
+ kwargs["force_download"] = force_download
+ kwargs["local_files_only"] = local_files_only
+ kwargs["revision"] = revision
+
+ use_auth_token = kwargs.pop("use_auth_token", None)
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
+ FutureWarning,
+ )
+ if token is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ token = use_auth_token
+
+ if token is not None:
+ kwargs["token"] = token
+
+ image_processor_dict, kwargs = cls.get_image_processor_dict(pretrained_model_name_or_path, **kwargs)
+
+ return cls.from_dict(image_processor_dict, **kwargs)
+
+ def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
+ """
+ Save an image processor object to the directory `save_directory`, so that it can be re-loaded using the
+ [`~image_processing_utils.ImageProcessingMixin.from_pretrained`] class method.
+
+ Args:
+ save_directory (`str` or `os.PathLike`):
+ Directory where the image processor JSON file will be saved (will be created if it does not exist).
+ push_to_hub (`bool`, *optional*, defaults to `False`):
+ Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
+ repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
+ namespace).
+ kwargs (`Dict[str, Any]`, *optional*):
+ Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
+ """
+ use_auth_token = kwargs.pop("use_auth_token", None)
+
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
+ FutureWarning,
+ )
+ if kwargs.get("token", None) is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ kwargs["token"] = use_auth_token
+
+ if os.path.isfile(save_directory):
+ raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
+
+ os.makedirs(save_directory, exist_ok=True)
+
+ if push_to_hub:
+ commit_message = kwargs.pop("commit_message", None)
+ repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
+ repo_id = self._create_repo(repo_id, **kwargs)
+ files_timestamps = self._get_files_timestamps(save_directory)
+
+ # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
+ # loaded from the Hub.
+ if self._auto_class is not None:
+ custom_object_save(self, save_directory, config=self)
+
+ # If we save using the predefined names, we can load using `from_pretrained`
+ output_image_processor_file = os.path.join(save_directory, IMAGE_PROCESSOR_NAME)
+
+ self.to_json_file(output_image_processor_file)
+ logger.info(f"Image processor saved in {output_image_processor_file}")
+
+ if push_to_hub:
+ self._upload_modified_files(
+ save_directory,
+ repo_id,
+ files_timestamps,
+ commit_message=commit_message,
+ token=kwargs.get("token"),
+ )
+
+ return [output_image_processor_file]
+
+ @classmethod
+ def get_image_processor_dict(
+ cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
+ ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
+ """
+ From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a
+ image processor of type [`~image_processor_utils.ImageProcessingMixin`] using `from_dict`.
+
+ Parameters:
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
+ The identifier of the pre-trained checkpoint from which we want the dictionary of parameters.
+ 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.
+ image_processor_filename (`str`, *optional*, defaults to `"config.json"`):
+ The name of the file in the model directory to use for the image processor config.
+
+ Returns:
+ `Tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the image processor object.
+ """
+ cache_dir = kwargs.pop("cache_dir", None)
+ force_download = kwargs.pop("force_download", False)
+ resume_download = kwargs.pop("resume_download", None)
+ proxies = kwargs.pop("proxies", None)
+ token = kwargs.pop("token", None)
+ use_auth_token = kwargs.pop("use_auth_token", None)
+ local_files_only = kwargs.pop("local_files_only", False)
+ revision = kwargs.pop("revision", None)
+ subfolder = kwargs.pop("subfolder", "")
+ image_processor_filename = kwargs.pop("image_processor_filename", IMAGE_PROCESSOR_NAME)
+
+ from_pipeline = kwargs.pop("_from_pipeline", None)
+ from_auto_class = kwargs.pop("_from_auto", 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
+
+ user_agent = {"file_type": "image processor", "from_auto_class": from_auto_class}
+ if from_pipeline is not None:
+ user_agent["using_pipeline"] = from_pipeline
+
+ if is_offline_mode() and not local_files_only:
+ logger.info("Offline mode: forcing local_files_only=True")
+ local_files_only = True
+
+ pretrained_model_name_or_path = str(pretrained_model_name_or_path)
+ is_local = os.path.isdir(pretrained_model_name_or_path)
+ if os.path.isdir(pretrained_model_name_or_path):
+ image_processor_file = os.path.join(pretrained_model_name_or_path, image_processor_filename)
+ if os.path.isfile(pretrained_model_name_or_path):
+ resolved_image_processor_file = pretrained_model_name_or_path
+ is_local = True
+ elif is_remote_url(pretrained_model_name_or_path):
+ image_processor_file = pretrained_model_name_or_path
+ resolved_image_processor_file = download_url(pretrained_model_name_or_path)
+ else:
+ image_processor_file = image_processor_filename
+ try:
+ # Load from local folder or from cache or download from model Hub and cache
+ resolved_image_processor_file = cached_file(
+ pretrained_model_name_or_path,
+ image_processor_file,
+ 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,
+ )
+ except EnvironmentError:
+ # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to
+ # the original exception.
+ raise
+ except Exception:
+ # For any other exception, we throw a generic error.
+ raise EnvironmentError(
+ f"Can't load image processor for '{pretrained_model_name_or_path}'. If you were trying to load"
+ " it from 'https://huggingface.co/models', make sure you don't have a local directory with the"
+ f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a"
+ f" directory containing a {image_processor_filename} file"
+ )
+
+ try:
+ # Load image_processor dict
+ with open(resolved_image_processor_file, "r", encoding="utf-8") as reader:
+ text = reader.read()
+ image_processor_dict = json.loads(text)
+
+ except json.JSONDecodeError:
+ raise EnvironmentError(
+ f"It looks like the config file at '{resolved_image_processor_file}' is not a valid JSON file."
+ )
+
+ if is_local:
+ logger.info(f"loading configuration file {resolved_image_processor_file}")
+ else:
+ logger.info(
+ f"loading configuration file {image_processor_file} from cache at {resolved_image_processor_file}"
+ )
+ if "auto_map" in image_processor_dict:
+ image_processor_dict["auto_map"] = add_model_info_to_auto_map(
+ image_processor_dict["auto_map"], pretrained_model_name_or_path
+ )
+ if "custom_pipelines" in image_processor_dict:
+ image_processor_dict["custom_pipelines"] = add_model_info_to_custom_pipelines(
+ image_processor_dict["custom_pipelines"], pretrained_model_name_or_path
+ )
+
+ return image_processor_dict, kwargs
+
+ @classmethod
+ def from_dict(cls, image_processor_dict: Dict[str, Any], **kwargs):
+ """
+ Instantiates a type of [`~image_processing_utils.ImageProcessingMixin`] from a Python dictionary of parameters.
+
+ Args:
+ image_processor_dict (`Dict[str, Any]`):
+ Dictionary that will be used to instantiate the image processor object. Such a dictionary can be
+ retrieved from a pretrained checkpoint by leveraging the
+ [`~image_processing_utils.ImageProcessingMixin.to_dict`] method.
+ kwargs (`Dict[str, Any]`):
+ Additional parameters from which to initialize the image processor object.
+
+ Returns:
+ [`~image_processing_utils.ImageProcessingMixin`]: The image processor object instantiated from those
+ parameters.
+ """
+ image_processor_dict = image_processor_dict.copy()
+ return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
+
+ # The `size` parameter is a dict and was previously an int or tuple in feature extractors.
+ # We set `size` here directly to the `image_processor_dict` so that it is converted to the appropriate
+ # dict within the image processor and isn't overwritten if `size` is passed in as a kwarg.
+ if "size" in kwargs and "size" in image_processor_dict:
+ image_processor_dict["size"] = kwargs.pop("size")
+ if "crop_size" in kwargs and "crop_size" in image_processor_dict:
+ image_processor_dict["crop_size"] = kwargs.pop("crop_size")
+
+ image_processor = cls(**image_processor_dict)
+
+ # Update image_processor with kwargs if needed
+ to_remove = []
+ for key, value in kwargs.items():
+ if hasattr(image_processor, key):
+ setattr(image_processor, key, value)
+ to_remove.append(key)
+ for key in to_remove:
+ kwargs.pop(key, None)
+
+ logger.info(f"Image processor {image_processor}")
+ if return_unused_kwargs:
+ return image_processor, kwargs
+ else:
+ return image_processor
+
+ 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 image processor instance.
+ """
+ output = copy.deepcopy(self.__dict__)
+ output["image_processor_type"] = self.__class__.__name__
+
+ return output
+
+ @classmethod
+ def from_json_file(cls, json_file: Union[str, os.PathLike]):
+ """
+ Instantiates a image processor of type [`~image_processing_utils.ImageProcessingMixin`] from the path to a JSON
+ file of parameters.
+
+ Args:
+ json_file (`str` or `os.PathLike`):
+ Path to the JSON file containing the parameters.
+
+ Returns:
+ A image processor of type [`~image_processing_utils.ImageProcessingMixin`]: The image_processor object
+ instantiated from that JSON file.
+ """
+ with open(json_file, "r", encoding="utf-8") as reader:
+ text = reader.read()
+ image_processor_dict = json.loads(text)
+ return cls(**image_processor_dict)
+
+ def to_json_string(self) -> str:
+ """
+ Serializes this instance to a JSON string.
+
+ Returns:
+ `str`: String containing all the attributes that make up this feature_extractor instance in JSON format.
+ """
+ dictionary = self.to_dict()
+
+ for key, value in dictionary.items():
+ if isinstance(value, np.ndarray):
+ dictionary[key] = value.tolist()
+
+ # make sure private name "_processor_class" is correctly
+ # saved as "processor_class"
+ _processor_class = dictionary.pop("_processor_class", None)
+ if _processor_class is not None:
+ dictionary["processor_class"] = _processor_class
+
+ return json.dumps(dictionary, indent=2, sort_keys=True) + "\n"
+
+ 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 image_processor instance's parameters will be saved.
+ """
+ with open(json_file_path, "w", encoding="utf-8") as writer:
+ writer.write(self.to_json_string())
+
+ def __repr__(self):
+ return f"{self.__class__.__name__} {self.to_json_string()}"
+
+ @classmethod
+ def register_for_auto_class(cls, auto_class="AutoImageProcessor"):
+ """
+ Register this class with a given auto class. This should only be used for custom image processors as the ones
+ in the library are already mapped with `AutoImageProcessor `.
+
+
+
+ This API is experimental and may have some slight breaking changes in the next releases.
+
+
+
+ Args:
+ auto_class (`str` or `type`, *optional*, defaults to `"AutoImageProcessor "`):
+ The auto class to register this new image processor with.
+ """
+ if not isinstance(auto_class, str):
+ auto_class = auto_class.__name__
+
+ import transformers.models.auto as auto_module
+
+ if not hasattr(auto_module, auto_class):
+ raise ValueError(f"{auto_class} is not a valid auto class.")
+
+ cls._auto_class = auto_class
+
+ def fetch_images(self, image_url_or_urls: Union[str, List[str]]):
+ """
+ Convert a single or a list of urls into the corresponding `PIL.Image` objects.
+
+ If a single url is passed, the return value will be a single object. If a list is passed a list of objects is
+ returned.
+ """
+ headers = {
+ "User-Agent": (
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0"
+ " Safari/537.36"
+ )
+ }
+ if isinstance(image_url_or_urls, list):
+ return [self.fetch_images(x) for x in image_url_or_urls]
+ elif isinstance(image_url_or_urls, str):
+ response = requests.get(image_url_or_urls, stream=True, headers=headers)
+ response.raise_for_status()
+ return Image.open(BytesIO(response.content))
+ else:
+ raise TypeError(f"only a single or a list of entries is supported but got type={type(image_url_or_urls)}")
+
+
+ImageProcessingMixin.push_to_hub = copy_func(ImageProcessingMixin.push_to_hub)
+if ImageProcessingMixin.push_to_hub.__doc__ is not None:
+ ImageProcessingMixin.push_to_hub.__doc__ = ImageProcessingMixin.push_to_hub.__doc__.format(
+ object="image processor", object_class="AutoImageProcessor", object_files="image processor file"
+ )
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/image_processing_utils.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/image_processing_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..59aea9b8a5a8d7e207455d72d3e42b0705f1bd7c
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/image_processing_utils.py
@@ -0,0 +1,308 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Dict, Iterable, Optional, Union
+
+import numpy as np
+
+from .image_processing_base import BatchFeature, ImageProcessingMixin
+from .image_transforms import center_crop, normalize, rescale
+from .image_utils import ChannelDimension, get_image_size
+from .utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+INIT_SERVICE_KWARGS = [
+ "processor_class",
+ "image_processor_type",
+]
+
+
+class BaseImageProcessor(ImageProcessingMixin):
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ def __call__(self, images, **kwargs) -> BatchFeature:
+ """Preprocess an image or a batch of images."""
+ return self.preprocess(images, **kwargs)
+
+ def preprocess(self, images, **kwargs) -> BatchFeature:
+ raise NotImplementedError("Each image processor must implement its own preprocess method")
+
+ def rescale(
+ self,
+ image: np.ndarray,
+ scale: float,
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Rescale an image by a scale factor. image = image * scale.
+
+ Args:
+ image (`np.ndarray`):
+ Image to rescale.
+ scale (`float`):
+ The scaling factor to rescale pixel values by.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
+ image is used. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
+ from the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+
+ Returns:
+ `np.ndarray`: The rescaled image.
+ """
+ return rescale(image, scale=scale, data_format=data_format, input_data_format=input_data_format, **kwargs)
+
+ def normalize(
+ self,
+ image: np.ndarray,
+ mean: Union[float, Iterable[float]],
+ std: Union[float, Iterable[float]],
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Normalize an image. image = (image - image_mean) / image_std.
+
+ Args:
+ image (`np.ndarray`):
+ Image to normalize.
+ mean (`float` or `Iterable[float]`):
+ Image mean to use for normalization.
+ std (`float` or `Iterable[float]`):
+ Image standard deviation to use for normalization.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
+ image is used. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
+ from the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+
+ Returns:
+ `np.ndarray`: The normalized image.
+ """
+ return normalize(
+ image, mean=mean, std=std, data_format=data_format, input_data_format=input_data_format, **kwargs
+ )
+
+ def center_crop(
+ self,
+ image: np.ndarray,
+ size: Dict[str, int],
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Center crop an image to `(size["height"], size["width"])`. If the input size is smaller than `crop_size` along
+ any edge, the image is padded with 0's and then center cropped.
+
+ Args:
+ image (`np.ndarray`):
+ Image to center crop.
+ size (`Dict[str, int]`):
+ Size of the output image.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
+ image is used. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
+ from the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ """
+ size = get_size_dict(size)
+ if "height" not in size or "width" not in size:
+ raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}")
+ return center_crop(
+ image,
+ size=(size["height"], size["width"]),
+ data_format=data_format,
+ input_data_format=input_data_format,
+ **kwargs,
+ )
+
+ def to_dict(self):
+ encoder_dict = super().to_dict()
+ encoder_dict.pop("_valid_processor_keys", None)
+ return encoder_dict
+
+
+VALID_SIZE_DICT_KEYS = (
+ {"height", "width"},
+ {"shortest_edge"},
+ {"shortest_edge", "longest_edge"},
+ {"longest_edge"},
+ {"max_height", "max_width"},
+)
+
+
+def is_valid_size_dict(size_dict):
+ if not isinstance(size_dict, dict):
+ return False
+
+ size_dict_keys = set(size_dict.keys())
+ for allowed_keys in VALID_SIZE_DICT_KEYS:
+ if size_dict_keys == allowed_keys:
+ return True
+ return False
+
+
+def convert_to_size_dict(
+ size, max_size: Optional[int] = None, default_to_square: bool = True, height_width_order: bool = True
+):
+ # By default, if size is an int we assume it represents a tuple of (size, size).
+ if isinstance(size, int) and default_to_square:
+ if max_size is not None:
+ raise ValueError("Cannot specify both size as an int, with default_to_square=True and max_size")
+ return {"height": size, "width": size}
+ # In other configs, if size is an int and default_to_square is False, size represents the length of
+ # the shortest edge after resizing.
+ elif isinstance(size, int) and not default_to_square:
+ size_dict = {"shortest_edge": size}
+ if max_size is not None:
+ size_dict["longest_edge"] = max_size
+ return size_dict
+ # Otherwise, if size is a tuple it's either (height, width) or (width, height)
+ elif isinstance(size, (tuple, list)) and height_width_order:
+ return {"height": size[0], "width": size[1]}
+ elif isinstance(size, (tuple, list)) and not height_width_order:
+ return {"height": size[1], "width": size[0]}
+ elif size is None and max_size is not None:
+ if default_to_square:
+ raise ValueError("Cannot specify both default_to_square=True and max_size")
+ return {"longest_edge": max_size}
+
+ raise ValueError(f"Could not convert size input to size dict: {size}")
+
+
+def get_size_dict(
+ size: Union[int, Iterable[int], Dict[str, int]] = None,
+ max_size: Optional[int] = None,
+ height_width_order: bool = True,
+ default_to_square: bool = True,
+ param_name="size",
+) -> dict:
+ """
+ Converts the old size parameter in the config into the new dict expected in the config. This is to ensure backwards
+ compatibility with the old image processor configs and removes ambiguity over whether the tuple is in (height,
+ width) or (width, height) format.
+
+ - If `size` is tuple, it is converted to `{"height": size[0], "width": size[1]}` or `{"height": size[1], "width":
+ size[0]}` if `height_width_order` is `False`.
+ - If `size` is an int, and `default_to_square` is `True`, it is converted to `{"height": size, "width": size}`.
+ - If `size` is an int and `default_to_square` is False, it is converted to `{"shortest_edge": size}`. If `max_size`
+ is set, it is added to the dict as `{"longest_edge": max_size}`.
+
+ Args:
+ size (`Union[int, Iterable[int], Dict[str, int]]`, *optional*):
+ The `size` parameter to be cast into a size dictionary.
+ max_size (`Optional[int]`, *optional*):
+ The `max_size` parameter to be cast into a size dictionary.
+ height_width_order (`bool`, *optional*, defaults to `True`):
+ If `size` is a tuple, whether it's in (height, width) or (width, height) order.
+ default_to_square (`bool`, *optional*, defaults to `True`):
+ If `size` is an int, whether to default to a square image or not.
+ """
+ if not isinstance(size, dict):
+ size_dict = convert_to_size_dict(size, max_size, default_to_square, height_width_order)
+ logger.info(
+ f"{param_name} should be a dictionary on of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size}."
+ f" Converted to {size_dict}.",
+ )
+ else:
+ size_dict = size
+
+ if not is_valid_size_dict(size_dict):
+ raise ValueError(
+ f"{param_name} must have one of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size_dict.keys()}"
+ )
+ return size_dict
+
+
+def select_best_resolution(original_size: tuple, possible_resolutions: list) -> tuple:
+ """
+ Selects the best resolution from a list of possible resolutions based on the original size.
+
+ This is done by calculating the effective and wasted resolution for each possible resolution.
+
+ The best fit resolution is the one that maximizes the effective resolution and minimizes the wasted resolution.
+
+ Args:
+ original_size (tuple):
+ The original size of the image in the format (height, width).
+ possible_resolutions (list):
+ A list of possible resolutions in the format [(height1, width1), (height2, width2), ...].
+
+ Returns:
+ tuple: The best fit resolution in the format (height, width).
+ """
+ original_height, original_width = original_size
+ best_fit = None
+ max_effective_resolution = 0
+ min_wasted_resolution = float("inf")
+
+ for height, width in possible_resolutions:
+ scale = min(width / original_width, height / original_height)
+ downscaled_width, downscaled_height = int(original_width * scale), int(original_height * scale)
+ effective_resolution = min(downscaled_width * downscaled_height, original_width * original_height)
+ wasted_resolution = (width * height) - effective_resolution
+
+ if effective_resolution > max_effective_resolution or (
+ effective_resolution == max_effective_resolution and wasted_resolution < min_wasted_resolution
+ ):
+ max_effective_resolution = effective_resolution
+ min_wasted_resolution = wasted_resolution
+ best_fit = (height, width)
+
+ return best_fit
+
+
+def get_patch_output_size(image, target_resolution, input_data_format):
+ """
+ Given an image and a target resolution, calculate the output size of the image after cropping to the target
+ """
+ original_height, original_width = get_image_size(image, channel_dim=input_data_format)
+ target_height, target_width = target_resolution
+
+ scale_w = target_width / original_width
+ scale_h = target_height / original_height
+
+ if scale_w < scale_h:
+ new_width = target_width
+ new_height = min(math.ceil(original_height * scale_w), target_height)
+ else:
+ new_height = target_height
+ new_width = min(math.ceil(original_width * scale_h), target_width)
+
+ return new_height, new_width
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/image_processing_utils_fast.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/image_processing_utils_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a201220b6773d3d786a18cf981d35660893bbae
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/image_processing_utils_fast.py
@@ -0,0 +1,792 @@
+# coding=utf-8
+# Copyright 2024 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from functools import lru_cache, partial
+from typing import Any, Dict, Iterable, List, Optional, Tuple, TypedDict, Union
+
+import numpy as np
+
+from .image_processing_utils import (
+ BaseImageProcessor,
+ BatchFeature,
+ get_size_dict,
+)
+from .image_transforms import (
+ convert_to_rgb,
+ get_resize_output_image_size,
+ get_size_with_aspect_ratio,
+ group_images_by_shape,
+ reorder_images,
+)
+from .image_utils import (
+ ChannelDimension,
+ ImageInput,
+ ImageType,
+ SizeDict,
+ get_image_size,
+ get_image_size_for_max_height_width,
+ get_image_type,
+ infer_channel_dimension_format,
+ make_flat_list_of_images,
+ validate_kwargs,
+ validate_preprocess_arguments,
+)
+from .processing_utils import Unpack
+from .utils import (
+ TensorType,
+ add_start_docstrings,
+ is_torch_available,
+ is_torchvision_available,
+ is_torchvision_v2_available,
+ is_vision_available,
+ logging,
+)
+
+
+if is_vision_available():
+ from .image_utils import PILImageResampling
+
+if is_torch_available():
+ import torch
+
+if is_torchvision_available():
+ from .image_utils import pil_torch_interpolation_mapping
+
+ if is_torchvision_v2_available():
+ from torchvision.transforms.v2 import functional as F
+ else:
+ from torchvision.transforms import functional as F
+
+logger = logging.get_logger(__name__)
+
+
+@lru_cache(maxsize=10)
+def validate_fast_preprocess_arguments(
+ do_rescale: Optional[bool] = None,
+ rescale_factor: Optional[float] = None,
+ do_normalize: Optional[bool] = None,
+ image_mean: Optional[Union[float, List[float]]] = None,
+ image_std: Optional[Union[float, List[float]]] = None,
+ do_pad: Optional[bool] = None,
+ size_divisibility: Optional[int] = None,
+ do_center_crop: Optional[bool] = None,
+ crop_size: Optional[SizeDict] = None,
+ do_resize: Optional[bool] = None,
+ size: Optional[SizeDict] = None,
+ resample: Optional["PILImageResampling"] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
+):
+ """
+ Checks validity of typically used arguments in an `ImageProcessorFast` `preprocess` method.
+ Raises `ValueError` if arguments incompatibility is caught.
+ """
+ validate_preprocess_arguments(
+ do_rescale=do_rescale,
+ rescale_factor=rescale_factor,
+ do_normalize=do_normalize,
+ image_mean=image_mean,
+ image_std=image_std,
+ do_pad=do_pad,
+ size_divisibility=size_divisibility,
+ do_center_crop=do_center_crop,
+ crop_size=crop_size,
+ do_resize=do_resize,
+ size=size,
+ resample=resample,
+ )
+ # Extra checks for ImageProcessorFast
+ if return_tensors is not None and return_tensors != "pt":
+ raise ValueError("Only returning PyTorch tensors is currently supported.")
+
+ if data_format != ChannelDimension.FIRST:
+ raise ValueError("Only channel first data format is currently supported.")
+
+
+def safe_squeeze(tensor: "torch.Tensor", axis: Optional[int] = None) -> "torch.Tensor":
+ """
+ Squeezes a tensor, but only if the axis specified has dim 1.
+ """
+ if axis is None:
+ return tensor.squeeze()
+
+ try:
+ return tensor.squeeze(axis=axis)
+ except ValueError:
+ return tensor
+
+
+def max_across_indices(values: Iterable[Any]) -> List[Any]:
+ """
+ Return the maximum value across all indices of an iterable of values.
+ """
+ return [max(values_i) for values_i in zip(*values)]
+
+
+def get_max_height_width(images: List["torch.Tensor"]) -> Tuple[int]:
+ """
+ Get the maximum height and width across all images in a batch.
+ """
+
+ _, max_height, max_width = max_across_indices([img.shape for img in images])
+
+ return (max_height, max_width)
+
+
+def divide_to_patches(
+ image: Union[np.array, "torch.Tensor"], patch_size: int
+) -> List[Union[np.array, "torch.Tensor"]]:
+ """
+ Divides an image into patches of a specified size.
+
+ Args:
+ image (`Union[np.array, "torch.Tensor"]`):
+ The input image.
+ patch_size (`int`):
+ The size of each patch.
+ Returns:
+ list: A list of Union[np.array, "torch.Tensor"] representing the patches.
+ """
+ patches = []
+ height, width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
+ for i in range(0, height, patch_size):
+ for j in range(0, width, patch_size):
+ patch = image[:, i : i + patch_size, j : j + patch_size]
+ patches.append(patch)
+
+ return patches
+
+
+class DefaultFastImageProcessorKwargs(TypedDict, total=False):
+ do_resize: Optional[bool]
+ size: Optional[Dict[str, int]]
+ default_to_square: Optional[bool]
+ resample: Optional[Union["PILImageResampling", "F.InterpolationMode"]]
+ do_center_crop: Optional[bool]
+ crop_size: Optional[Dict[str, int]]
+ do_rescale: Optional[bool]
+ rescale_factor: Optional[Union[int, float]]
+ do_normalize: Optional[bool]
+ image_mean: Optional[Union[float, List[float]]]
+ image_std: Optional[Union[float, List[float]]]
+ do_convert_rgb: Optional[bool]
+ return_tensors: Optional[Union[str, TensorType]]
+ data_format: Optional[ChannelDimension]
+ input_data_format: Optional[Union[str, ChannelDimension]]
+ device: Optional["torch.device"]
+
+
+BASE_IMAGE_PROCESSOR_FAST_DOCSTRING = r"""
+
+ Args:
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
+ `do_resize` parameter in the `preprocess` method.
+ size (`dict`, *optional*, defaults to `self.size`):
+ Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
+ method.
+ default_to_square (`bool`, *optional*, defaults to `self.default_to_square`):
+ Whether to default to a square image when resizing, if size is an int.
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
+ Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`. Can be
+ overridden by the `resample` parameter in the `preprocess` method.
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
+ Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
+ `preprocess` method.
+ crop_size (`Dict[str, int]` *optional*, defaults to `self.crop_size`):
+ Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
+ method.
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
+ `do_rescale` parameter in the `preprocess` method.
+ rescale_factor (`int` or `float`, *optional*, defaults to `self.rescale_factor`):
+ Scale factor to use if rescaling the image. Only has an effect if `do_rescale` is set to `True`. Can be
+ overridden by the `rescale_factor` parameter in the `preprocess` method.
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
+ method. Can be overridden by the `do_normalize` parameter in the `preprocess` method.
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be
+ overridden by the `image_mean` parameter in the `preprocess` method.
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
+ Can be overridden by the `image_std` parameter in the `preprocess` method.
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
+ Whether to convert the image to RGB.
+ return_tensors (`str` or `TensorType`, *optional*, defaults to `self.return_tensors`):
+ Returns stacked tensors if set to `pt, otherwise returns a list of tensors.
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `self.data_format`):
+ Only `ChannelDimension.FIRST` is supported. Added for compatibility with slow processors.
+ input_data_format (`ChannelDimension` or `str`, *optional*, defaults to `self.input_data_format`):
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
+ from the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
+ device (`torch.device`, *optional*, defaults to `self.device`):
+ The device to process the images on. If unset, the device is inferred from the input images."""
+
+BASE_IMAGE_PROCESSOR_FAST_DOCSTRING_PREPROCESS = r"""
+ Preprocess an image or batch of images.
+
+ Args:
+ images (`ImageInput`):
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
+ Whether to resize the image.
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
+ Describes the maximum input dimensions to the model.
+ resample (`PILImageResampling` or `InterpolationMode`, *optional*, defaults to `self.resample`):
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
+ has an effect if `do_resize` is set to `True`.
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
+ Whether to center crop the image.
+ crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
+ Size of the output image after applying `center_crop`.
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
+ Whether to rescale the image.
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
+ Whether to normalize the image.
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
+ `True`.
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
+ Whether to convert the image to RGB.
+ return_tensors (`str` or `TensorType`, *optional*, defaults to `self.return_tensors`):
+ Returns stacked tensors if set to `pt, otherwise returns a list of tensors.
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `self.data_format`):
+ Only `ChannelDimension.FIRST` is supported. Added for compatibility with slow processors.
+ input_data_format (`ChannelDimension` or `str`, *optional*, defaults to `self.input_data_format`):
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
+ from the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
+ device (`torch.device`, *optional*, defaults to `self.device`):
+ The device to process the images on. If unset, the device is inferred from the input images."""
+
+
+@add_start_docstrings(
+ "Constructs a fast base image processor.",
+ BASE_IMAGE_PROCESSOR_FAST_DOCSTRING,
+)
+class BaseImageProcessorFast(BaseImageProcessor):
+ resample = None
+ image_mean = None
+ image_std = None
+ size = None
+ default_to_square = True
+ crop_size = None
+ do_resize = None
+ do_center_crop = None
+ do_rescale = None
+ rescale_factor = 1 / 255
+ do_normalize = None
+ do_convert_rgb = None
+ return_tensors = None
+ data_format = ChannelDimension.FIRST
+ input_data_format = None
+ device = None
+ model_input_names = ["pixel_values"]
+ valid_kwargs = DefaultFastImageProcessorKwargs
+ unused_kwargs = None
+
+ def __init__(
+ self,
+ **kwargs: Unpack[DefaultFastImageProcessorKwargs],
+ ) -> None:
+ super().__init__(**kwargs)
+ kwargs = self.filter_out_unused_kwargs(kwargs)
+ size = kwargs.pop("size", self.size)
+ self.size = (
+ get_size_dict(size=size, default_to_square=kwargs.pop("default_to_square", self.default_to_square))
+ if size is not None
+ else None
+ )
+ crop_size = kwargs.pop("crop_size", self.crop_size)
+ self.crop_size = get_size_dict(crop_size, param_name="crop_size") if crop_size is not None else None
+ for key in self.valid_kwargs.__annotations__.keys():
+ kwarg = kwargs.pop(key, None)
+ if kwarg is not None:
+ setattr(self, key, kwarg)
+ else:
+ setattr(self, key, getattr(self, key, None))
+
+ def resize(
+ self,
+ image: "torch.Tensor",
+ size: SizeDict,
+ interpolation: "F.InterpolationMode" = None,
+ antialias: bool = True,
+ **kwargs,
+ ) -> "torch.Tensor":
+ """
+ Resize an image to `(size["height"], size["width"])`.
+
+ Args:
+ image (`torch.Tensor`):
+ Image to resize.
+ size (`SizeDict`):
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
+ resample (`InterpolationMode`, *optional*, defaults to `InterpolationMode.BILINEAR`):
+ `InterpolationMode` filter to use when resizing the image e.g. `InterpolationMode.BICUBIC`.
+
+ Returns:
+ `torch.Tensor`: The resized image.
+ """
+ interpolation = interpolation if interpolation is not None else F.InterpolationMode.BILINEAR
+ if size.shortest_edge and size.longest_edge:
+ # Resize the image so that the shortest edge or the longest edge is of the given size
+ # while maintaining the aspect ratio of the original image.
+ new_size = get_size_with_aspect_ratio(
+ image.size()[-2:],
+ size.shortest_edge,
+ size.longest_edge,
+ )
+ elif size.shortest_edge:
+ new_size = get_resize_output_image_size(
+ image,
+ size=size.shortest_edge,
+ default_to_square=False,
+ input_data_format=ChannelDimension.FIRST,
+ )
+ elif size.max_height and size.max_width:
+ new_size = get_image_size_for_max_height_width(image.size()[-2:], size.max_height, size.max_width)
+ elif size.height and size.width:
+ new_size = (size.height, size.width)
+ else:
+ raise ValueError(
+ "Size must contain 'height' and 'width' keys, or 'max_height' and 'max_width', or 'shortest_edge' key. Got"
+ f" {size}."
+ )
+ return F.resize(image, new_size, interpolation=interpolation, antialias=antialias)
+
+ def rescale(
+ self,
+ image: "torch.Tensor",
+ scale: float,
+ **kwargs,
+ ) -> "torch.Tensor":
+ """
+ Rescale an image by a scale factor. image = image * scale.
+
+ Args:
+ image (`torch.Tensor`):
+ Image to rescale.
+ scale (`float`):
+ The scaling factor to rescale pixel values by.
+
+ Returns:
+ `torch.Tensor`: The rescaled image.
+ """
+ return image * scale
+
+ def normalize(
+ self,
+ image: "torch.Tensor",
+ mean: Union[float, Iterable[float]],
+ std: Union[float, Iterable[float]],
+ **kwargs,
+ ) -> "torch.Tensor":
+ """
+ Normalize an image. image = (image - image_mean) / image_std.
+
+ Args:
+ image (`torch.Tensor`):
+ Image to normalize.
+ mean (`torch.Tensor`, `float` or `Iterable[float]`):
+ Image mean to use for normalization.
+ std (`torch.Tensor`, `float` or `Iterable[float]`):
+ Image standard deviation to use for normalization.
+
+ Returns:
+ `torch.Tensor`: The normalized image.
+ """
+ return F.normalize(image, mean, std)
+
+ @lru_cache(maxsize=10)
+ def _fuse_mean_std_and_rescale_factor(
+ self,
+ do_normalize: Optional[bool] = None,
+ image_mean: Optional[Union[float, List[float]]] = None,
+ image_std: Optional[Union[float, List[float]]] = None,
+ do_rescale: Optional[bool] = None,
+ rescale_factor: Optional[float] = None,
+ device: Optional["torch.device"] = None,
+ ) -> tuple:
+ if do_rescale and do_normalize:
+ # Fused rescale and normalize
+ image_mean = torch.tensor(image_mean, device=device) * (1.0 / rescale_factor)
+ image_std = torch.tensor(image_std, device=device) * (1.0 / rescale_factor)
+ do_rescale = False
+ return image_mean, image_std, do_rescale
+
+ def rescale_and_normalize(
+ self,
+ images: "torch.Tensor",
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ image_mean: Union[float, List[float]],
+ image_std: Union[float, List[float]],
+ ) -> "torch.Tensor":
+ """
+ Rescale and normalize images.
+ """
+ image_mean, image_std, do_rescale = self._fuse_mean_std_and_rescale_factor(
+ do_normalize=do_normalize,
+ image_mean=image_mean,
+ image_std=image_std,
+ do_rescale=do_rescale,
+ rescale_factor=rescale_factor,
+ device=images.device,
+ )
+ # if/elif as we use fused rescale and normalize if both are set to True
+ if do_normalize:
+ images = self.normalize(images.to(dtype=torch.float32), image_mean, image_std)
+ elif do_rescale:
+ images = self.rescale(images, rescale_factor)
+
+ return images
+
+ def center_crop(
+ self,
+ image: "torch.Tensor",
+ size: Dict[str, int],
+ **kwargs,
+ ) -> "torch.Tensor":
+ """
+ Center crop an image to `(size["height"], size["width"])`. If the input size is smaller than `crop_size` along
+ any edge, the image is padded with 0's and then center cropped.
+
+ Args:
+ image (`"torch.Tensor"`):
+ Image to center crop.
+ size (`Dict[str, int]`):
+ Size of the output image.
+
+ Returns:
+ `torch.Tensor`: The center cropped image.
+ """
+ if size.height is None or size.width is None:
+ raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}")
+ return F.center_crop(image, (size["height"], size["width"]))
+
+ def convert_to_rgb(
+ self,
+ image: ImageInput,
+ ) -> ImageInput:
+ """
+ Converts an image to RGB format. Only converts if the image is of type PIL.Image.Image, otherwise returns the image
+ as is.
+ Args:
+ image (ImageInput):
+ The image to convert.
+
+ Returns:
+ ImageInput: The converted image.
+ """
+ return convert_to_rgb(image)
+
+ def filter_out_unused_kwargs(self, kwargs: dict):
+ """
+ Filter out the unused kwargs from the kwargs dictionary.
+ """
+ if self.unused_kwargs is None:
+ return kwargs
+
+ for kwarg_name in self.unused_kwargs:
+ if kwarg_name in kwargs:
+ logger.warning_once(f"This processor does not use the `{kwarg_name}` parameter. It will be ignored.")
+ kwargs.pop(kwarg_name)
+ return kwargs
+
+ def _prepare_images_structure(
+ self,
+ images: ImageInput,
+ ) -> ImageInput:
+ """
+ Prepare the images structure for processing.
+
+ Args:
+ images (`ImageInput`):
+ The input images to process.
+
+ Returns:
+ `ImageInput`: The images with a valid nesting.
+ """
+ return make_flat_list_of_images(images)
+
+ def _process_image(
+ self,
+ image: ImageInput,
+ do_convert_rgb: Optional[bool] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ device: Optional["torch.device"] = None,
+ ) -> "torch.Tensor":
+ image_type = get_image_type(image)
+ if image_type not in [ImageType.PIL, ImageType.TORCH, ImageType.NUMPY]:
+ raise ValueError(f"Unsupported input image type {image_type}")
+
+ if do_convert_rgb:
+ image = self.convert_to_rgb(image)
+
+ if image_type == ImageType.PIL:
+ image = F.pil_to_tensor(image)
+ elif image_type == ImageType.NUMPY:
+ # not using F.to_tensor as it doesn't handle (C, H, W) numpy arrays
+ image = torch.from_numpy(image).contiguous()
+
+ # Infer the channel dimension format if not provided
+ if input_data_format is None:
+ input_data_format = infer_channel_dimension_format(image)
+
+ if input_data_format == ChannelDimension.LAST:
+ # We force the channel dimension to be first for torch tensors as this is what torchvision expects.
+ image = image.permute(2, 0, 1).contiguous()
+
+ # Now that we have torch tensors, we can move them to the right device
+ if device is not None:
+ image = image.to(device)
+
+ return image
+
+ def _prepare_input_images(
+ self,
+ images: ImageInput,
+ do_convert_rgb: bool = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ device: Optional["torch.device"] = None,
+ ) -> List["torch.Tensor"]:
+ """
+ Prepare the input images for processing.
+ """
+ images = self._prepare_images_structure(images)
+ process_image_fn = partial(
+ self._process_image,
+ do_convert_rgb=do_convert_rgb,
+ input_data_format=input_data_format,
+ device=device,
+ )
+ # todo: yoni - check if we can parallelize this efficiently
+ processed_images = []
+ for image in images:
+ processed_images.append(process_image_fn(image))
+
+ return processed_images
+
+ def _further_process_kwargs(
+ self,
+ size: Optional[SizeDict] = None,
+ crop_size: Optional[SizeDict] = None,
+ default_to_square: Optional[bool] = None,
+ image_mean: Optional[Union[float, List[float]]] = None,
+ image_std: Optional[Union[float, List[float]]] = None,
+ data_format: Optional[ChannelDimension] = None,
+ **kwargs,
+ ) -> dict:
+ """
+ Update kwargs that need further processing before being validated
+ Can be overridden by subclasses to customize the processing of kwargs.
+ """
+ if kwargs is None:
+ kwargs = {}
+ if size is not None:
+ size = SizeDict(**get_size_dict(size=size, default_to_square=default_to_square))
+ if crop_size is not None:
+ crop_size = SizeDict(**get_size_dict(crop_size, param_name="crop_size"))
+ if isinstance(image_mean, list):
+ image_mean = tuple(image_mean)
+ if isinstance(image_std, list):
+ image_std = tuple(image_std)
+ if data_format is None:
+ data_format = ChannelDimension.FIRST
+
+ kwargs["size"] = size
+ kwargs["crop_size"] = crop_size
+ kwargs["default_to_square"] = default_to_square
+ kwargs["image_mean"] = image_mean
+ kwargs["image_std"] = image_std
+ kwargs["data_format"] = data_format
+
+ return kwargs
+
+ def _validate_preprocess_kwargs(
+ self,
+ do_rescale: Optional[bool] = None,
+ rescale_factor: Optional[float] = None,
+ do_normalize: Optional[bool] = None,
+ image_mean: Optional[Union[float, tuple[float]]] = None,
+ image_std: Optional[Union[float, tuple[float]]] = None,
+ do_resize: Optional[bool] = None,
+ size: Optional[SizeDict] = None,
+ do_center_crop: Optional[bool] = None,
+ crop_size: Optional[SizeDict] = None,
+ resample: Optional[Union["PILImageResampling", "F.InterpolationMode"]] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ data_format: Optional[ChannelDimension] = None,
+ **kwargs,
+ ):
+ """
+ validate the kwargs for the preprocess method.
+ """
+ validate_fast_preprocess_arguments(
+ do_rescale=do_rescale,
+ rescale_factor=rescale_factor,
+ do_normalize=do_normalize,
+ image_mean=image_mean,
+ image_std=image_std,
+ do_resize=do_resize,
+ size=size,
+ do_center_crop=do_center_crop,
+ crop_size=crop_size,
+ resample=resample,
+ return_tensors=return_tensors,
+ data_format=data_format,
+ )
+
+ @add_start_docstrings(BASE_IMAGE_PROCESSOR_FAST_DOCSTRING_PREPROCESS)
+ def preprocess(self, images: ImageInput, **kwargs: Unpack[DefaultFastImageProcessorKwargs]) -> BatchFeature:
+ validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self.valid_kwargs.__annotations__.keys())
+ # Set default kwargs from self. This ensures that if a kwarg is not provided
+ # by the user, it gets its default value from the instance, or is set to None.
+ for kwarg_name in self.valid_kwargs.__annotations__:
+ kwargs.setdefault(kwarg_name, getattr(self, kwarg_name, None))
+
+ # Extract parameters that are only used for preparing the input images
+ do_convert_rgb = kwargs.pop("do_convert_rgb")
+ input_data_format = kwargs.pop("input_data_format")
+ device = kwargs.pop("device")
+ # Prepare input images
+ images = self._prepare_input_images(
+ images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device
+ )
+
+ # Update kwargs that need further processing before being validated
+ kwargs = self._further_process_kwargs(**kwargs)
+
+ # Validate kwargs
+ self._validate_preprocess_kwargs(**kwargs)
+
+ # torch resize uses interpolation instead of resample
+ resample = kwargs.pop("resample")
+ kwargs["interpolation"] = (
+ pil_torch_interpolation_mapping[resample] if isinstance(resample, (PILImageResampling, int)) else resample
+ )
+
+ # Pop kwargs that are not needed in _preprocess
+ kwargs.pop("default_to_square")
+ kwargs.pop("data_format")
+
+ return self._preprocess(images=images, **kwargs)
+
+ def _preprocess(
+ self,
+ images: List["torch.Tensor"],
+ do_resize: bool,
+ size: SizeDict,
+ interpolation: Optional["F.InterpolationMode"],
+ do_center_crop: bool,
+ crop_size: SizeDict,
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ image_mean: Optional[Union[float, List[float]]],
+ image_std: Optional[Union[float, List[float]]],
+ return_tensors: Optional[Union[str, TensorType]],
+ **kwargs,
+ ) -> BatchFeature:
+ # Group images by size for batched resizing
+ grouped_images, grouped_images_index = group_images_by_shape(images)
+ resized_images_grouped = {}
+ for shape, stacked_images in grouped_images.items():
+ if do_resize:
+ stacked_images = self.resize(image=stacked_images, size=size, interpolation=interpolation)
+ resized_images_grouped[shape] = stacked_images
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
+
+ # Group images by size for further processing
+ # Needed in case do_resize is False, or resize returns images with different sizes
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images)
+ processed_images_grouped = {}
+ for shape, stacked_images in grouped_images.items():
+ if do_center_crop:
+ stacked_images = self.center_crop(stacked_images, crop_size)
+ # Fused rescale and normalize
+ stacked_images = self.rescale_and_normalize(
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
+ )
+ processed_images_grouped[shape] = stacked_images
+
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
+ processed_images = torch.stack(processed_images, dim=0) if return_tensors else processed_images
+
+ return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
+
+ def to_dict(self):
+ encoder_dict = super().to_dict()
+ encoder_dict.pop("_valid_processor_keys", None)
+ return encoder_dict
+
+
+class SemanticSegmentationMixin:
+ def post_process_semantic_segmentation(self, outputs, target_sizes: List[Tuple] = None):
+ """
+ Converts the output of [`MobileNetV2ForSemanticSegmentation`] into semantic segmentation maps. Only supports PyTorch.
+
+ Args:
+ outputs ([`MobileNetV2ForSemanticSegmentation`]):
+ Raw outputs of the model.
+ target_sizes (`List[Tuple]` of length `batch_size`, *optional*):
+ List of tuples corresponding to the requested final size (height, width) of each prediction. If unset,
+ predictions will not be resized.
+
+ Returns:
+ semantic_segmentation: `List[torch.Tensor]` of length `batch_size`, where each item is a semantic
+ segmentation map of shape (height, width) corresponding to the target_sizes entry (if `target_sizes` is
+ specified). Each entry of each `torch.Tensor` correspond to a semantic class id.
+ """
+ logits = outputs.logits
+
+ # Resize logits and compute semantic segmentation maps
+ if target_sizes is not None:
+ if len(logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ # if is_torch_tensor(target_sizes):
+ # target_sizes = target_sizes.numpy()
+
+ semantic_segmentation = []
+
+ for idx in range(len(logits)):
+ resized_logits = torch.nn.functional.interpolate(
+ logits[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
+ )
+ semantic_map = resized_logits[0].argmax(dim=0)
+ semantic_segmentation.append(semantic_map)
+ else:
+ semantic_segmentation = logits.argmax(dim=1)
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
+
+ return semantic_segmentation
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/image_transforms.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/image_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..22f0b8e62c8f752e1f608515a5c9c2d4d2f3a5f3
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/image_transforms.py
@@ -0,0 +1,898 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import warnings
+from collections.abc import Collection
+from math import ceil
+from typing import Dict, Iterable, List, Optional, Tuple, Union
+
+import numpy as np
+
+from .image_utils import (
+ ChannelDimension,
+ ImageInput,
+ get_channel_dimension_axis,
+ get_image_size,
+ infer_channel_dimension_format,
+)
+from .utils import ExplicitEnum, TensorType, is_jax_tensor, is_tf_tensor, is_torch_tensor
+from .utils.import_utils import (
+ is_flax_available,
+ is_tf_available,
+ is_torch_available,
+ is_vision_available,
+ requires_backends,
+)
+
+
+if is_vision_available():
+ import PIL
+
+ from .image_utils import PILImageResampling
+
+if is_torch_available():
+ import torch
+
+if is_tf_available():
+ import tensorflow as tf
+
+if is_flax_available():
+ import jax.numpy as jnp
+
+
+def to_channel_dimension_format(
+ image: np.ndarray,
+ channel_dim: Union[ChannelDimension, str],
+ input_channel_dim: Optional[Union[ChannelDimension, str]] = None,
+) -> np.ndarray:
+ """
+ Converts `image` to the channel dimension format specified by `channel_dim`.
+
+ Args:
+ image (`numpy.ndarray`):
+ The image to have its channel dimension set.
+ channel_dim (`ChannelDimension`):
+ The channel dimension format to use.
+ input_channel_dim (`ChannelDimension`, *optional*):
+ The channel dimension format of the input image. If not provided, it will be inferred from the input image.
+
+ Returns:
+ `np.ndarray`: The image with the channel dimension set to `channel_dim`.
+ """
+ if not isinstance(image, np.ndarray):
+ raise TypeError(f"Input image must be of type np.ndarray, got {type(image)}")
+
+ if input_channel_dim is None:
+ input_channel_dim = infer_channel_dimension_format(image)
+
+ target_channel_dim = ChannelDimension(channel_dim)
+ if input_channel_dim == target_channel_dim:
+ return image
+
+ if target_channel_dim == ChannelDimension.FIRST:
+ image = image.transpose((2, 0, 1))
+ elif target_channel_dim == ChannelDimension.LAST:
+ image = image.transpose((1, 2, 0))
+ else:
+ raise ValueError("Unsupported channel dimension format: {}".format(channel_dim))
+
+ return image
+
+
+def rescale(
+ image: np.ndarray,
+ scale: float,
+ data_format: Optional[ChannelDimension] = None,
+ dtype: np.dtype = np.float32,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> np.ndarray:
+ """
+ Rescales `image` by `scale`.
+
+ Args:
+ image (`np.ndarray`):
+ The image to rescale.
+ scale (`float`):
+ The scale to use for rescaling the image.
+ data_format (`ChannelDimension`, *optional*):
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
+ dtype (`np.dtype`, *optional*, defaults to `np.float32`):
+ The dtype of the output image. Defaults to `np.float32`. Used for backwards compatibility with feature
+ extractors.
+ input_data_format (`ChannelDimension`, *optional*):
+ The channel dimension format of the input image. If not provided, it will be inferred from the input image.
+
+ Returns:
+ `np.ndarray`: The rescaled image.
+ """
+ if not isinstance(image, np.ndarray):
+ raise TypeError(f"Input image must be of type np.ndarray, got {type(image)}")
+
+ rescaled_image = image.astype(np.float64) * scale # Numpy type promotion has changed, so always upcast first
+ if data_format is not None:
+ rescaled_image = to_channel_dimension_format(rescaled_image, data_format, input_data_format)
+
+ rescaled_image = rescaled_image.astype(dtype) # Finally downcast to the desired dtype at the end
+
+ return rescaled_image
+
+
+def _rescale_for_pil_conversion(image):
+ """
+ Detects whether or not the image needs to be rescaled before being converted to a PIL image.
+
+ The assumption is that if the image is of type `np.float` and all values are between 0 and 1, it needs to be
+ rescaled.
+ """
+ if image.dtype == np.uint8:
+ do_rescale = False
+ elif np.allclose(image, image.astype(int)):
+ if np.all(0 <= image) and np.all(image <= 255):
+ do_rescale = False
+ else:
+ raise ValueError(
+ "The image to be converted to a PIL image contains values outside the range [0, 255], "
+ f"got [{image.min()}, {image.max()}] which cannot be converted to uint8."
+ )
+ elif np.all(0 <= image) and np.all(image <= 1):
+ do_rescale = True
+ else:
+ raise ValueError(
+ "The image to be converted to a PIL image contains values outside the range [0, 1], "
+ f"got [{image.min()}, {image.max()}] which cannot be converted to uint8."
+ )
+ return do_rescale
+
+
+def to_pil_image(
+ image: Union[np.ndarray, "PIL.Image.Image", "torch.Tensor", "tf.Tensor", "jnp.ndarray"],
+ do_rescale: Optional[bool] = None,
+ image_mode: Optional[str] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> "PIL.Image.Image":
+ """
+ Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if
+ needed.
+
+ Args:
+ image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor` or `tf.Tensor`):
+ The image to convert to the `PIL.Image` format.
+ do_rescale (`bool`, *optional*):
+ Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will default
+ to `True` if the image type is a floating type and casting to `int` would result in a loss of precision,
+ and `False` otherwise.
+ image_mode (`str`, *optional*):
+ The mode to use for the PIL image. If unset, will use the default mode for the input image type.
+ input_data_format (`ChannelDimension`, *optional*):
+ The channel dimension format of the input image. If unset, will use the inferred format from the input.
+
+ Returns:
+ `PIL.Image.Image`: The converted image.
+ """
+ requires_backends(to_pil_image, ["vision"])
+
+ if isinstance(image, PIL.Image.Image):
+ return image
+
+ # Convert all tensors to numpy arrays before converting to PIL image
+ if is_torch_tensor(image) or is_tf_tensor(image):
+ image = image.numpy()
+ elif is_jax_tensor(image):
+ image = np.array(image)
+ elif not isinstance(image, np.ndarray):
+ raise ValueError("Input image type not supported: {}".format(type(image)))
+
+ # If the channel has been moved to first dim, we put it back at the end.
+ image = to_channel_dimension_format(image, ChannelDimension.LAST, input_data_format)
+
+ # If there is a single channel, we squeeze it, as otherwise PIL can't handle it.
+ image = np.squeeze(image, axis=-1) if image.shape[-1] == 1 else image
+
+ # PIL.Image can only store uint8 values so we rescale the image to be between 0 and 255 if needed.
+ do_rescale = _rescale_for_pil_conversion(image) if do_rescale is None else do_rescale
+
+ if do_rescale:
+ image = rescale(image, 255)
+
+ image = image.astype(np.uint8)
+ return PIL.Image.fromarray(image, mode=image_mode)
+
+
+def get_size_with_aspect_ratio(image_size, size, max_size=None) -> Tuple[int, int]:
+ """
+ Computes the output image size given the input image size and the desired output size.
+
+ Args:
+ image_size (`Tuple[int, int]`):
+ The input image size.
+ size (`int`):
+ The desired output size.
+ max_size (`int`, *optional*):
+ The maximum allowed output size.
+ """
+ height, width = image_size
+ raw_size = None
+ if max_size is not None:
+ min_original_size = float(min((height, width)))
+ max_original_size = float(max((height, width)))
+ if max_original_size / min_original_size * size > max_size:
+ raw_size = max_size * min_original_size / max_original_size
+ size = int(round(raw_size))
+
+ if (height <= width and height == size) or (width <= height and width == size):
+ oh, ow = height, width
+ elif width < height:
+ ow = size
+ if max_size is not None and raw_size is not None:
+ oh = int(raw_size * height / width)
+ else:
+ oh = int(size * height / width)
+ else:
+ oh = size
+ if max_size is not None and raw_size is not None:
+ ow = int(raw_size * width / height)
+ else:
+ ow = int(size * width / height)
+
+ return (oh, ow)
+
+
+# Logic adapted from torchvision resizing logic: https://github.com/pytorch/vision/blob/511924c1ced4ce0461197e5caa64ce5b9e558aab/torchvision/transforms/functional.py#L366
+def get_resize_output_image_size(
+ input_image: np.ndarray,
+ size: Union[int, Tuple[int, int], List[int], Tuple[int]],
+ default_to_square: bool = True,
+ max_size: Optional[int] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> tuple:
+ """
+ Find the target (height, width) dimension of the output image after resizing given the input image and the desired
+ size.
+
+ Args:
+ input_image (`np.ndarray`):
+ The image to resize.
+ size (`int` or `Tuple[int, int]` or List[int] or `Tuple[int]`):
+ The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be matched to
+ this.
+
+ If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If
+ `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to this
+ number. i.e, if height > width, then image will be rescaled to (size * height / width, size).
+ default_to_square (`bool`, *optional*, defaults to `True`):
+ How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a square
+ (`size`,`size`). If set to `False`, will replicate
+ [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize)
+ with support for resizing only the smallest edge and providing an optional `max_size`.
+ max_size (`int`, *optional*):
+ The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater
+ than `max_size` after being resized according to `size`, then the image is resized again so that the longer
+ edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller edge may be shorter
+ than `size`. Only used if `default_to_square` is `False`.
+ input_data_format (`ChannelDimension`, *optional*):
+ The channel dimension format of the input image. If unset, will use the inferred format from the input.
+
+ Returns:
+ `tuple`: The target (height, width) dimension of the output image after resizing.
+ """
+ if isinstance(size, (tuple, list)):
+ if len(size) == 2:
+ return tuple(size)
+ elif len(size) == 1:
+ # Perform same logic as if size was an int
+ size = size[0]
+ else:
+ raise ValueError("size must have 1 or 2 elements if it is a list or tuple")
+
+ if default_to_square:
+ return (size, size)
+
+ height, width = get_image_size(input_image, input_data_format)
+ short, long = (width, height) if width <= height else (height, width)
+ requested_new_short = size
+
+ new_short, new_long = requested_new_short, int(requested_new_short * long / short)
+
+ if max_size is not None:
+ if max_size <= requested_new_short:
+ raise ValueError(
+ f"max_size = {max_size} must be strictly greater than the requested "
+ f"size for the smaller edge size = {size}"
+ )
+ if new_long > max_size:
+ new_short, new_long = int(max_size * new_short / new_long), max_size
+
+ return (new_long, new_short) if width <= height else (new_short, new_long)
+
+
+def resize(
+ image: np.ndarray,
+ size: Tuple[int, int],
+ resample: "PILImageResampling" = None,
+ reducing_gap: Optional[int] = None,
+ data_format: Optional[ChannelDimension] = None,
+ return_numpy: bool = True,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> np.ndarray:
+ """
+ Resizes `image` to `(height, width)` specified by `size` using the PIL library.
+
+ Args:
+ image (`np.ndarray`):
+ The image to resize.
+ size (`Tuple[int, int]`):
+ The size to use for resizing the image.
+ resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ The filter to user for resampling.
+ reducing_gap (`int`, *optional*):
+ Apply optimization by resizing the image in two steps. The bigger `reducing_gap`, the closer the result to
+ the fair resampling. See corresponding Pillow documentation for more details.
+ data_format (`ChannelDimension`, *optional*):
+ The channel dimension format of the output image. If unset, will use the inferred format from the input.
+ return_numpy (`bool`, *optional*, defaults to `True`):
+ Whether or not to return the resized image as a numpy array. If False a `PIL.Image.Image` object is
+ returned.
+ input_data_format (`ChannelDimension`, *optional*):
+ The channel dimension format of the input image. If unset, will use the inferred format from the input.
+
+ Returns:
+ `np.ndarray`: The resized image.
+ """
+ requires_backends(resize, ["vision"])
+
+ resample = resample if resample is not None else PILImageResampling.BILINEAR
+
+ if not len(size) == 2:
+ raise ValueError("size must have 2 elements")
+
+ # For all transformations, we want to keep the same data format as the input image unless otherwise specified.
+ # The resized image from PIL will always have channels last, so find the input format first.
+ if input_data_format is None:
+ input_data_format = infer_channel_dimension_format(image)
+ data_format = input_data_format if data_format is None else data_format
+
+ # To maintain backwards compatibility with the resizing done in previous image feature extractors, we use
+ # the pillow library to resize the image and then convert back to numpy
+ do_rescale = False
+ if not isinstance(image, PIL.Image.Image):
+ do_rescale = _rescale_for_pil_conversion(image)
+ image = to_pil_image(image, do_rescale=do_rescale, input_data_format=input_data_format)
+ height, width = size
+ # PIL images are in the format (width, height)
+ resized_image = image.resize((width, height), resample=resample, reducing_gap=reducing_gap)
+
+ if return_numpy:
+ resized_image = np.array(resized_image)
+ # If the input image channel dimension was of size 1, then it is dropped when converting to a PIL image
+ # so we need to add it back if necessary.
+ resized_image = np.expand_dims(resized_image, axis=-1) if resized_image.ndim == 2 else resized_image
+ # The image is always in channels last format after converting from a PIL image
+ resized_image = to_channel_dimension_format(
+ resized_image, data_format, input_channel_dim=ChannelDimension.LAST
+ )
+ # If an image was rescaled to be in the range [0, 255] before converting to a PIL image, then we need to
+ # rescale it back to the original range.
+ resized_image = rescale(resized_image, 1 / 255) if do_rescale else resized_image
+ return resized_image
+
+
+def normalize(
+ image: np.ndarray,
+ mean: Union[float, Collection[float]],
+ std: Union[float, Collection[float]],
+ data_format: Optional[ChannelDimension] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> np.ndarray:
+ """
+ Normalizes `image` using the mean and standard deviation specified by `mean` and `std`.
+
+ image = (image - mean) / std
+
+ Args:
+ image (`np.ndarray`):
+ The image to normalize.
+ mean (`float` or `Collection[float]`):
+ The mean to use for normalization.
+ std (`float` or `Collection[float]`):
+ The standard deviation to use for normalization.
+ data_format (`ChannelDimension`, *optional*):
+ The channel dimension format of the output image. If unset, will use the inferred format from the input.
+ input_data_format (`ChannelDimension`, *optional*):
+ The channel dimension format of the input image. If unset, will use the inferred format from the input.
+ """
+ if not isinstance(image, np.ndarray):
+ raise ValueError("image must be a numpy array")
+
+ if input_data_format is None:
+ input_data_format = infer_channel_dimension_format(image)
+
+ channel_axis = get_channel_dimension_axis(image, input_data_format=input_data_format)
+ num_channels = image.shape[channel_axis]
+
+ # We cast to float32 to avoid errors that can occur when subtracting uint8 values.
+ # We preserve the original dtype if it is a float type to prevent upcasting float16.
+ if not np.issubdtype(image.dtype, np.floating):
+ image = image.astype(np.float32)
+
+ if isinstance(mean, Collection):
+ if len(mean) != num_channels:
+ raise ValueError(f"mean must have {num_channels} elements if it is an iterable, got {len(mean)}")
+ else:
+ mean = [mean] * num_channels
+ mean = np.array(mean, dtype=image.dtype)
+
+ if isinstance(std, Collection):
+ if len(std) != num_channels:
+ raise ValueError(f"std must have {num_channels} elements if it is an iterable, got {len(std)}")
+ else:
+ std = [std] * num_channels
+ std = np.array(std, dtype=image.dtype)
+
+ if input_data_format == ChannelDimension.LAST:
+ image = (image - mean) / std
+ else:
+ image = ((image.T - mean) / std).T
+
+ image = to_channel_dimension_format(image, data_format, input_data_format) if data_format is not None else image
+ return image
+
+
+def center_crop(
+ image: np.ndarray,
+ size: Tuple[int, int],
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ return_numpy: Optional[bool] = None,
+) -> np.ndarray:
+ """
+ Crops the `image` to the specified `size` using a center crop. Note that if the image is too small to be cropped to
+ the size given, it will be padded (so the returned result will always be of size `size`).
+
+ Args:
+ image (`np.ndarray`):
+ The image to crop.
+ size (`Tuple[int, int]`):
+ The target size for the cropped image.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the output image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ If unset, will use the inferred format of the input image.
+ input_data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ If unset, will use the inferred format of the input image.
+ return_numpy (`bool`, *optional*):
+ Whether or not to return the cropped image as a numpy array. Used for backwards compatibility with the
+ previous ImageFeatureExtractionMixin method.
+ - Unset: will return the same type as the input image.
+ - `True`: will return a numpy array.
+ - `False`: will return a `PIL.Image.Image` object.
+ Returns:
+ `np.ndarray`: The cropped image.
+ """
+ requires_backends(center_crop, ["vision"])
+
+ if return_numpy is not None:
+ warnings.warn("return_numpy is deprecated and will be removed in v.4.33", FutureWarning)
+
+ return_numpy = True if return_numpy is None else return_numpy
+
+ if not isinstance(image, np.ndarray):
+ raise TypeError(f"Input image must be of type np.ndarray, got {type(image)}")
+
+ if not isinstance(size, Iterable) or len(size) != 2:
+ raise ValueError("size must have 2 elements representing the height and width of the output image")
+
+ if input_data_format is None:
+ input_data_format = infer_channel_dimension_format(image)
+ output_data_format = data_format if data_format is not None else input_data_format
+
+ # We perform the crop in (C, H, W) format and then convert to the output format
+ image = to_channel_dimension_format(image, ChannelDimension.FIRST, input_data_format)
+
+ orig_height, orig_width = get_image_size(image, ChannelDimension.FIRST)
+ crop_height, crop_width = size
+ crop_height, crop_width = int(crop_height), int(crop_width)
+
+ # In case size is odd, (image_shape[0] + size[0]) // 2 won't give the proper result.
+ top = (orig_height - crop_height) // 2
+ bottom = top + crop_height
+ # In case size is odd, (image_shape[1] + size[1]) // 2 won't give the proper result.
+ left = (orig_width - crop_width) // 2
+ right = left + crop_width
+
+ # Check if cropped area is within image boundaries
+ if top >= 0 and bottom <= orig_height and left >= 0 and right <= orig_width:
+ image = image[..., top:bottom, left:right]
+ image = to_channel_dimension_format(image, output_data_format, ChannelDimension.FIRST)
+ return image
+
+ # Otherwise, we may need to pad if the image is too small. Oh joy...
+ new_height = max(crop_height, orig_height)
+ new_width = max(crop_width, orig_width)
+ new_shape = image.shape[:-2] + (new_height, new_width)
+ new_image = np.zeros_like(image, shape=new_shape)
+
+ # If the image is too small, pad it with zeros
+ top_pad = ceil((new_height - orig_height) / 2)
+ bottom_pad = top_pad + orig_height
+ left_pad = ceil((new_width - orig_width) / 2)
+ right_pad = left_pad + orig_width
+ new_image[..., top_pad:bottom_pad, left_pad:right_pad] = image
+
+ top += top_pad
+ bottom += top_pad
+ left += left_pad
+ right += left_pad
+
+ new_image = new_image[..., max(0, top) : min(new_height, bottom), max(0, left) : min(new_width, right)]
+ new_image = to_channel_dimension_format(new_image, output_data_format, ChannelDimension.FIRST)
+
+ if not return_numpy:
+ new_image = to_pil_image(new_image)
+
+ return new_image
+
+
+def _center_to_corners_format_torch(bboxes_center: "torch.Tensor") -> "torch.Tensor":
+ center_x, center_y, width, height = bboxes_center.unbind(-1)
+ bbox_corners = torch.stack(
+ # top left x, top left y, bottom right x, bottom right y
+ [(center_x - 0.5 * width), (center_y - 0.5 * height), (center_x + 0.5 * width), (center_y + 0.5 * height)],
+ dim=-1,
+ )
+ return bbox_corners
+
+
+def _center_to_corners_format_numpy(bboxes_center: np.ndarray) -> np.ndarray:
+ center_x, center_y, width, height = bboxes_center.T
+ bboxes_corners = np.stack(
+ # top left x, top left y, bottom right x, bottom right y
+ [center_x - 0.5 * width, center_y - 0.5 * height, center_x + 0.5 * width, center_y + 0.5 * height],
+ axis=-1,
+ )
+ return bboxes_corners
+
+
+def _center_to_corners_format_tf(bboxes_center: "tf.Tensor") -> "tf.Tensor":
+ center_x, center_y, width, height = tf.unstack(bboxes_center, axis=-1)
+ bboxes_corners = tf.stack(
+ # top left x, top left y, bottom right x, bottom right y
+ [center_x - 0.5 * width, center_y - 0.5 * height, center_x + 0.5 * width, center_y + 0.5 * height],
+ axis=-1,
+ )
+ return bboxes_corners
+
+
+# 2 functions below inspired by https://github.com/facebookresearch/detr/blob/master/util/box_ops.py
+def center_to_corners_format(bboxes_center: TensorType) -> TensorType:
+ """
+ Converts bounding boxes from center format to corners format.
+
+ center format: contains the coordinate for the center of the box and its width, height dimensions
+ (center_x, center_y, width, height)
+ corners format: contains the coordinates for the top-left and bottom-right corners of the box
+ (top_left_x, top_left_y, bottom_right_x, bottom_right_y)
+ """
+ # Function is used during model forward pass, so we use the input framework if possible, without
+ # converting to numpy
+ if is_torch_tensor(bboxes_center):
+ return _center_to_corners_format_torch(bboxes_center)
+ elif isinstance(bboxes_center, np.ndarray):
+ return _center_to_corners_format_numpy(bboxes_center)
+ elif is_tf_tensor(bboxes_center):
+ return _center_to_corners_format_tf(bboxes_center)
+
+ raise ValueError(f"Unsupported input type {type(bboxes_center)}")
+
+
+def _corners_to_center_format_torch(bboxes_corners: "torch.Tensor") -> "torch.Tensor":
+ top_left_x, top_left_y, bottom_right_x, bottom_right_y = bboxes_corners.unbind(-1)
+ b = [
+ (top_left_x + bottom_right_x) / 2, # center x
+ (top_left_y + bottom_right_y) / 2, # center y
+ (bottom_right_x - top_left_x), # width
+ (bottom_right_y - top_left_y), # height
+ ]
+ return torch.stack(b, dim=-1)
+
+
+def _corners_to_center_format_numpy(bboxes_corners: np.ndarray) -> np.ndarray:
+ top_left_x, top_left_y, bottom_right_x, bottom_right_y = bboxes_corners.T
+ bboxes_center = np.stack(
+ [
+ (top_left_x + bottom_right_x) / 2, # center x
+ (top_left_y + bottom_right_y) / 2, # center y
+ (bottom_right_x - top_left_x), # width
+ (bottom_right_y - top_left_y), # height
+ ],
+ axis=-1,
+ )
+ return bboxes_center
+
+
+def _corners_to_center_format_tf(bboxes_corners: "tf.Tensor") -> "tf.Tensor":
+ top_left_x, top_left_y, bottom_right_x, bottom_right_y = tf.unstack(bboxes_corners, axis=-1)
+ bboxes_center = tf.stack(
+ [
+ (top_left_x + bottom_right_x) / 2, # center x
+ (top_left_y + bottom_right_y) / 2, # center y
+ (bottom_right_x - top_left_x), # width
+ (bottom_right_y - top_left_y), # height
+ ],
+ axis=-1,
+ )
+ return bboxes_center
+
+
+def corners_to_center_format(bboxes_corners: TensorType) -> TensorType:
+ """
+ Converts bounding boxes from corners format to center format.
+
+ corners format: contains the coordinates for the top-left and bottom-right corners of the box
+ (top_left_x, top_left_y, bottom_right_x, bottom_right_y)
+ center format: contains the coordinate for the center of the box and its the width, height dimensions
+ (center_x, center_y, width, height)
+ """
+ # Inverse function accepts different input types so implemented here too
+ if is_torch_tensor(bboxes_corners):
+ return _corners_to_center_format_torch(bboxes_corners)
+ elif isinstance(bboxes_corners, np.ndarray):
+ return _corners_to_center_format_numpy(bboxes_corners)
+ elif is_tf_tensor(bboxes_corners):
+ return _corners_to_center_format_tf(bboxes_corners)
+
+ raise ValueError(f"Unsupported input type {type(bboxes_corners)}")
+
+
+# 2 functions below copied from https://github.com/cocodataset/panopticapi/blob/master/panopticapi/utils.py
+# Copyright (c) 2018, Alexander Kirillov
+# All rights reserved.
+def rgb_to_id(color):
+ """
+ Converts RGB color to unique ID.
+ """
+ if isinstance(color, np.ndarray) and len(color.shape) == 3:
+ if color.dtype == np.uint8:
+ color = color.astype(np.int32)
+ return color[:, :, 0] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 2]
+ return int(color[0] + 256 * color[1] + 256 * 256 * color[2])
+
+
+def id_to_rgb(id_map):
+ """
+ Converts unique ID to RGB color.
+ """
+ if isinstance(id_map, np.ndarray):
+ id_map_copy = id_map.copy()
+ rgb_shape = tuple(list(id_map.shape) + [3])
+ rgb_map = np.zeros(rgb_shape, dtype=np.uint8)
+ for i in range(3):
+ rgb_map[..., i] = id_map_copy % 256
+ id_map_copy //= 256
+ return rgb_map
+ color = []
+ for _ in range(3):
+ color.append(id_map % 256)
+ id_map //= 256
+ return color
+
+
+class PaddingMode(ExplicitEnum):
+ """
+ Enum class for the different padding modes to use when padding images.
+ """
+
+ CONSTANT = "constant"
+ REFLECT = "reflect"
+ REPLICATE = "replicate"
+ SYMMETRIC = "symmetric"
+
+
+def pad(
+ image: np.ndarray,
+ padding: Union[int, Tuple[int, int], Iterable[Tuple[int, int]]],
+ mode: PaddingMode = PaddingMode.CONSTANT,
+ constant_values: Union[float, Iterable[float]] = 0.0,
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> np.ndarray:
+ """
+ Pads the `image` with the specified (height, width) `padding` and `mode`.
+
+ Args:
+ image (`np.ndarray`):
+ The image to pad.
+ padding (`int` or `Tuple[int, int]` or `Iterable[Tuple[int, int]]`):
+ Padding to apply to the edges of the height, width axes. Can be one of three formats:
+ - `((before_height, after_height), (before_width, after_width))` unique pad widths for each axis.
+ - `((before, after),)` yields same before and after pad for height and width.
+ - `(pad,)` or int is a shortcut for before = after = pad width for all axes.
+ mode (`PaddingMode`):
+ The padding mode to use. Can be one of:
+ - `"constant"`: pads with a constant value.
+ - `"reflect"`: pads with the reflection of the vector mirrored on the first and last values of the
+ vector along each axis.
+ - `"replicate"`: pads with the replication of the last value on the edge of the array along each axis.
+ - `"symmetric"`: pads with the reflection of the vector mirrored along the edge of the array.
+ constant_values (`float` or `Iterable[float]`, *optional*):
+ The value to use for the padding if `mode` is `"constant"`.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the output image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ If unset, will use same as the input image.
+ input_data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ If unset, will use the inferred format of the input image.
+
+ Returns:
+ `np.ndarray`: The padded image.
+
+ """
+ if input_data_format is None:
+ input_data_format = infer_channel_dimension_format(image)
+
+ def _expand_for_data_format(values):
+ """
+ Convert values to be in the format expected by np.pad based on the data format.
+ """
+ if isinstance(values, (int, float)):
+ values = ((values, values), (values, values))
+ elif isinstance(values, tuple) and len(values) == 1:
+ values = ((values[0], values[0]), (values[0], values[0]))
+ elif isinstance(values, tuple) and len(values) == 2 and isinstance(values[0], int):
+ values = (values, values)
+ elif isinstance(values, tuple) and len(values) == 2 and isinstance(values[0], tuple):
+ values = values
+ else:
+ raise ValueError(f"Unsupported format: {values}")
+
+ # add 0 for channel dimension
+ values = ((0, 0), *values) if input_data_format == ChannelDimension.FIRST else (*values, (0, 0))
+
+ # Add additional padding if there's a batch dimension
+ values = (0, *values) if image.ndim == 4 else values
+ return values
+
+ padding = _expand_for_data_format(padding)
+
+ if mode == PaddingMode.CONSTANT:
+ constant_values = _expand_for_data_format(constant_values)
+ image = np.pad(image, padding, mode="constant", constant_values=constant_values)
+ elif mode == PaddingMode.REFLECT:
+ image = np.pad(image, padding, mode="reflect")
+ elif mode == PaddingMode.REPLICATE:
+ image = np.pad(image, padding, mode="edge")
+ elif mode == PaddingMode.SYMMETRIC:
+ image = np.pad(image, padding, mode="symmetric")
+ else:
+ raise ValueError(f"Invalid padding mode: {mode}")
+
+ image = to_channel_dimension_format(image, data_format, input_data_format) if data_format is not None else image
+ return image
+
+
+# TODO (Amy): Accept 1/3/4 channel numpy array as input and return np.array as default
+def convert_to_rgb(image: ImageInput) -> ImageInput:
+ """
+ Converts an image to RGB format. Only converts if the image is of type PIL.Image.Image, otherwise returns the image
+ as is.
+ Args:
+ image (Image):
+ The image to convert.
+ """
+ requires_backends(convert_to_rgb, ["vision"])
+
+ if not isinstance(image, PIL.Image.Image):
+ return image
+
+ if image.mode == "RGB":
+ return image
+
+ image = image.convert("RGB")
+ return image
+
+
+def flip_channel_order(
+ image: np.ndarray,
+ data_format: Optional[ChannelDimension] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> np.ndarray:
+ """
+ Flips the channel order of the image.
+
+ If the image is in RGB format, it will be converted to BGR and vice versa.
+
+ Args:
+ image (`np.ndarray`):
+ The image to flip.
+ data_format (`ChannelDimension`, *optional*):
+ The channel dimension format for the output image. Can be one of:
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ If unset, will use same as the input image.
+ input_data_format (`ChannelDimension`, *optional*):
+ The channel dimension format for the input image. Can be one of:
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ If unset, will use the inferred format of the input image.
+ """
+ input_data_format = infer_channel_dimension_format(image) if input_data_format is None else input_data_format
+
+ if input_data_format == ChannelDimension.LAST:
+ image = image[..., ::-1]
+ elif input_data_format == ChannelDimension.FIRST:
+ image = image[::-1, ...]
+ else:
+ raise ValueError(f"Unsupported channel dimension: {input_data_format}")
+
+ if data_format is not None:
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
+ return image
+
+
+def _cast_tensor_to_float(x):
+ if x.is_floating_point():
+ return x
+ return x.float()
+
+
+def group_images_by_shape(
+ images: List["torch.Tensor"],
+) -> Tuple[Dict[Tuple[int, int], List["torch.Tensor"]], Dict[int, Tuple[Tuple[int, int], int]]]:
+ """
+ Groups images by shape.
+ Returns a dictionary with the shape as key and a list of images with that shape as value,
+ and a dictionary with the index of the image in the original list as key and the shape and index in the grouped list as value.
+ """
+ grouped_images = {}
+ grouped_images_index = {}
+ for i, image in enumerate(images):
+ shape = image.shape[1:]
+ if shape not in grouped_images:
+ grouped_images[shape] = []
+ grouped_images[shape].append(image)
+ grouped_images_index[i] = (shape, len(grouped_images[shape]) - 1)
+ # stack images with the same shape
+ grouped_images = {shape: torch.stack(images, dim=0) for shape, images in grouped_images.items()}
+ return grouped_images, grouped_images_index
+
+
+def reorder_images(
+ processed_images: Dict[Tuple[int, int], "torch.Tensor"], grouped_images_index: Dict[int, Tuple[int, int]]
+) -> List["torch.Tensor"]:
+ """
+ Reconstructs a list of images in the original order.
+ """
+ return [
+ processed_images[grouped_images_index[i][0]][grouped_images_index[i][1]]
+ for i in range(len(grouped_images_index))
+ ]
+
+
+class NumpyToTensor:
+ """
+ Convert a numpy array to a PyTorch tensor.
+ """
+
+ def __call__(self, image: np.ndarray):
+ # Same as in PyTorch, we assume incoming numpy images are in HWC format
+ # c.f. https://github.com/pytorch/vision/blob/61d97f41bc209e1407dcfbd685d2ee2da9c1cdad/torchvision/transforms/functional.py#L154
+ return torch.from_numpy(image.transpose(2, 0, 1)).contiguous()
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/image_utils.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/image_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..bde61e3803b57065e8d732644041d5775ea49807
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/image_utils.py
@@ -0,0 +1,1345 @@
+# 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 base64
+import os
+from contextlib import redirect_stdout
+from dataclasses import dataclass
+from io import BytesIO
+from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Optional, Tuple, Union
+
+import numpy as np
+import requests
+from packaging import version
+
+from .utils import (
+ ExplicitEnum,
+ is_av_available,
+ is_cv2_available,
+ is_decord_available,
+ is_jax_tensor,
+ is_numpy_array,
+ is_tf_tensor,
+ is_torch_available,
+ is_torch_tensor,
+ is_torchvision_available,
+ is_vision_available,
+ is_yt_dlp_available,
+ logging,
+ requires_backends,
+ to_numpy,
+)
+from .utils.constants import ( # noqa: F401
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ IMAGENET_STANDARD_MEAN,
+ IMAGENET_STANDARD_STD,
+ OPENAI_CLIP_MEAN,
+ OPENAI_CLIP_STD,
+)
+
+
+if is_vision_available():
+ import PIL.Image
+ import PIL.ImageOps
+
+ if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
+ PILImageResampling = PIL.Image.Resampling
+ else:
+ PILImageResampling = PIL.Image
+
+ if is_torchvision_available():
+ from torchvision import io as torchvision_io
+ from torchvision.transforms import InterpolationMode
+
+ pil_torch_interpolation_mapping = {
+ PILImageResampling.NEAREST: InterpolationMode.NEAREST,
+ PILImageResampling.BOX: InterpolationMode.BOX,
+ PILImageResampling.BILINEAR: InterpolationMode.BILINEAR,
+ PILImageResampling.HAMMING: InterpolationMode.HAMMING,
+ PILImageResampling.BICUBIC: InterpolationMode.BICUBIC,
+ PILImageResampling.LANCZOS: InterpolationMode.LANCZOS,
+ }
+
+
+if TYPE_CHECKING:
+ if is_torch_available():
+ import torch
+
+
+logger = logging.get_logger(__name__)
+
+
+ImageInput = Union[
+ "PIL.Image.Image", np.ndarray, "torch.Tensor", List["PIL.Image.Image"], List[np.ndarray], List["torch.Tensor"]
+] # noqa
+
+
+VideoInput = Union[
+ List["PIL.Image.Image"],
+ "np.ndarray",
+ "torch.Tensor",
+ List["np.ndarray"],
+ List["torch.Tensor"],
+ List[List["PIL.Image.Image"]],
+ List[List["np.ndarrray"]],
+ List[List["torch.Tensor"]],
+] # noqa
+
+
+class ChannelDimension(ExplicitEnum):
+ FIRST = "channels_first"
+ LAST = "channels_last"
+
+
+class AnnotationFormat(ExplicitEnum):
+ COCO_DETECTION = "coco_detection"
+ COCO_PANOPTIC = "coco_panoptic"
+
+
+class AnnotionFormat(ExplicitEnum):
+ COCO_DETECTION = AnnotationFormat.COCO_DETECTION.value
+ COCO_PANOPTIC = AnnotationFormat.COCO_PANOPTIC.value
+
+
+@dataclass
+class VideoMetadata:
+ total_num_frames: int
+ fps: float
+ duration: float
+ video_backend: str
+
+
+AnnotationType = Dict[str, Union[int, str, List[Dict]]]
+
+
+def is_pil_image(img):
+ return is_vision_available() and isinstance(img, PIL.Image.Image)
+
+
+class ImageType(ExplicitEnum):
+ PIL = "pillow"
+ TORCH = "torch"
+ NUMPY = "numpy"
+ TENSORFLOW = "tensorflow"
+ JAX = "jax"
+
+
+def get_image_type(image):
+ if is_pil_image(image):
+ return ImageType.PIL
+ if is_torch_tensor(image):
+ return ImageType.TORCH
+ if is_numpy_array(image):
+ return ImageType.NUMPY
+ if is_tf_tensor(image):
+ return ImageType.TENSORFLOW
+ if is_jax_tensor(image):
+ return ImageType.JAX
+ raise ValueError(f"Unrecognised image type {type(image)}")
+
+
+def is_valid_image(img):
+ return is_pil_image(img) or is_numpy_array(img) or is_torch_tensor(img) or is_tf_tensor(img) or is_jax_tensor(img)
+
+
+def is_valid_list_of_images(images: List):
+ return images and all(is_valid_image(image) for image in images)
+
+
+def valid_images(imgs):
+ # If we have an list of images, make sure every image is valid
+ if isinstance(imgs, (list, tuple)):
+ for img in imgs:
+ if not valid_images(img):
+ return False
+ # If not a list of tuple, we have been given a single image or batched tensor of images
+ elif not is_valid_image(imgs):
+ return False
+ return True
+
+
+def is_batched(img):
+ if isinstance(img, (list, tuple)):
+ return is_valid_image(img[0])
+ return False
+
+
+def is_scaled_image(image: np.ndarray) -> bool:
+ """
+ Checks to see whether the pixel values have already been rescaled to [0, 1].
+ """
+ if image.dtype == np.uint8:
+ return False
+
+ # It's possible the image has pixel values in [0, 255] but is of floating type
+ return np.min(image) >= 0 and np.max(image) <= 1
+
+
+def make_list_of_images(images, expected_ndims: int = 3) -> List[ImageInput]:
+ """
+ Ensure that the output is a list of images. If the input is a single image, it is converted to a list of length 1.
+ If the input is a batch of images, it is converted to a list of images.
+
+ Args:
+ images (`ImageInput`):
+ Image of images to turn into a list of images.
+ expected_ndims (`int`, *optional*, defaults to 3):
+ Expected number of dimensions for a single input image. If the input image has a different number of
+ dimensions, an error is raised.
+ """
+ if is_batched(images):
+ return images
+
+ # Either the input is a single image, in which case we create a list of length 1
+ if is_pil_image(images):
+ # PIL images are never batched
+ return [images]
+
+ if is_valid_image(images):
+ if images.ndim == expected_ndims + 1:
+ # Batch of images
+ images = list(images)
+ elif images.ndim == expected_ndims:
+ # Single image
+ images = [images]
+ else:
+ raise ValueError(
+ f"Invalid image shape. Expected either {expected_ndims + 1} or {expected_ndims} dimensions, but got"
+ f" {images.ndim} dimensions."
+ )
+ return images
+ raise ValueError(
+ "Invalid image type. Expected either PIL.Image.Image, numpy.ndarray, torch.Tensor, tf.Tensor or "
+ f"jax.ndarray, but got {type(images)}."
+ )
+
+
+def make_flat_list_of_images(
+ images: Union[List[ImageInput], ImageInput],
+) -> ImageInput:
+ """
+ Ensure that the output is a flat list of images. If the input is a single image, it is converted to a list of length 1.
+ If the input is a nested list of images, it is converted to a flat list of images.
+ Args:
+ images (`Union[List[ImageInput], ImageInput]`):
+ The input image.
+ Returns:
+ list: A list of images or a 4d array of images.
+ """
+ # If the input is a nested list of images, we flatten it
+ if (
+ isinstance(images, (list, tuple))
+ and all(isinstance(images_i, (list, tuple)) for images_i in images)
+ and all(is_valid_list_of_images(images_i) for images_i in images)
+ ):
+ return [img for img_list in images for img in img_list]
+
+ if isinstance(images, (list, tuple)) and is_valid_list_of_images(images):
+ if is_pil_image(images[0]) or images[0].ndim == 3:
+ return images
+ if images[0].ndim == 4:
+ return [img for img_list in images for img in img_list]
+
+ if is_valid_image(images):
+ if is_pil_image(images) or images.ndim == 3:
+ return [images]
+ if images.ndim == 4:
+ return list(images)
+
+ raise ValueError(f"Could not make a flat list of images from {images}")
+
+
+def make_nested_list_of_images(
+ images: Union[List[ImageInput], ImageInput],
+) -> ImageInput:
+ """
+ Ensure that the output is a nested list of images.
+ Args:
+ images (`Union[List[ImageInput], ImageInput]`):
+ The input image.
+ Returns:
+ list: A list of list of images or a list of 4d array of images.
+ """
+ # If it's a list of batches, it's already in the right format
+ if (
+ isinstance(images, (list, tuple))
+ and all(isinstance(images_i, (list, tuple)) for images_i in images)
+ and all(is_valid_list_of_images(images_i) for images_i in images)
+ ):
+ return images
+
+ # If it's a list of images, it's a single batch, so convert it to a list of lists
+ if isinstance(images, (list, tuple)) and is_valid_list_of_images(images):
+ if is_pil_image(images[0]) or images[0].ndim == 3:
+ return [images]
+ if images[0].ndim == 4:
+ return [list(image) for image in images]
+
+ # If it's a single image, convert it to a list of lists
+ if is_valid_image(images):
+ if is_pil_image(images) or images.ndim == 3:
+ return [[images]]
+ if images.ndim == 4:
+ return [list(images)]
+
+ raise ValueError("Invalid input type. Must be a single image, a list of images, or a list of batches of images.")
+
+
+def make_batched_videos(videos) -> VideoInput:
+ """
+ Ensure that the input is a list of videos.
+ Args:
+ videos (`VideoInput`):
+ Video or videos to turn into a list of videos.
+ Returns:
+ list: A list of videos.
+ """
+ if isinstance(videos, (list, tuple)) and isinstance(videos[0], (list, tuple)) and is_valid_image(videos[0][0]):
+ # case 1: nested batch of videos so we flatten it
+ if not is_pil_image(videos[0][0]) and videos[0][0].ndim == 4:
+ videos = [[video for batch_list in batched_videos for video in batch_list] for batched_videos in videos]
+ # case 2: list of videos represented as list of video frames
+ return videos
+
+ elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
+ if is_pil_image(videos[0]) or videos[0].ndim == 3:
+ return [videos]
+ elif videos[0].ndim == 4:
+ return [list(video) for video in videos]
+
+ elif is_valid_image(videos):
+ if is_pil_image(videos) or videos.ndim == 3:
+ return [[videos]]
+ elif videos.ndim == 4:
+ return [list(videos)]
+
+ raise ValueError(f"Could not make batched video from {videos}")
+
+
+def to_numpy_array(img) -> np.ndarray:
+ if not is_valid_image(img):
+ raise ValueError(f"Invalid image type: {type(img)}")
+
+ if is_vision_available() and isinstance(img, PIL.Image.Image):
+ return np.array(img)
+ return to_numpy(img)
+
+
+def infer_channel_dimension_format(
+ image: np.ndarray, num_channels: Optional[Union[int, Tuple[int, ...]]] = None
+) -> ChannelDimension:
+ """
+ Infers the channel dimension format of `image`.
+
+ Args:
+ image (`np.ndarray`):
+ The image to infer the channel dimension of.
+ num_channels (`int` or `Tuple[int, ...]`, *optional*, defaults to `(1, 3)`):
+ The number of channels of the image.
+
+ Returns:
+ The channel dimension of the image.
+ """
+ num_channels = num_channels if num_channels is not None else (1, 3)
+ num_channels = (num_channels,) if isinstance(num_channels, int) else num_channels
+
+ if image.ndim == 3:
+ first_dim, last_dim = 0, 2
+ elif image.ndim == 4:
+ first_dim, last_dim = 1, 3
+ else:
+ raise ValueError(f"Unsupported number of image dimensions: {image.ndim}")
+
+ if image.shape[first_dim] in num_channels and image.shape[last_dim] in num_channels:
+ logger.warning(
+ f"The channel dimension is ambiguous. Got image shape {image.shape}. Assuming channels are the first dimension."
+ )
+ return ChannelDimension.FIRST
+ elif image.shape[first_dim] in num_channels:
+ return ChannelDimension.FIRST
+ elif image.shape[last_dim] in num_channels:
+ return ChannelDimension.LAST
+ raise ValueError("Unable to infer channel dimension format")
+
+
+def get_channel_dimension_axis(
+ image: np.ndarray, input_data_format: Optional[Union[ChannelDimension, str]] = None
+) -> int:
+ """
+ Returns the channel dimension axis of the image.
+
+ Args:
+ image (`np.ndarray`):
+ The image to get the channel dimension axis of.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format of the image. If `None`, will infer the channel dimension from the image.
+
+ Returns:
+ The channel dimension axis of the image.
+ """
+ if input_data_format is None:
+ input_data_format = infer_channel_dimension_format(image)
+ if input_data_format == ChannelDimension.FIRST:
+ return image.ndim - 3
+ elif input_data_format == ChannelDimension.LAST:
+ return image.ndim - 1
+ raise ValueError(f"Unsupported data format: {input_data_format}")
+
+
+def get_image_size(image: np.ndarray, channel_dim: ChannelDimension = None) -> Tuple[int, int]:
+ """
+ Returns the (height, width) dimensions of the image.
+
+ Args:
+ image (`np.ndarray`):
+ The image to get the dimensions of.
+ channel_dim (`ChannelDimension`, *optional*):
+ Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the image.
+
+ Returns:
+ A tuple of the image's height and width.
+ """
+ if channel_dim is None:
+ channel_dim = infer_channel_dimension_format(image)
+
+ if channel_dim == ChannelDimension.FIRST:
+ return image.shape[-2], image.shape[-1]
+ elif channel_dim == ChannelDimension.LAST:
+ return image.shape[-3], image.shape[-2]
+ else:
+ raise ValueError(f"Unsupported data format: {channel_dim}")
+
+
+def get_image_size_for_max_height_width(
+ image_size: Tuple[int, int],
+ max_height: int,
+ max_width: int,
+) -> Tuple[int, int]:
+ """
+ Computes the output image size given the input image and the maximum allowed height and width. Keep aspect ratio.
+ Important, even if image_height < max_height and image_width < max_width, the image will be resized
+ to at least one of the edges be equal to max_height or max_width.
+
+ For example:
+ - input_size: (100, 200), max_height: 50, max_width: 50 -> output_size: (25, 50)
+ - input_size: (100, 200), max_height: 200, max_width: 500 -> output_size: (200, 400)
+
+ Args:
+ image_size (`Tuple[int, int]`):
+ The image to resize.
+ max_height (`int`):
+ The maximum allowed height.
+ max_width (`int`):
+ The maximum allowed width.
+ """
+ height, width = image_size
+ height_scale = max_height / height
+ width_scale = max_width / width
+ min_scale = min(height_scale, width_scale)
+ new_height = int(height * min_scale)
+ new_width = int(width * min_scale)
+ return new_height, new_width
+
+
+def is_valid_annotation_coco_detection(annotation: Dict[str, Union[List, Tuple]]) -> bool:
+ if (
+ isinstance(annotation, dict)
+ and "image_id" in annotation
+ and "annotations" in annotation
+ and isinstance(annotation["annotations"], (list, tuple))
+ and (
+ # an image can have no annotations
+ len(annotation["annotations"]) == 0 or isinstance(annotation["annotations"][0], dict)
+ )
+ ):
+ return True
+ return False
+
+
+def is_valid_annotation_coco_panoptic(annotation: Dict[str, Union[List, Tuple]]) -> bool:
+ if (
+ isinstance(annotation, dict)
+ and "image_id" in annotation
+ and "segments_info" in annotation
+ and "file_name" in annotation
+ and isinstance(annotation["segments_info"], (list, tuple))
+ and (
+ # an image can have no segments
+ len(annotation["segments_info"]) == 0 or isinstance(annotation["segments_info"][0], dict)
+ )
+ ):
+ return True
+ return False
+
+
+def valid_coco_detection_annotations(annotations: Iterable[Dict[str, Union[List, Tuple]]]) -> bool:
+ return all(is_valid_annotation_coco_detection(ann) for ann in annotations)
+
+
+def valid_coco_panoptic_annotations(annotations: Iterable[Dict[str, Union[List, Tuple]]]) -> bool:
+ return all(is_valid_annotation_coco_panoptic(ann) for ann in annotations)
+
+
+def load_image(image: Union[str, "PIL.Image.Image"], timeout: Optional[float] = None) -> "PIL.Image.Image":
+ """
+ Loads `image` to a PIL Image.
+
+ Args:
+ image (`str` or `PIL.Image.Image`):
+ The image to convert to the PIL Image format.
+ timeout (`float`, *optional*):
+ The timeout value in seconds for the URL request.
+
+ Returns:
+ `PIL.Image.Image`: A PIL Image.
+ """
+ requires_backends(load_image, ["vision"])
+ if isinstance(image, str):
+ if image.startswith("http://") or image.startswith("https://"):
+ # We need to actually check for a real protocol, otherwise it's impossible to use a local file
+ # like http_huggingface_co.png
+ image = PIL.Image.open(BytesIO(requests.get(image, timeout=timeout).content))
+ elif os.path.isfile(image):
+ image = PIL.Image.open(image)
+ else:
+ if image.startswith("data:image/"):
+ image = image.split(",")[1]
+
+ # Try to load as base64
+ try:
+ b64 = base64.decodebytes(image.encode())
+ image = PIL.Image.open(BytesIO(b64))
+ except Exception as e:
+ raise ValueError(
+ f"Incorrect image source. Must be a valid URL starting with `http://` or `https://`, a valid path to an image file, or a base64 encoded string. Got {image}. Failed with {e}"
+ )
+ elif isinstance(image, PIL.Image.Image):
+ image = image
+ else:
+ raise TypeError(
+ "Incorrect format used for image. Should be an url linking to an image, a base64 string, a local path, or a PIL image."
+ )
+ image = PIL.ImageOps.exif_transpose(image)
+ image = image.convert("RGB")
+ return image
+
+
+def default_sample_indices_fn(metadata: VideoMetadata, num_frames=None, fps=None, **kwargs):
+ """
+ A default sampling function that replicates the logic used in get_uniform_frame_indices,
+ while optionally handling `fps` if `num_frames` is not provided.
+
+ Args:
+ metadata (`VideoMetadata`):
+ `VideoMetadata` object containing metadata about the video, such as "total_num_frames" or "fps".
+ num_frames (`int`, *optional*):
+ Number of frames to sample uniformly.
+ fps (`int`, *optional*):
+ Desired frames per second. Takes priority over num_frames if both are provided.
+
+ Returns:
+ `np.ndarray`: Array of frame indices to sample.
+ """
+ total_num_frames = metadata.total_num_frames
+ video_fps = metadata.fps
+
+ # If num_frames is not given but fps is, calculate num_frames from fps
+ if num_frames is None and fps is not None:
+ num_frames = int(total_num_frames / video_fps * fps)
+ if num_frames > total_num_frames:
+ raise ValueError(
+ f"When loading the video with fps={fps}, we computed num_frames={num_frames} "
+ f"which exceeds total_num_frames={total_num_frames}. Check fps or video metadata."
+ )
+
+ if num_frames is not None:
+ indices = np.arange(0, total_num_frames, total_num_frames / num_frames, dtype=int)
+ else:
+ indices = np.arange(0, total_num_frames, dtype=int)
+ return indices
+
+
+def read_video_opencv(
+ video_path: str,
+ sample_indices_fn: Callable,
+ **kwargs,
+):
+ """
+ Decode a video using the OpenCV backend.
+
+ Args:
+ video_path (`str`):
+ Path to the video file.
+ sample_indices_fn (`Callable`):
+ A callable function that will return indices at which the video should be sampled. If the video has to be loaded using
+ by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`.
+ If not provided, simple uniform sampling with fps is performed.
+ Example:
+ def sample_indices_fn(metadata, **kwargs):
+ return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int)
+
+ Returns:
+ Tuple[`np.array`, `VideoMetadata`]: A tuple containing:
+ - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
+ - `VideoMetadata` object.
+ """
+ # Lazy import cv2
+ requires_backends(read_video_opencv, ["cv2"])
+ import cv2
+
+ video = cv2.VideoCapture(video_path)
+ total_num_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
+ video_fps = video.get(cv2.CAP_PROP_FPS)
+ duration = total_num_frames / video_fps if video_fps else 0
+ metadata = VideoMetadata(
+ total_num_frames=int(total_num_frames), fps=float(video_fps), duration=float(duration), video_backend="opencv"
+ )
+ indices = sample_indices_fn(metadata=metadata, **kwargs)
+
+ index = 0
+ frames = []
+ while video.isOpened():
+ success, frame = video.read()
+ if not success:
+ break
+ if index in indices:
+ height, width, channel = frame.shape
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
+ frames.append(frame[0:height, 0:width, 0:channel])
+ if success:
+ index += 1
+ if index >= total_num_frames:
+ break
+
+ video.release()
+ metadata.frames_indices = indices
+ return np.stack(frames), metadata
+
+
+def read_video_decord(
+ video_path: str,
+ sample_indices_fn: Optional[Callable] = None,
+ **kwargs,
+):
+ """
+ Decode a video using the Decord backend.
+
+ Args:
+ video_path (`str`):
+ Path to the video file.
+ sample_indices_fn (`Callable`, *optional*):
+ A callable function that will return indices at which the video should be sampled. If the video has to be loaded using
+ by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`.
+ If not provided, simple uniform sampling with fps is performed.
+ Example:
+ def sample_indices_fn(metadata, **kwargs):
+ return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int)
+
+ Returns:
+ Tuple[`np.array`, `VideoMetadata`]: A tuple containing:
+ - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
+ - `VideoMetadata` object.
+ """
+ # Lazy import from decord
+ requires_backends(read_video_decord, ["decord"])
+ from decord import VideoReader, cpu
+
+ vr = VideoReader(uri=video_path, ctx=cpu(0)) # decord has problems with gpu
+ video_fps = vr.get_avg_fps()
+ total_num_frames = len(vr)
+ duration = total_num_frames / video_fps if video_fps else 0
+ metadata = VideoMetadata(
+ total_num_frames=int(total_num_frames), fps=float(video_fps), duration=float(duration), video_backend="decord"
+ )
+
+ indices = sample_indices_fn(metadata=metadata, **kwargs)
+
+ frames = vr.get_batch(indices).asnumpy()
+ metadata.frames_indices = indices
+ return frames, metadata
+
+
+def read_video_pyav(
+ video_path: str,
+ sample_indices_fn: Callable,
+ **kwargs,
+):
+ """
+ Decode the video with PyAV decoder.
+
+ Args:
+ video_path (`str`):
+ Path to the video file.
+ sample_indices_fn (`Callable`, *optional*):
+ A callable function that will return indices at which the video should be sampled. If the video has to be loaded using
+ by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`.
+ If not provided, simple uniform sampling with fps is performed.
+ Example:
+ def sample_indices_fn(metadata, **kwargs):
+ return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int)
+
+ Returns:
+ Tuple[`np.array`, `VideoMetadata`]: A tuple containing:
+ - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
+ - `VideoMetadata` object.
+ """
+ # Lazy import av
+ requires_backends(read_video_pyav, ["av"])
+ import av
+
+ container = av.open(video_path)
+ total_num_frames = container.streams.video[0].frames
+ video_fps = container.streams.video[0].average_rate # should we better use `av_guess_frame_rate`?
+ duration = total_num_frames / video_fps if video_fps else 0
+ metadata = VideoMetadata(
+ total_num_frames=int(total_num_frames), fps=float(video_fps), duration=float(duration), video_backend="pyav"
+ )
+ indices = sample_indices_fn(metadata=metadata, **kwargs)
+
+ frames = []
+ container.seek(0)
+ end_index = indices[-1]
+ for i, frame in enumerate(container.decode(video=0)):
+ if i > end_index:
+ break
+ if i >= 0 and i in indices:
+ frames.append(frame)
+
+ video = np.stack([x.to_ndarray(format="rgb24") for x in frames])
+ metadata.frames_indices = indices
+ return video, metadata
+
+
+def read_video_torchvision(
+ video_path: str,
+ sample_indices_fn: Callable,
+ **kwargs,
+):
+ """
+ Decode the video with torchvision decoder.
+
+ Args:
+ video_path (`str`):
+ Path to the video file.
+ sample_indices_fn (`Callable`, *optional*):
+ A callable function that will return indices at which the video should be sampled. If the video has to be loaded using
+ by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`.
+ If not provided, simple uniform sampling with fps is performed.
+ Example:
+ def sample_indices_fn(metadata, **kwargs):
+ return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int)
+
+ Returns:
+ Tuple[`np.array`, `VideoMetadata`]: A tuple containing:
+ - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
+ - `VideoMetadata` object.
+ """
+ video, _, info = torchvision_io.read_video(
+ video_path,
+ start_pts=0.0,
+ end_pts=None,
+ pts_unit="sec",
+ output_format="THWC",
+ )
+ video_fps = info["video_fps"]
+ total_num_frames = video.size(0)
+ duration = total_num_frames / video_fps if video_fps else 0
+ metadata = VideoMetadata(
+ total_num_frames=int(total_num_frames),
+ fps=float(video_fps),
+ duration=float(duration),
+ video_backend="torchvision",
+ )
+
+ indices = sample_indices_fn(metadata=metadata, **kwargs)
+
+ video = video[indices].contiguous().numpy()
+ metadata.frames_indices = indices
+ return video, metadata
+
+
+VIDEO_DECODERS = {
+ "decord": read_video_decord,
+ "opencv": read_video_opencv,
+ "pyav": read_video_pyav,
+ "torchvision": read_video_torchvision,
+}
+
+
+def load_video(
+ video: Union[str, "VideoInput"],
+ num_frames: Optional[int] = None,
+ fps: Optional[int] = None,
+ backend: str = "opencv",
+ sample_indices_fn: Optional[Callable] = None,
+ **kwargs,
+) -> np.array:
+ """
+ Loads `video` to a numpy array.
+
+ Args:
+ video (`str` or `VideoInput`):
+ The video to convert to the numpy array format. Can be a link to video or local path.
+ num_frames (`int`, *optional*):
+ Number of frames to sample uniformly. If not passed, the whole video is loaded.
+ fps (`int`, *optional*):
+ Number of frames to sample per second. Should be passed only when `num_frames=None`.
+ If not specified and `num_frames==None`, all frames are sampled.
+ backend (`str`, *optional*, defaults to `"opencv"`):
+ The backend to use when loading the video. Can be any of ["decord", "pyav", "opencv", "torchvision"]. Defaults to "opencv".
+ sample_indices_fn (`Callable`, *optional*):
+ A callable function that will return indices at which the video should be sampled. If the video has to be loaded using
+ by a different sampling technique than provided by `num_frames` or `fps` arguments, one should provide their own `sample_indices_fn`.
+ If not provided, simple uniformt sampling with fps is performed, otherwise `sample_indices_fn` has priority over other args.
+ The function expects at input the all args along with all kwargs passed to `load_video` and should output valid
+ indices at which the video should be sampled. For example:
+
+ Example:
+ def sample_indices_fn(metadata, **kwargs):
+ return np.linspace(0, metadata.total_num_frames - 1, num_frames, dtype=int)
+
+ Returns:
+ Tuple[`np.array`, Dict]: A tuple containing:
+ - Numpy array of frames in RGB (shape: [num_frames, height, width, 3]).
+ - Metadata dictionary.
+ """
+
+ # If `sample_indices_fn` is given, we can accept any args as those might be needed by custom `sample_indices_fn`
+ if fps is not None and num_frames is not None and sample_indices_fn is None:
+ raise ValueError(
+ "`num_frames`, `fps`, and `sample_indices_fn` are mutually exclusive arguments, please use only one!"
+ )
+
+ # If user didn't pass a sampling function, create one on the fly with default logic
+ if sample_indices_fn is None:
+
+ def sample_indices_fn_func(metadata, **fn_kwargs):
+ return default_sample_indices_fn(metadata, num_frames=num_frames, fps=fps, **fn_kwargs)
+
+ sample_indices_fn = sample_indices_fn_func
+
+ if video.startswith("https://www.youtube.com") or video.startswith("http://www.youtube.com"):
+ if not is_yt_dlp_available():
+ raise ImportError("To load a video from YouTube url you have to install `yt_dlp` first.")
+ # Lazy import from yt_dlp
+ requires_backends(load_video, ["yt_dlp"])
+ from yt_dlp import YoutubeDL
+
+ buffer = BytesIO()
+ with redirect_stdout(buffer), YoutubeDL() as f:
+ f.download([video])
+ bytes_obj = buffer.getvalue()
+ file_obj = BytesIO(bytes_obj)
+ elif video.startswith("http://") or video.startswith("https://"):
+ file_obj = BytesIO(requests.get(video).content)
+ elif os.path.isfile(video):
+ file_obj = video
+ elif is_valid_image(video) or (isinstance(video, (list, tuple)) and is_valid_image(video[0])):
+ file_obj = None
+ else:
+ raise TypeError("Incorrect format used for video. Should be an url linking to an video or a local path.")
+
+ # can also load with decord, but not cv2/torchvision
+ # both will fail in case of url links
+ video_is_url = video.startswith("http://") or video.startswith("https://")
+ if video_is_url and backend in ["opencv", "torchvision"]:
+ raise ValueError(
+ "If you are trying to load a video from URL, you can decode the video only with `pyav` or `decord` as backend"
+ )
+
+ if file_obj is None:
+ return video
+
+ if (
+ (not is_decord_available() and backend == "decord")
+ or (not is_av_available() and backend == "pyav")
+ or (not is_cv2_available() and backend == "opencv")
+ or (not is_torchvision_available() and backend == "torchvision")
+ ):
+ raise ImportError(
+ f"You chose backend={backend} for loading the video but the required library is not found in your environment "
+ f"Make sure to install {backend} before loading the video."
+ )
+
+ video_decoder = VIDEO_DECODERS[backend]
+ video, metadata = video_decoder(file_obj, sample_indices_fn, **kwargs)
+ return video, metadata
+
+
+def load_images(
+ images: Union[List, Tuple, str, "PIL.Image.Image"], timeout: Optional[float] = None
+) -> Union["PIL.Image.Image", List["PIL.Image.Image"], List[List["PIL.Image.Image"]]]:
+ """Loads images, handling different levels of nesting.
+
+ Args:
+ images: A single image, a list of images, or a list of lists of images to load.
+ timeout: Timeout for loading images.
+
+ Returns:
+ A single image, a list of images, a list of lists of images.
+ """
+ if isinstance(images, (list, tuple)):
+ if len(images) and isinstance(images[0], (list, tuple)):
+ return [[load_image(image, timeout=timeout) for image in image_group] for image_group in images]
+ else:
+ return [load_image(image, timeout=timeout) for image in images]
+ else:
+ return load_image(images, timeout=timeout)
+
+
+def validate_preprocess_arguments(
+ do_rescale: Optional[bool] = None,
+ rescale_factor: Optional[float] = None,
+ do_normalize: Optional[bool] = None,
+ image_mean: Optional[Union[float, List[float]]] = None,
+ image_std: Optional[Union[float, List[float]]] = None,
+ do_pad: Optional[bool] = None,
+ size_divisibility: Optional[int] = None,
+ do_center_crop: Optional[bool] = None,
+ crop_size: Optional[Dict[str, int]] = None,
+ do_resize: Optional[bool] = None,
+ size: Optional[Dict[str, int]] = None,
+ resample: Optional["PILImageResampling"] = None,
+):
+ """
+ Checks validity of typically used arguments in an `ImageProcessor` `preprocess` method.
+ Raises `ValueError` if arguments incompatibility is caught.
+ Many incompatibilities are model-specific. `do_pad` sometimes needs `size_divisor`,
+ sometimes `size_divisibility`, and sometimes `size`. New models and processors added should follow
+ existing arguments when possible.
+
+ """
+ if do_rescale and rescale_factor is None:
+ raise ValueError("`rescale_factor` must be specified if `do_rescale` is `True`.")
+
+ if do_pad and size_divisibility is None:
+ # Here, size_divisor might be passed as the value of size
+ raise ValueError(
+ "Depending on the model, `size_divisibility`, `size_divisor`, `pad_size` or `size` must be specified if `do_pad` is `True`."
+ )
+
+ if do_normalize and (image_mean is None or image_std is None):
+ raise ValueError("`image_mean` and `image_std` must both be specified if `do_normalize` is `True`.")
+
+ if do_center_crop and crop_size is None:
+ raise ValueError("`crop_size` must be specified if `do_center_crop` is `True`.")
+
+ if do_resize and (size is None or resample is None):
+ raise ValueError("`size` and `resample` must be specified if `do_resize` is `True`.")
+
+
+# In the future we can add a TF implementation here when we have TF models.
+class ImageFeatureExtractionMixin:
+ """
+ Mixin that contain utilities for preparing image features.
+ """
+
+ def _ensure_format_supported(self, image):
+ if not isinstance(image, (PIL.Image.Image, np.ndarray)) and not is_torch_tensor(image):
+ raise ValueError(
+ f"Got type {type(image)} which is not supported, only `PIL.Image.Image`, `np.array` and "
+ "`torch.Tensor` are."
+ )
+
+ def to_pil_image(self, image, rescale=None):
+ """
+ Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if
+ needed.
+
+ Args:
+ image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor`):
+ The image to convert to the PIL Image format.
+ rescale (`bool`, *optional*):
+ Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will
+ default to `True` if the image type is a floating type, `False` otherwise.
+ """
+ self._ensure_format_supported(image)
+
+ if is_torch_tensor(image):
+ image = image.numpy()
+
+ if isinstance(image, np.ndarray):
+ if rescale is None:
+ # rescale default to the array being of floating type.
+ rescale = isinstance(image.flat[0], np.floating)
+ # If the channel as been moved to first dim, we put it back at the end.
+ if image.ndim == 3 and image.shape[0] in [1, 3]:
+ image = image.transpose(1, 2, 0)
+ if rescale:
+ image = image * 255
+ image = image.astype(np.uint8)
+ return PIL.Image.fromarray(image)
+ return image
+
+ def convert_rgb(self, image):
+ """
+ Converts `PIL.Image.Image` to RGB format.
+
+ Args:
+ image (`PIL.Image.Image`):
+ The image to convert.
+ """
+ self._ensure_format_supported(image)
+ if not isinstance(image, PIL.Image.Image):
+ return image
+
+ return image.convert("RGB")
+
+ def rescale(self, image: np.ndarray, scale: Union[float, int]) -> np.ndarray:
+ """
+ Rescale a numpy image by scale amount
+ """
+ self._ensure_format_supported(image)
+ return image * scale
+
+ def to_numpy_array(self, image, rescale=None, channel_first=True):
+ """
+ Converts `image` to a numpy array. Optionally rescales it and puts the channel dimension as the first
+ dimension.
+
+ Args:
+ image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
+ The image to convert to a NumPy array.
+ rescale (`bool`, *optional*):
+ Whether or not to apply the scaling factor (to make pixel values floats between 0. and 1.). Will
+ default to `True` if the image is a PIL Image or an array/tensor of integers, `False` otherwise.
+ channel_first (`bool`, *optional*, defaults to `True`):
+ Whether or not to permute the dimensions of the image to put the channel dimension first.
+ """
+ self._ensure_format_supported(image)
+
+ if isinstance(image, PIL.Image.Image):
+ image = np.array(image)
+
+ if is_torch_tensor(image):
+ image = image.numpy()
+
+ rescale = isinstance(image.flat[0], np.integer) if rescale is None else rescale
+
+ if rescale:
+ image = self.rescale(image.astype(np.float32), 1 / 255.0)
+
+ if channel_first and image.ndim == 3:
+ image = image.transpose(2, 0, 1)
+
+ return image
+
+ def expand_dims(self, image):
+ """
+ Expands 2-dimensional `image` to 3 dimensions.
+
+ Args:
+ image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
+ The image to expand.
+ """
+ self._ensure_format_supported(image)
+
+ # Do nothing if PIL image
+ if isinstance(image, PIL.Image.Image):
+ return image
+
+ if is_torch_tensor(image):
+ image = image.unsqueeze(0)
+ else:
+ image = np.expand_dims(image, axis=0)
+ return image
+
+ def normalize(self, image, mean, std, rescale=False):
+ """
+ Normalizes `image` with `mean` and `std`. Note that this will trigger a conversion of `image` to a NumPy array
+ if it's a PIL Image.
+
+ Args:
+ image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
+ The image to normalize.
+ mean (`List[float]` or `np.ndarray` or `torch.Tensor`):
+ The mean (per channel) to use for normalization.
+ std (`List[float]` or `np.ndarray` or `torch.Tensor`):
+ The standard deviation (per channel) to use for normalization.
+ rescale (`bool`, *optional*, defaults to `False`):
+ Whether or not to rescale the image to be between 0 and 1. If a PIL image is provided, scaling will
+ happen automatically.
+ """
+ self._ensure_format_supported(image)
+
+ if isinstance(image, PIL.Image.Image):
+ image = self.to_numpy_array(image, rescale=True)
+ # If the input image is a PIL image, it automatically gets rescaled. If it's another
+ # type it may need rescaling.
+ elif rescale:
+ if isinstance(image, np.ndarray):
+ image = self.rescale(image.astype(np.float32), 1 / 255.0)
+ elif is_torch_tensor(image):
+ image = self.rescale(image.float(), 1 / 255.0)
+
+ if isinstance(image, np.ndarray):
+ if not isinstance(mean, np.ndarray):
+ mean = np.array(mean).astype(image.dtype)
+ if not isinstance(std, np.ndarray):
+ std = np.array(std).astype(image.dtype)
+ elif is_torch_tensor(image):
+ import torch
+
+ if not isinstance(mean, torch.Tensor):
+ if isinstance(mean, np.ndarray):
+ mean = torch.from_numpy(mean)
+ else:
+ mean = torch.tensor(mean)
+ if not isinstance(std, torch.Tensor):
+ if isinstance(std, np.ndarray):
+ std = torch.from_numpy(std)
+ else:
+ std = torch.tensor(std)
+
+ if image.ndim == 3 and image.shape[0] in [1, 3]:
+ return (image - mean[:, None, None]) / std[:, None, None]
+ else:
+ return (image - mean) / std
+
+ def resize(self, image, size, resample=None, default_to_square=True, max_size=None):
+ """
+ Resizes `image`. Enforces conversion of input to PIL.Image.
+
+ Args:
+ image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
+ The image to resize.
+ size (`int` or `Tuple[int, int]`):
+ The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be
+ matched to this.
+
+ If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If
+ `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to
+ this number. i.e, if height > width, then image will be rescaled to (size * height / width, size).
+ resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ The filter to user for resampling.
+ default_to_square (`bool`, *optional*, defaults to `True`):
+ How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a
+ square (`size`,`size`). If set to `False`, will replicate
+ [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize)
+ with support for resizing only the smallest edge and providing an optional `max_size`.
+ max_size (`int`, *optional*, defaults to `None`):
+ The maximum allowed for the longer edge of the resized image: if the longer edge of the image is
+ greater than `max_size` after being resized according to `size`, then the image is resized again so
+ that the longer edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller
+ edge may be shorter than `size`. Only used if `default_to_square` is `False`.
+
+ Returns:
+ image: A resized `PIL.Image.Image`.
+ """
+ resample = resample if resample is not None else PILImageResampling.BILINEAR
+
+ self._ensure_format_supported(image)
+
+ if not isinstance(image, PIL.Image.Image):
+ image = self.to_pil_image(image)
+
+ if isinstance(size, list):
+ size = tuple(size)
+
+ if isinstance(size, int) or len(size) == 1:
+ if default_to_square:
+ size = (size, size) if isinstance(size, int) else (size[0], size[0])
+ else:
+ width, height = image.size
+ # specified size only for the smallest edge
+ short, long = (width, height) if width <= height else (height, width)
+ requested_new_short = size if isinstance(size, int) else size[0]
+
+ if short == requested_new_short:
+ return image
+
+ new_short, new_long = requested_new_short, int(requested_new_short * long / short)
+
+ if max_size is not None:
+ if max_size <= requested_new_short:
+ raise ValueError(
+ f"max_size = {max_size} must be strictly greater than the requested "
+ f"size for the smaller edge size = {size}"
+ )
+ if new_long > max_size:
+ new_short, new_long = int(max_size * new_short / new_long), max_size
+
+ size = (new_short, new_long) if width <= height else (new_long, new_short)
+
+ return image.resize(size, resample=resample)
+
+ def center_crop(self, image, size):
+ """
+ Crops `image` to the given size using a center crop. Note that if the image is too small to be cropped to the
+ size given, it will be padded (so the returned result has the size asked).
+
+ Args:
+ image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor` of shape (n_channels, height, width) or (height, width, n_channels)):
+ The image to resize.
+ size (`int` or `Tuple[int, int]`):
+ The size to which crop the image.
+
+ Returns:
+ new_image: A center cropped `PIL.Image.Image` or `np.ndarray` or `torch.Tensor` of shape: (n_channels,
+ height, width).
+ """
+ self._ensure_format_supported(image)
+
+ if not isinstance(size, tuple):
+ size = (size, size)
+
+ # PIL Image.size is (width, height) but NumPy array and torch Tensors have (height, width)
+ if is_torch_tensor(image) or isinstance(image, np.ndarray):
+ if image.ndim == 2:
+ image = self.expand_dims(image)
+ image_shape = image.shape[1:] if image.shape[0] in [1, 3] else image.shape[:2]
+ else:
+ image_shape = (image.size[1], image.size[0])
+
+ top = (image_shape[0] - size[0]) // 2
+ bottom = top + size[0] # In case size is odd, (image_shape[0] + size[0]) // 2 won't give the proper result.
+ left = (image_shape[1] - size[1]) // 2
+ right = left + size[1] # In case size is odd, (image_shape[1] + size[1]) // 2 won't give the proper result.
+
+ # For PIL Images we have a method to crop directly.
+ if isinstance(image, PIL.Image.Image):
+ return image.crop((left, top, right, bottom))
+
+ # Check if image is in (n_channels, height, width) or (height, width, n_channels) format
+ channel_first = True if image.shape[0] in [1, 3] else False
+
+ # Transpose (height, width, n_channels) format images
+ if not channel_first:
+ if isinstance(image, np.ndarray):
+ image = image.transpose(2, 0, 1)
+ if is_torch_tensor(image):
+ image = image.permute(2, 0, 1)
+
+ # Check if cropped area is within image boundaries
+ if top >= 0 and bottom <= image_shape[0] and left >= 0 and right <= image_shape[1]:
+ return image[..., top:bottom, left:right]
+
+ # Otherwise, we may need to pad if the image is too small. Oh joy...
+ new_shape = image.shape[:-2] + (max(size[0], image_shape[0]), max(size[1], image_shape[1]))
+ if isinstance(image, np.ndarray):
+ new_image = np.zeros_like(image, shape=new_shape)
+ elif is_torch_tensor(image):
+ new_image = image.new_zeros(new_shape)
+
+ top_pad = (new_shape[-2] - image_shape[0]) // 2
+ bottom_pad = top_pad + image_shape[0]
+ left_pad = (new_shape[-1] - image_shape[1]) // 2
+ right_pad = left_pad + image_shape[1]
+ new_image[..., top_pad:bottom_pad, left_pad:right_pad] = image
+
+ top += top_pad
+ bottom += top_pad
+ left += left_pad
+ right += left_pad
+
+ new_image = new_image[
+ ..., max(0, top) : min(new_image.shape[-2], bottom), max(0, left) : min(new_image.shape[-1], right)
+ ]
+
+ return new_image
+
+ def flip_channel_order(self, image):
+ """
+ Flips the channel order of `image` from RGB to BGR, or vice versa. Note that this will trigger a conversion of
+ `image` to a NumPy array if it's a PIL Image.
+
+ Args:
+ image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
+ The image whose color channels to flip. If `np.ndarray` or `torch.Tensor`, the channel dimension should
+ be first.
+ """
+ self._ensure_format_supported(image)
+
+ if isinstance(image, PIL.Image.Image):
+ image = self.to_numpy_array(image)
+
+ return image[::-1, :, :]
+
+ def rotate(self, image, angle, resample=None, expand=0, center=None, translate=None, fillcolor=None):
+ """
+ Returns a rotated copy of `image`. This method returns a copy of `image`, rotated the given number of degrees
+ counter clockwise around its centre.
+
+ Args:
+ image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
+ The image to rotate. If `np.ndarray` or `torch.Tensor`, will be converted to `PIL.Image.Image` before
+ rotating.
+
+ Returns:
+ image: A rotated `PIL.Image.Image`.
+ """
+ resample = resample if resample is not None else PIL.Image.NEAREST
+
+ self._ensure_format_supported(image)
+
+ if not isinstance(image, PIL.Image.Image):
+ image = self.to_pil_image(image)
+
+ return image.rotate(
+ angle, resample=resample, expand=expand, center=center, translate=translate, fillcolor=fillcolor
+ )
+
+
+def validate_annotations(
+ annotation_format: AnnotationFormat,
+ supported_annotation_formats: Tuple[AnnotationFormat, ...],
+ annotations: List[Dict],
+) -> None:
+ if annotation_format not in supported_annotation_formats:
+ raise ValueError(f"Unsupported annotation format: {format} must be one of {supported_annotation_formats}")
+
+ if annotation_format is AnnotationFormat.COCO_DETECTION:
+ if not valid_coco_detection_annotations(annotations):
+ raise ValueError(
+ "Invalid COCO detection annotations. Annotations must a dict (single image) or list of dicts "
+ "(batch of images) with the following keys: `image_id` and `annotations`, with the latter "
+ "being a list of annotations in the COCO format."
+ )
+
+ if annotation_format is AnnotationFormat.COCO_PANOPTIC:
+ if not valid_coco_panoptic_annotations(annotations):
+ raise ValueError(
+ "Invalid COCO panoptic annotations. Annotations must a dict (single image) or list of dicts "
+ "(batch of images) with the following keys: `image_id`, `file_name` and `segments_info`, with "
+ "the latter being a list of annotations in the COCO format."
+ )
+
+
+def validate_kwargs(valid_processor_keys: List[str], captured_kwargs: List[str]):
+ unused_keys = set(captured_kwargs).difference(set(valid_processor_keys))
+ if unused_keys:
+ unused_key_str = ", ".join(unused_keys)
+ # TODO raise a warning here instead of simply logging?
+ logger.warning(f"Unused or unrecognized kwargs: {unused_key_str}.")
+
+
+@dataclass(frozen=True)
+class SizeDict:
+ """
+ Hashable dictionary to store image size information.
+ """
+
+ height: int = None
+ width: int = None
+ longest_edge: int = None
+ shortest_edge: int = None
+ max_height: int = None
+ max_width: int = None
+
+ def __getitem__(self, key):
+ if hasattr(self, key):
+ return getattr(self, key)
+ raise KeyError(f"Key {key} not found in SizeDict.")
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/__init__.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5fd8a1e9dfde2745541093baffb355ad8598936
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/__init__.py
@@ -0,0 +1,277 @@
+# 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.
+from typing import TYPE_CHECKING
+
+from ..utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_torch_greater_or_equal
+
+
+_import_structure = {
+ "aqlm": ["replace_with_aqlm_linear"],
+ "awq": [
+ "fuse_awq_modules",
+ "post_init_awq_exllama_modules",
+ "post_init_awq_ipex_modules",
+ "replace_quantization_scales",
+ "replace_with_awq_linear",
+ ],
+ "bitnet": [
+ "BitLinear",
+ "pack_weights",
+ "replace_with_bitnet_linear",
+ "unpack_weights",
+ ],
+ "bitsandbytes": [
+ "dequantize_and_replace",
+ "get_keys_to_not_convert",
+ "replace_8bit_linear",
+ "replace_with_bnb_linear",
+ "set_module_8bit_tensor_to_device",
+ "set_module_quantized_tensor_to_device",
+ "validate_bnb_backend_availability",
+ ],
+ "deepspeed": [
+ "HfDeepSpeedConfig",
+ "HfTrainerDeepSpeedConfig",
+ "deepspeed_config",
+ "deepspeed_init",
+ "deepspeed_load_checkpoint",
+ "deepspeed_optim_sched",
+ "is_deepspeed_available",
+ "is_deepspeed_zero3_enabled",
+ "set_hf_deepspeed_config",
+ "unset_hf_deepspeed_config",
+ ],
+ "eetq": ["replace_with_eetq_linear"],
+ "fbgemm_fp8": ["FbgemmFp8Linear", "replace_with_fbgemm_fp8_linear"],
+ "finegrained_fp8": ["FP8Linear", "replace_with_fp8_linear"],
+ "fsdp": ["is_fsdp_managed_module"],
+ "ggml": [
+ "GGUF_CONFIG_MAPPING",
+ "GGUF_TOKENIZER_MAPPING",
+ "_gguf_parse_value",
+ "load_dequant_gguf_tensor",
+ "load_gguf",
+ ],
+ "higgs": [
+ "HiggsLinear",
+ "dequantize_higgs",
+ "quantize_with_higgs",
+ "replace_with_higgs_linear",
+ ],
+ "hqq": ["prepare_for_hqq_linear"],
+ "integration_utils": [
+ "INTEGRATION_TO_CALLBACK",
+ "AzureMLCallback",
+ "ClearMLCallback",
+ "CodeCarbonCallback",
+ "CometCallback",
+ "DagsHubCallback",
+ "DVCLiveCallback",
+ "FlyteCallback",
+ "MLflowCallback",
+ "NeptuneCallback",
+ "NeptuneMissingConfiguration",
+ "SwanLabCallback",
+ "TensorBoardCallback",
+ "WandbCallback",
+ "get_available_reporting_integrations",
+ "get_reporting_integration_callbacks",
+ "hp_params",
+ "is_azureml_available",
+ "is_clearml_available",
+ "is_codecarbon_available",
+ "is_comet_available",
+ "is_dagshub_available",
+ "is_dvclive_available",
+ "is_flyte_deck_standard_available",
+ "is_flytekit_available",
+ "is_mlflow_available",
+ "is_neptune_available",
+ "is_optuna_available",
+ "is_ray_available",
+ "is_ray_tune_available",
+ "is_sigopt_available",
+ "is_swanlab_available",
+ "is_tensorboard_available",
+ "is_wandb_available",
+ "rewrite_logs",
+ "run_hp_search_optuna",
+ "run_hp_search_ray",
+ "run_hp_search_sigopt",
+ "run_hp_search_wandb",
+ ],
+ "peft": ["PeftAdapterMixin"],
+ "quanto": ["replace_with_quanto_layers"],
+ "spqr": ["replace_with_spqr_linear"],
+ "vptq": ["replace_with_vptq_linear"],
+}
+
+try:
+ if not is_torch_available():
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ pass
+else:
+ _import_structure["executorch"] = [
+ "TorchExportableModuleWithStaticCache",
+ "convert_and_export_with_cache",
+ ]
+
+try:
+ if not is_torch_greater_or_equal("2.3"):
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ pass
+else:
+ _import_structure["tensor_parallel"] = [
+ "shard_and_distribute_module",
+ "SUPPORTED_TP_STYLES",
+ "translate_to_torch_parallel_style",
+ ]
+try:
+ if not is_torch_greater_or_equal("2.5"):
+ raise OptionalDependencyNotAvailable()
+except OptionalDependencyNotAvailable:
+ pass
+else:
+ _import_structure["flex_attention"] = [
+ "make_flex_block_causal_mask",
+ ]
+
+if TYPE_CHECKING:
+ from .aqlm import replace_with_aqlm_linear
+ from .awq import (
+ fuse_awq_modules,
+ post_init_awq_exllama_modules,
+ post_init_awq_ipex_modules,
+ replace_quantization_scales,
+ replace_with_awq_linear,
+ )
+ from .bitnet import (
+ BitLinear,
+ pack_weights,
+ replace_with_bitnet_linear,
+ unpack_weights,
+ )
+ from .bitsandbytes import (
+ dequantize_and_replace,
+ get_keys_to_not_convert,
+ replace_8bit_linear,
+ replace_with_bnb_linear,
+ set_module_8bit_tensor_to_device,
+ set_module_quantized_tensor_to_device,
+ validate_bnb_backend_availability,
+ )
+ from .deepspeed import (
+ HfDeepSpeedConfig,
+ HfTrainerDeepSpeedConfig,
+ deepspeed_config,
+ deepspeed_init,
+ deepspeed_load_checkpoint,
+ deepspeed_optim_sched,
+ is_deepspeed_available,
+ is_deepspeed_zero3_enabled,
+ set_hf_deepspeed_config,
+ unset_hf_deepspeed_config,
+ )
+ from .eetq import replace_with_eetq_linear
+ from .fbgemm_fp8 import FbgemmFp8Linear, replace_with_fbgemm_fp8_linear
+ from .finegrained_fp8 import FP8Linear, replace_with_fp8_linear
+ from .fsdp import is_fsdp_managed_module
+ from .ggml import (
+ GGUF_CONFIG_MAPPING,
+ GGUF_TOKENIZER_MAPPING,
+ _gguf_parse_value,
+ load_dequant_gguf_tensor,
+ load_gguf,
+ )
+ from .higgs import HiggsLinear, dequantize_higgs, quantize_with_higgs, replace_with_higgs_linear
+ from .hqq import prepare_for_hqq_linear
+ from .integration_utils import (
+ INTEGRATION_TO_CALLBACK,
+ AzureMLCallback,
+ ClearMLCallback,
+ CodeCarbonCallback,
+ CometCallback,
+ DagsHubCallback,
+ DVCLiveCallback,
+ FlyteCallback,
+ MLflowCallback,
+ NeptuneCallback,
+ NeptuneMissingConfiguration,
+ SwanLabCallback,
+ TensorBoardCallback,
+ WandbCallback,
+ get_available_reporting_integrations,
+ get_reporting_integration_callbacks,
+ hp_params,
+ is_azureml_available,
+ is_clearml_available,
+ is_codecarbon_available,
+ is_comet_available,
+ is_dagshub_available,
+ is_dvclive_available,
+ is_flyte_deck_standard_available,
+ is_flytekit_available,
+ is_mlflow_available,
+ is_neptune_available,
+ is_optuna_available,
+ is_ray_available,
+ is_ray_tune_available,
+ is_sigopt_available,
+ is_swanlab_available,
+ is_tensorboard_available,
+ is_wandb_available,
+ rewrite_logs,
+ run_hp_search_optuna,
+ run_hp_search_ray,
+ run_hp_search_sigopt,
+ run_hp_search_wandb,
+ )
+ from .peft import PeftAdapterMixin
+ from .quanto import replace_with_quanto_layers
+ from .spqr import replace_with_spqr_linear
+ from .vptq import replace_with_vptq_linear
+
+ try:
+ if not is_torch_available():
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ pass
+ else:
+ from .executorch import TorchExportableModuleWithStaticCache, convert_and_export_with_cache
+
+ try:
+ if not is_torch_greater_or_equal("2.3"):
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ pass
+ else:
+ from .tensor_parallel import (
+ SUPPORTED_TP_STYLES,
+ shard_and_distribute_module,
+ translate_to_torch_parallel_style,
+ )
+
+ try:
+ if not is_torch_greater_or_equal("2.5"):
+ raise OptionalDependencyNotAvailable()
+ except OptionalDependencyNotAvailable:
+ pass
+ else:
+ from .flex_attention import make_flex_block_causal_mask
+else:
+ import sys
+
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/aqlm.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/aqlm.py
new file mode 100644
index 0000000000000000000000000000000000000000..0626da7aced5bc259295ac51c58931858aac8dc8
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/aqlm.py
@@ -0,0 +1,100 @@
+# 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.
+"AQLM (Additive Quantization of Language Model) integration file"
+
+from ..utils import ACCELERATE_MIN_VERSION, is_accelerate_available, is_aqlm_available, is_torch_available
+
+
+if is_torch_available():
+ import torch.nn as nn
+
+
+def replace_with_aqlm_linear(
+ model,
+ quantization_config=None,
+ linear_weights_not_to_quantize=None,
+ current_key_name=None,
+ has_been_replaced=False,
+):
+ """
+ Public method that recursively replaces the Linear layers of the given model with AQLM quantized layers.
+ `accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the
+ conversion has been successfull or not.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to convert, can be any `torch.nn.Module` instance.
+ quantization_config (`AqlmConfig`):
+ The quantization config object that contains the quantization parameters.
+ linear_weights_not_to_quantize (`list[str]`, *optional*):
+ A list of nn.Linear weights to not convert. If a parameter path is in the list (e.g. `lm_head.weight`), the corresponding module will not be
+ converted.
+ current_key_name (`list`, *optional*):
+ A list that contains the current key name. This is used for recursion and should not be passed by the user.
+ has_been_replaced (`bool`, *optional*):
+ A boolean that indicates if the conversion has been successful or not. This is used for recursion and
+ should not be passed by the user.
+ """
+ if not is_aqlm_available():
+ raise ValueError("AQLM is not available. Please install it with `pip install aqlm[cpu,gpu]`")
+
+ if not is_accelerate_available():
+ raise ValueError(
+ f"AQLM requires Accelerate to be installed: `pip install 'accelerate>={ACCELERATE_MIN_VERSION}'`"
+ )
+
+ if linear_weights_not_to_quantize is None:
+ linear_weights_not_to_quantize = []
+
+ from accelerate import init_empty_weights
+ from aqlm import QuantizedLinear
+
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if isinstance(module, nn.Linear):
+ # Check if the current key is not in the `linear_weights_not_to_quantize`
+ if ".".join(current_key_name) + ".weight" not in linear_weights_not_to_quantize:
+ with init_empty_weights():
+ in_features = module.in_features
+ out_features = module.out_features
+
+ model._modules[name] = QuantizedLinear(
+ in_features,
+ out_features,
+ bias=module.bias is not None,
+ in_group_size=quantization_config.in_group_size,
+ out_group_size=quantization_config.out_group_size,
+ num_codebooks=quantization_config.num_codebooks,
+ nbits_per_codebook=quantization_config.nbits_per_codebook,
+ )
+ has_been_replaced = True
+
+ # Store the module class in case we need to transpose the weight later
+ model._modules[name].source_cls = type(module)
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = replace_with_aqlm_linear(
+ module,
+ quantization_config=quantization_config,
+ linear_weights_not_to_quantize=linear_weights_not_to_quantize,
+ current_key_name=current_key_name,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/awq.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/awq.py
new file mode 100644
index 0000000000000000000000000000000000000000..c860ea1f53744bba6a4d63bc73ee51a187fc92f8
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/awq.py
@@ -0,0 +1,498 @@
+# 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.
+"AWQ (Activation aware Weight Quantization) integration file"
+
+import importlib
+
+from packaging import version
+
+from ..activations import ACT2FN
+from ..modeling_utils import PreTrainedModel
+from ..utils import is_auto_awq_available, is_ipex_available, is_torch_available, logging
+from ..utils.quantization_config import (
+ AwqBackendPackingMethod,
+ AwqConfig,
+ AWQLinearVersion,
+ ExllamaVersion,
+)
+
+
+if is_torch_available():
+ import torch
+ import torch.nn as nn
+
+logger = logging.get_logger(__name__)
+
+AWQ_FUSED_MAPPINGS = {
+ "mistral": {
+ "attention": ["q_proj", "k_proj", "v_proj", "o_proj"],
+ "mlp": ["gate_proj", "up_proj", "down_proj"],
+ "layernorm": ["input_layernorm", "post_attention_layernorm", "norm"],
+ "use_alibi": False,
+ },
+ "mixtral": {
+ "attention": ["q_proj", "k_proj", "v_proj", "o_proj"],
+ "mlp": ["w1", "w3", "w2"],
+ "layernorm": ["input_layernorm", "post_attention_layernorm", "norm"],
+ "use_alibi": False,
+ "rope_theta": 1000000.0,
+ },
+ "llama": {
+ "attention": ["q_proj", "k_proj", "v_proj", "o_proj"],
+ "mlp": ["gate_proj", "up_proj", "down_proj"],
+ "layernorm": ["input_layernorm", "post_attention_layernorm", "norm"],
+ "use_alibi": False,
+ },
+ "llava": {
+ "attention": ["q_proj", "k_proj", "v_proj", "o_proj"],
+ "mlp": ["gate_proj", "up_proj", "down_proj"],
+ "layernorm": ["input_layernorm", "post_attention_layernorm", "norm"],
+ "use_alibi": False,
+ },
+}
+
+AWQ_SCALES_MAPPINGS = {
+ "starcoder2": {"act": "act", "layer_before_act": "c_fc"},
+ "RefinedWebModel": {"act": "act", "layer_before_act": "dense_h_to_4h"},
+ "falcon": {"act": "act", "layer_before_act": "dense_h_to_4h"},
+ "mpt": {"act": "act", "layer_before_act": "up_proj"},
+ "gptj": {"act": "act", "layer_before_act": "fc_in"},
+ "gpt_neox": {"act": "act", "layer_before_act": "dense_h_to_4h"},
+ "gpt_bigcode": {"act": "act", "layer_before_act": "c_fc"},
+ "bloom": {"act": "gelu_impl", "layer_before_act": "dense_h_to_4h"},
+}
+
+
+def replace_quantization_scales(model, model_type):
+ from awq.modules.act import ScaledActivation
+
+ if model_type not in AWQ_SCALES_MAPPINGS:
+ return model
+ for name, module in model.named_children():
+ act_name = AWQ_SCALES_MAPPINGS[model_type]["act"]
+ layer_before_act_name = AWQ_SCALES_MAPPINGS[model_type]["layer_before_act"]
+ if name == act_name and hasattr(model, layer_before_act_name):
+ layer_before_act = getattr(model, AWQ_SCALES_MAPPINGS[model_type]["layer_before_act"])
+ size = layer_before_act.out_features
+ scale_like = torch.ones(size)
+ model._modules[name] = ScaledActivation(module, scale_like)
+ _ = replace_quantization_scales(module, model_type)
+ return model
+
+
+def replace_with_awq_linear(
+ model,
+ modules_to_not_convert=None,
+ quantization_config=None,
+ current_key_name=None,
+ has_been_replaced=False,
+) -> bool:
+ """
+ Public method that recursively replaces the Linear layers of the given model with AWQ quantized layers.
+ `accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the
+ conversion has been successfull or not.
+
+ During the module replacement, we also infer the backend to use through the `quantization_config` object.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to convert, can be any `torch.nn.Module` instance.
+ quantization_config (`AwqConfig`):
+ The quantization config object that contains the quantization parameters.
+ modules_to_not_convert (`list`, *optional*):
+ A list of modules to not convert. If a module name is in the list (e.g. `lm_head`), it will not be
+ converted.
+ current_key_name (`list`, *optional*):
+ A list that contains the current key name. This is used for recursion and should not be passed by the user.
+ has_been_replaced (`bool`, *optional*):
+ A boolean that indicates if the conversion has been successful or not. This is used for recursion and
+ should not be passed by the user.
+ """
+ if modules_to_not_convert is None:
+ modules_to_not_convert = []
+
+ backend = quantization_config.backend
+
+ if not is_auto_awq_available():
+ raise ValueError(
+ "AWQ (either `autoawq` or `llmawq`) is not available. Please install it with `pip install autoawq` or check out the installation guide in https://github.com/mit-han-lab/llm-awq"
+ )
+
+ if backend == AwqBackendPackingMethod.AUTOAWQ:
+ if quantization_config.version == AWQLinearVersion.GEMM:
+ from awq.modules.linear.gemm import WQLinear_GEMM
+
+ target_cls = WQLinear_GEMM
+ elif quantization_config.version == AWQLinearVersion.GEMV:
+ from awq.modules.linear.gemv import WQLinear_GEMV
+
+ target_cls = WQLinear_GEMV
+ elif quantization_config.version == AWQLinearVersion.EXLLAMA:
+ if quantization_config.exllama_config["version"] == ExllamaVersion.ONE:
+ from awq.modules.linear.exllama import WQLinear_Exllama
+
+ target_cls = WQLinear_Exllama
+ elif quantization_config.exllama_config["version"] == ExllamaVersion.TWO:
+ from awq.modules.linear.exllamav2 import WQLinear_ExllamaV2
+
+ target_cls = WQLinear_ExllamaV2
+ else:
+ raise ValueError(f"Unrecognized Exllama version: {quantization_config.exllama_config['version']}")
+ elif quantization_config.version == AWQLinearVersion.IPEX:
+ from awq.modules.linear.gemm_ipex import WQLinear_IPEX
+
+ target_cls = WQLinear_IPEX
+ else:
+ raise ValueError(f"Unrecognized AWQ version: {quantization_config.version}")
+ else:
+ from awq.quantize.qmodule import WQLinear
+
+ target_cls = WQLinear
+
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if isinstance(module, nn.Linear) and name not in modules_to_not_convert:
+ # Check if the current key is not in the `modules_to_not_convert`
+ if not any(key in ".".join(current_key_name) for key in modules_to_not_convert):
+ in_features = module.in_features
+ out_features = module.out_features
+
+ model._modules[name] = target_cls(
+ w_bit=quantization_config.bits,
+ group_size=quantization_config.group_size,
+ in_features=in_features,
+ out_features=out_features,
+ bias=module.bias is not None,
+ dev=module.weight.device,
+ )
+ has_been_replaced = True
+
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = replace_with_awq_linear(
+ module,
+ modules_to_not_convert=modules_to_not_convert,
+ current_key_name=current_key_name,
+ quantization_config=quantization_config,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
+
+
+def get_modules_to_fuse(model, quantization_config):
+ """
+ Returns the fusing mapping given the quantization config and the model
+
+ Args:
+ model (`~PreTrainedModel`):
+ The model to fuse - note this model should have been converted into AWQ format beforehand.
+ quantization_config (`~transformers.quantization_config.AWQConfig`):
+ The quantization configuration to use.
+ """
+ if not isinstance(model, PreTrainedModel):
+ raise TypeError(f"The model should be an instance of `PreTrainedModel`, got {model.__class__.__name__}")
+
+ # Always default to `quantization_config.modules_to_fuse`
+ if quantization_config.modules_to_fuse is not None:
+ current_fused_mapping = quantization_config.modules_to_fuse
+ current_fused_mapping["max_seq_len"] = quantization_config.fuse_max_seq_len
+ elif model.config.model_type in AWQ_FUSED_MAPPINGS:
+ current_fused_mapping = AWQ_FUSED_MAPPINGS[model.config.model_type]
+
+ # Properly deal with the case where we have a multi-modal model as well (e.g. Llava)
+ config = model.config.get_text_config(decoder=True)
+
+ # Handle hidden_size, num_attention_heads, num_key_value_heads on our own.
+ hidden_size = config.hidden_size
+ num_attention_heads = config.num_attention_heads
+ num_key_value_heads = getattr(config, "num_key_value_heads", num_attention_heads)
+
+ # Fill `current_fused_mapping` with the expected values
+ current_fused_mapping["hidden_size"] = hidden_size
+ current_fused_mapping["num_attention_heads"] = num_attention_heads
+ current_fused_mapping["num_key_value_heads"] = num_key_value_heads
+ current_fused_mapping["max_seq_len"] = quantization_config.fuse_max_seq_len
+ else:
+ raise ValueError(
+ "Fusing mapping not found either on the quantization config or the supported `AWQ_FUSED_MAPPINGS`. Please pass a `fused_mapping` argument"
+ " in the `quantization_config` or raise an issue on transformers https://github.com/huggingface/transformers to add its support."
+ )
+ return current_fused_mapping
+
+
+def fuse_awq_modules(model, quantization_config):
+ """
+ Optionally fuse some modules in the model to speedup inference.
+
+ Args:
+ model (`~PreTrainedModel`):
+ The model to fuse - note this model should have been converted into AWQ format beforehand.
+ quantization_config (`Union[AwqConfig, dict]`):
+ The quantization configuration to use.
+ """
+ # We need to convert it from dict in order to get an AwqConfig object
+ # otherwise the fields `backend` etc. will not be available
+ # https://github.com/huggingface/transformers/pull/27411#discussion_r1414044495
+ if isinstance(quantization_config, dict):
+ quantization_config = AwqConfig.from_dict(quantization_config)
+ backend = quantization_config.backend
+
+ modules_to_fuse = get_modules_to_fuse(model, quantization_config)
+ modules_to_not_convert = getattr(quantization_config, "modules_to_not_convert", None)
+
+ if backend == AwqBackendPackingMethod.AUTOAWQ:
+ from awq.modules.fused.attn import QuantAttentionFused
+ from awq.modules.fused.mlp import QuantFusedMLP
+ from awq.modules.fused.norm import FasterTransformerRMSNorm
+ else:
+ raise ValueError("Fusing is only supported for the AutoAWQ backend")
+
+ fused_attention_modules = []
+
+ for name, module in model.named_modules():
+ if modules_to_not_convert is not None:
+ if any(module_name_to_not_convert in name for module_name_to_not_convert in modules_to_not_convert):
+ continue
+
+ # Replace layer norms
+ _fuse_awq_layernorm(modules_to_fuse["layernorm"], module, FasterTransformerRMSNorm)
+
+ # Replace MLP layers if awq version is not ipex.
+ if quantization_config.version != "ipex":
+ _fuse_awq_mlp(model, name, modules_to_fuse["mlp"], module, QuantFusedMLP)
+ else:
+ logger.info("The IPEX version AWQ does not support fuse mlp for now.")
+
+ # Replace attention layers
+ attention_has_been_fused = _fuse_awq_attention_layers(
+ model, module, modules_to_fuse, name, QuantAttentionFused
+ )
+
+ if attention_has_been_fused:
+ fused_attention_modules.append(name.split(".")[0])
+
+ # For AWQ fused + Llama we need to set `config._attn_implementation` = "custom" to avoid unexpected behavior and pass
+ # `None` attention mask to the fused attention modules as now the attention mask is dropped by our models and dealt
+ # by the `AttentionMaskConverter` module.
+ if len(fused_attention_modules) > 0:
+ for module_name, module in model.named_modules():
+ if any(
+ module_name in fused_attention_modules for fused_attention_parent_module in fused_attention_modules
+ ):
+ if hasattr(module, "config") and hasattr(module.config, "_attn_implementation"):
+ module.config._attn_implementation = "custom"
+ return model
+
+
+def _fuse_awq_layernorm(fuse_module_names, module, target_cls):
+ """
+ Fuse the LayerNorm layers into a target class using autoawq
+
+ Args:
+ fuse_module_names (`List[str]`):
+ The list of module names to fuse
+ module (`nn.Module`):
+ The pytorch parent module that has layernorm modules to fuse
+ target_cls (`~autoawq.FasterTransformerRMSNorm`):
+ The `FasterTransformerRMSNorm` class as it only supports that class
+ for now.
+ """
+ for module_name in fuse_module_names:
+ if hasattr(module, module_name):
+ old_module = getattr(module, module_name)
+ module._modules[module_name] = target_cls(
+ old_module.weight,
+ old_module.variance_epsilon,
+ ).to(old_module.weight.device)
+ del old_module
+
+
+def _fuse_awq_mlp(model, current_module_name, fuse_module_names, module, target_cls):
+ """
+ Fuse the MLP layers into a target class using autoawq
+
+ Args:
+ model (`~PreTrainedModel`):
+ The input pretrained model
+ current_module_name (`str`):
+ The current submodule name
+ fuse_module_names (`List[str]`):
+ The list of module names to fuse. For the MLP layers it has to be an array
+ of length 3 that consists of the 3 MLP layers in the order (gate (dense layer post-attention) / up / down layers)
+ module (`nn.Module`):
+ The pytorch parent module that has layernorm modules to fuse
+ target_cls (`~autoawq.QuantFusedMLP`):
+ The `QuantFusedMLP` class as it only supports that class
+ for now.
+ """
+ if len(fuse_module_names) == 0:
+ return
+
+ if hasattr(module, fuse_module_names[0]):
+ gate_proj = getattr(module, fuse_module_names[0])
+ up_proj = getattr(module, fuse_module_names[1])
+ down_proj = getattr(module, fuse_module_names[2])
+
+ previous_device = gate_proj.qweight.device
+
+ # Deal also with the case model has `text_config` attribute
+ config = model.config.get_text_config(decoder=True)
+ hidden_act = config.hidden_act
+ activation_fn = ACT2FN[hidden_act]
+ new_module = target_cls(gate_proj, down_proj, up_proj, activation_fn)
+
+ parent_name, child_name = current_module_name.rsplit(".", 1)
+ parent = model.get_submodule(parent_name)
+ setattr(parent, child_name, new_module.to(previous_device))
+
+ del gate_proj, up_proj, down_proj
+
+
+def _fuse_awq_attention_layers(model, module, modules_to_fuse, current_module_name, target_cls):
+ """
+ Fuse the Attention layers into a target class using autoawq
+
+ Args:
+ model (`~PreTrainedModel`):
+ The input pretrained model
+ module (`nn.Module`):
+ The pytorch parent module that has layernorm modules to fuse
+ modules_to_fuse (`List[str]`):
+ The module fusing mapping. The dictionary has to contain a field `attention` with attention module names
+ in the correct order: q, k, v, o layer
+ current_module_name (`str`):
+ The current submodule name
+ target_cls (`~autoawq.QuantAttentionFused`):
+ The `QuantAttentionFused` class as it only supports that class
+ for now.
+ """
+ from awq.modules.linear import WQLinear_GEMM, WQLinear_GEMV
+
+ module_has_been_fused = False
+
+ if len(modules_to_fuse["attention"]) == 0:
+ return module_has_been_fused
+
+ if hasattr(module, modules_to_fuse["attention"][0]):
+ # First, we pack the QKV layers together
+ q_proj = getattr(module, modules_to_fuse["attention"][0])
+
+ if isinstance(q_proj, WQLinear_GEMV):
+ linear_target_cls = WQLinear_GEMV
+ cat_dim = 0
+ elif isinstance(q_proj, WQLinear_GEMM):
+ linear_target_cls = WQLinear_GEMM
+ cat_dim = 1
+ elif is_ipex_available() and version.parse(importlib.metadata.version("autoawq")) > version.parse("0.2.6"):
+ from awq.modules.linear import WQLinear_IPEX
+
+ if isinstance(q_proj, WQLinear_IPEX):
+ linear_target_cls = WQLinear_IPEX
+ cat_dim = 1
+ else:
+ raise ValueError("Unsupported q_proj type: {type(q_proj)}")
+
+ previous_device = q_proj.qweight.device
+
+ k_proj = getattr(module, modules_to_fuse["attention"][1])
+ v_proj = getattr(module, modules_to_fuse["attention"][2])
+ o_proj = getattr(module, modules_to_fuse["attention"][3])
+
+ bias = torch.cat([q_proj.bias, k_proj.bias, v_proj.bias], dim=0) if q_proj.bias is not None else None
+
+ qkv_layer = linear_target_cls(
+ q_proj.w_bit,
+ q_proj.group_size,
+ q_proj.in_features,
+ q_proj.out_features + k_proj.out_features + v_proj.out_features,
+ q_proj.bias is not None,
+ next(iter(module.state_dict().values())).device,
+ )
+
+ qkv_layer.qweight = torch.cat([q_proj.qweight, k_proj.qweight, v_proj.qweight], dim=cat_dim)
+ qkv_layer.qzeros = torch.cat([q_proj.qzeros, k_proj.qzeros, v_proj.qzeros], dim=cat_dim)
+ qkv_layer.scales = torch.cat([q_proj.scales, k_proj.scales, v_proj.scales], dim=cat_dim)
+
+ if isinstance(qkv_layer, WQLinear_GEMV):
+ qkv_layer.split_k_iters = q_proj.split_k_iters
+
+ qkv_layer.bias = bias
+
+ fused_attention_layer = target_cls(
+ modules_to_fuse["hidden_size"],
+ modules_to_fuse["num_attention_heads"],
+ modules_to_fuse["num_key_value_heads"],
+ qkv_layer,
+ o_proj,
+ previous_device,
+ modules_to_fuse["max_seq_len"],
+ use_alibi=modules_to_fuse["use_alibi"],
+ # The default value in autoawq is set to 10000.0
+ rope_theta=modules_to_fuse.get("rope_theta", 10000.0),
+ )
+
+ fused_attention_layer.is_hf_transformers = True
+
+ parent_name, child_name = current_module_name.rsplit(".", 1)
+ parent = model.get_submodule(parent_name)
+ setattr(parent, child_name, fused_attention_layer.to(previous_device))
+
+ del q_proj, k_proj, v_proj, o_proj
+ module_has_been_fused = True
+
+ return module_has_been_fused
+
+
+def post_init_awq_exllama_modules(model, exllama_config):
+ """
+ Runs post init for Exllama layers which performs:
+ - Weights unpacking, reordering and repacking
+ - Devices scratch space allocation
+ """
+
+ if exllama_config["version"] == ExllamaVersion.ONE:
+ from awq.modules.linear.exllama import exllama_post_init
+
+ model = exllama_post_init(model)
+ elif exllama_config["version"] == ExllamaVersion.TWO:
+ from awq.modules.linear.exllamav2 import exllamav2_post_init
+
+ model = exllamav2_post_init(
+ model,
+ max_input_len=exllama_config["max_input_len"],
+ max_batch_size=exllama_config["max_batch_size"],
+ )
+ else:
+ raise ValueError(f"Unrecognized Exllama version: {exllama_config['version']}")
+
+ return model
+
+
+def post_init_awq_ipex_modules(model):
+ """
+ Runs post init for IPEX layers which performs:
+ - Weights packing, reordering and repacking
+ """
+
+ from awq.modules.linear.gemm_ipex import ipex_post_init
+
+ model = ipex_post_init(model)
+
+ return model
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/bitnet.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/bitnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b50f9738afb69e680371b5f868bc4508f2a60e7
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/bitnet.py
@@ -0,0 +1,288 @@
+from ..utils import is_accelerate_available, is_torch_available, logging
+
+
+if is_accelerate_available():
+ from accelerate import init_empty_weights
+
+if is_torch_available():
+ import torch
+ import torch.nn as nn
+ import torch.nn.functional as F
+
+logger = logging.get_logger(__name__)
+
+
+# the weights are ternary so can be represented with 2 bits, and they are packed in uint8 tensors, hence the number of values per item is 4
+VALUES_PER_ITEM = 4
+
+
+def pack_weights(quantized_weights: torch.Tensor) -> torch.Tensor:
+ """
+ Packs a tensor of quantized weights into a compact format using 2 bits per value.
+
+ Parameters:
+ -----------
+ quantized_weights : torch.Tensor
+ A tensor containing ternary quantized weights with values in {-1, 0, 1}. These values are adjusted to
+ {0, 1, 2} before being packed.
+
+ Returns:
+ --------
+ torch.Tensor
+ A packed tensor where each element stores 4 quantized values (each using 2 bits) in an 8-bit format.
+ """
+
+ original_shape = quantized_weights.shape
+
+ row_dim = (original_shape[0] + VALUES_PER_ITEM - 1) // VALUES_PER_ITEM
+
+ if len(original_shape) == 1:
+ packed_tensor_shape = (row_dim,)
+ else:
+ packed_tensor_shape = (row_dim, *original_shape[1:])
+
+ quantized_weights += 1
+ packed = torch.zeros(packed_tensor_shape, device=quantized_weights.device, dtype=torch.uint8)
+ unpacked = quantized_weights.to(torch.uint8)
+
+ it = min(VALUES_PER_ITEM, (original_shape[0] // row_dim) + 1)
+ for i in range(it):
+ start = i * row_dim
+ end = min(start + row_dim, original_shape[0])
+ packed[: (end - start)] |= unpacked[start:end] << 2 * i
+
+ return packed
+
+
+@torch.compile
+def unpack_weights(packed: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
+ """
+ Unpacks a tensor of quantized weights that were stored in a packed format using 2 bits per value.
+
+ Parameters:
+ -----------
+ packed : torch.Tensor
+ A tensor containing packed weights where each element represents 4 quantized values (using 2 bits per value).
+ dtype : torch.dtype
+ The dtype of the returned Tensor
+ Returns:
+ --------
+ torch.Tensor
+ A tensor of unpacked weights, where each value is converted from its packed 2-bit representation.
+
+ Example:
+ --------
+ packed = torch.tensor([[0b10100001, 0b00011000],
+ [0b10010000, 0b00001010]], dtype=torch.uint8)
+
+ # Unpack the values
+ unpacked = unpack_weights(packed)
+
+ # Resulting unpacked tensor
+ print(unpacked)
+ # Output: tensor([[ 0, -1],
+ [-1, 1],
+ [-1, 1],
+ [-1, 1],
+ [ 1, 0],
+ [ 0, -1],
+ [ 1, -1],
+ [ 1, -1]])
+
+ Explanation of the example:
+ ---------------------------
+ Let's take the first value for example 0b10100001, we we will only focus on the first column,
+ because every element is unpacked across the first dimension
+ - First 2 bits: `01` → 0 at [0][0]
+ - Second 2 bits: `00` → -1 at [0][2]
+ - Third 2 bits: `10` → 1 at [0][4]
+ - Fourth 2 bits: `10` → 1 at [0][6]
+ the second value of the same row (0b10010000) will give the values for [0][1], [0][3], [0][5], [0][7]
+
+ We subtract 1 because during the packing process, it's easier to work with values like 0, 1, and 2. To make this possible,
+ we add 1 to the original ternary weights (which are typically -1, 0, and 1) when packing them. When unpacking, we reverse
+ this by subtracting 1 to restore the original ternary values.
+ """
+ packed_shape = packed.shape
+
+ if len(packed_shape) == 1:
+ original_row_dim = packed_shape[0] * VALUES_PER_ITEM
+ unpacked_shape = (original_row_dim,)
+ else:
+ original_row_dim = packed_shape[0] * VALUES_PER_ITEM
+ unpacked_shape = (original_row_dim, *packed_shape[1:])
+
+ unpacked = torch.zeros(unpacked_shape, device=packed.device, dtype=torch.uint8)
+
+ for i in range(VALUES_PER_ITEM):
+ start = i * packed_shape[0]
+ end = start + packed_shape[0]
+ mask = 3 << (2 * i)
+ unpacked[start:end] = (packed & mask) >> (2 * i)
+
+ return unpacked.to(dtype) - 1
+
+
+class BitLinear(nn.Module):
+ def __init__(self, in_features: int, out_features: int, bias: bool, device=None, dtype=None):
+ super().__init__()
+ self.dtype = dtype
+ self.in_features = in_features
+ self.out_features = out_features
+ self.register_buffer(
+ "weight",
+ torch.zeros(
+ (out_features // VALUES_PER_ITEM, in_features),
+ dtype=torch.uint8,
+ device=device,
+ ),
+ )
+ self.register_buffer(
+ "weight_scale",
+ torch.ones(
+ (1),
+ dtype=dtype,
+ device=device,
+ ),
+ )
+ if bias:
+ self.register_buffer("bias", torch.zeros((out_features), dtype=dtype, device=device))
+ else:
+ self.bias = None
+
+ @torch.compile
+ def activation_quant(self, input, num_bits=8):
+ """
+ Activation function : Performs symmetric, per-token quantization on the input activations.
+ Parameters:
+ -----------
+ x : torch.Tensor
+ Input activations to be quantized.
+ num_bits : int, optional (default=8)
+ Number of bits to use for quantization, determining the quantization range.
+
+ Returns:
+ --------
+ result : torch.Tensor
+ Quantized activation tensor, with values mapped to an `int8` range.
+ scale : torch.Tensor
+ The per-channel scaling factors used to quantize the tensor.
+ """
+ Qn = -(2 ** (num_bits - 1))
+ Qp = 2 ** (num_bits - 1) - 1
+ scale = Qp / input.abs().max(dim=-1, keepdim=True).values.clamp(min=1e-5)
+ result = (input * scale).round().clamp(Qn, Qp)
+ return result.to(torch.int8), scale
+
+ @torch.compile
+ def post_quant_process(self, input, input_scale, weight_scale):
+ out = input / (input_scale * weight_scale)
+ return out
+
+ def forward(self, input):
+ w = self.weight
+ w_quant = unpack_weights(w, dtype=self.dtype)
+ input_quant, input_scale = self.activation_quant(input)
+ y = F.linear(input_quant.to(self.dtype), w_quant)
+ y = self.post_quant_process(y, self.weight_scale, input_scale)
+ if self.bias is not None:
+ y += self.bias.view(1, -1).expand_as(y)
+ return y
+
+
+def _replace_with_bitnet_linear(
+ model,
+ modules_to_not_convert=None,
+ current_key_name=None,
+ quantization_config=None,
+ has_been_replaced=False,
+ pre_quantized=False,
+):
+ """
+ Private method that wraps the recursion for module replacement.
+
+ Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
+ """
+
+ if current_key_name is None:
+ current_key_name = []
+
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ # Check if the current key is not in the `modules_to_not_convert`
+ if not any(key in ".".join(current_key_name) for key in modules_to_not_convert):
+ with init_empty_weights():
+ if isinstance(module, nn.Linear) and name not in modules_to_not_convert:
+ in_features = module.in_features
+ out_features = module.out_features
+ model._modules[name] = BitLinear(
+ in_features=in_features,
+ out_features=out_features,
+ bias=module.bias is not None,
+ device=module.weight.device,
+ dtype=module.weight.dtype,
+ )
+ has_been_replaced = True
+ model._modules[name].requires_grad_(False)
+
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = _replace_with_bitnet_linear(
+ module,
+ modules_to_not_convert=modules_to_not_convert,
+ current_key_name=current_key_name,
+ quantization_config=quantization_config,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
+
+
+def replace_with_bitnet_linear(
+ model,
+ modules_to_not_convert=None,
+ current_key_name=None,
+ quantization_config=None,
+ pre_quantized=False,
+):
+ """
+ A helper function to replace all `torch.nn.Linear` modules by `BitLinear158` modules`.
+
+ The function will be run recursively and replace all `torch.nn.Linear` modules except for the `lm_head` that should
+ be kept as a `torch.nn.Linear` module. The replacement is done under `init_empty_weights` context manager so no
+ CPU/GPU memory is required to run this function. Each weight will be quantized along the channel.
+
+ Parameters:
+ model (`torch.nn.Module`):
+ Input model or `torch.nn.Module` as the function is run recursively.
+ modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`):
+ Names of the modules to not convert in `EetqLinear`. In practice we keep the `lm_head` in full precision
+ for numerical stability reasons.
+ current_key_name (`List[`str`]`, *optional*):
+ An array to track the current key of the recursion. This is used to check whether the current key (part of
+ it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
+ `disk`).
+ """
+ modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
+ if quantization_config and quantization_config.modules_to_not_convert is not None:
+ modules_to_not_convert.extend(quantization_config.modules_to_not_convert)
+ modules_to_not_convert = list(set(modules_to_not_convert))
+ model, has_been_replaced = _replace_with_bitnet_linear(
+ model,
+ modules_to_not_convert,
+ current_key_name,
+ quantization_config,
+ pre_quantized=pre_quantized,
+ )
+
+ if not has_been_replaced:
+ logger.warning(
+ "You are loading your model using bitnet but no linear modules were found in your model."
+ " Please double check your model architecture, or submit an issue on github if you think this is"
+ " a bug."
+ )
+
+ return model
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/bitsandbytes.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/bitsandbytes.py
new file mode 100644
index 0000000000000000000000000000000000000000..61e9f8d8db5d6e6eb6b32c2584fd91ddae52036b
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/bitsandbytes.py
@@ -0,0 +1,559 @@
+import importlib.metadata
+import inspect
+import warnings
+from copy import deepcopy
+from inspect import signature
+
+from packaging import version
+
+from ..utils import (
+ get_available_devices,
+ is_accelerate_available,
+ is_bitsandbytes_available,
+ is_bitsandbytes_multi_backend_available,
+ is_ipex_available,
+ is_torch_available,
+ logging,
+)
+
+
+if is_bitsandbytes_available():
+ import bitsandbytes as bnb
+ import torch
+ import torch.nn as nn
+
+ from ..pytorch_utils import Conv1D
+
+if is_accelerate_available():
+ import accelerate
+ from accelerate import init_empty_weights
+ from accelerate.hooks import add_hook_to_module, remove_hook_from_module
+ from accelerate.utils import find_tied_parameters
+
+logger = logging.get_logger(__name__)
+
+
+def set_module_quantized_tensor_to_device(module, tensor_name, device, value=None, quantized_stats=None):
+ """
+ A helper function to set a given tensor (parameter of buffer) of a module on a specific device (note that doing
+ `param.to(device)` creates a new tensor not linked to the parameter, which is why we need this function). The
+ function is adapted from `set_module_tensor_to_device` function from accelerate that is adapted to support the
+ class `Int8Params` from `bitsandbytes`.
+
+ Args:
+ module (`torch.nn.Module`):
+ The module in which the tensor we want to move lives.
+ tensor_name (`str`):
+ The full name of the parameter/buffer.
+ device (`int`, `str` or `torch.device`):
+ The device on which to set the tensor.
+ value (`torch.Tensor`, *optional*):
+ The value of the tensor (useful when going from the meta device to any other device).
+ quantized_stats (`dict[str, Any]`, *optional*):
+ Dict with items for either 4-bit or 8-bit serialization
+ """
+ # Recurse if needed
+ if "." in tensor_name:
+ splits = tensor_name.split(".")
+ for split in splits[:-1]:
+ new_module = getattr(module, split)
+ if new_module is None:
+ raise ValueError(f"{module} has no attribute {split}.")
+ module = new_module
+ tensor_name = splits[-1]
+
+ if tensor_name not in module._parameters and tensor_name not in module._buffers:
+ raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.")
+ is_buffer = tensor_name in module._buffers
+ old_value = getattr(module, tensor_name)
+
+ if old_value.device == torch.device("meta") and device not in ["meta", torch.device("meta")] and value is None:
+ raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {device}.")
+
+ prequantized_loading = quantized_stats is not None
+ if is_buffer or not is_bitsandbytes_available():
+ is_8bit = False
+ is_4bit = False
+ else:
+ is_4bit = hasattr(bnb.nn, "Params4bit") and isinstance(module._parameters[tensor_name], bnb.nn.Params4bit)
+ is_8bit = isinstance(module._parameters[tensor_name], bnb.nn.Int8Params)
+
+ if is_8bit or is_4bit:
+ param = module._parameters[tensor_name]
+ if param.device.type != "cuda":
+ if value is None:
+ new_value = old_value.to(device)
+ elif isinstance(value, torch.Tensor):
+ new_value = value.to("cpu")
+ else:
+ new_value = torch.tensor(value, device="cpu")
+
+ # Support models using `Conv1D` in place of `nn.Linear` (e.g. openai-community/gpt2) by transposing the weight matrix prior to quantization.
+ # Since weights are saved in the correct "orientation", we skip transposing when loading.
+ if issubclass(module.source_cls, Conv1D) and not prequantized_loading:
+ new_value = new_value.T
+
+ kwargs = old_value.__dict__
+
+ if prequantized_loading != (new_value.dtype in (torch.int8, torch.uint8)):
+ raise ValueError(
+ f"Value dtype `{new_value.dtype}` is not compatible with parameter quantization status."
+ )
+
+ if is_8bit:
+ is_8bit_serializable = version.parse(importlib.metadata.version("bitsandbytes")) > version.parse(
+ "0.37.2"
+ )
+ if new_value.dtype in (torch.int8, torch.uint8) and not is_8bit_serializable:
+ raise ValueError(
+ "Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. "
+ "Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."
+ )
+ new_value = bnb.nn.Int8Params(new_value, requires_grad=False, **kwargs).to(device)
+ if prequantized_loading:
+ setattr(new_value, "SCB", quantized_stats["SCB"].to(device))
+ elif is_4bit:
+ if prequantized_loading:
+ is_4bit_serializable = version.parse(importlib.metadata.version("bitsandbytes")) >= version.parse(
+ "0.41.3"
+ )
+ if new_value.dtype in (torch.int8, torch.uint8) and not is_4bit_serializable:
+ raise ValueError(
+ "Detected 4-bit weights but the version of bitsandbytes is not compatible with 4-bit serialization. "
+ "Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."
+ )
+ new_value = bnb.nn.Params4bit.from_prequantized(
+ data=new_value,
+ quantized_stats=quantized_stats,
+ requires_grad=False,
+ device=device,
+ **kwargs,
+ )
+ else:
+ new_value = bnb.nn.Params4bit(new_value, requires_grad=False, **kwargs).to(device)
+ module._parameters[tensor_name] = new_value
+
+ else:
+ if value is None:
+ new_value = old_value.to(device)
+ elif isinstance(value, torch.Tensor):
+ new_value = value.to(device)
+ else:
+ new_value = torch.tensor(value, device=device)
+
+ if is_buffer:
+ module._buffers[tensor_name] = new_value
+ else:
+ new_value = nn.Parameter(new_value, requires_grad=old_value.requires_grad)
+ module._parameters[tensor_name] = new_value
+
+
+def _replace_with_bnb_linear(
+ model,
+ modules_to_not_convert=None,
+ current_key_name=None,
+ quantization_config=None,
+ has_been_replaced=False,
+):
+ """
+ Private method that wraps the recursion for module replacement.
+
+ Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
+ """
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if (isinstance(module, nn.Linear) or isinstance(module, Conv1D)) and name not in modules_to_not_convert:
+ # Check if the current key is not in the `modules_to_not_convert`
+ current_key_name_str = ".".join(current_key_name)
+ if not any(
+ (key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
+ ):
+ with init_empty_weights():
+ if isinstance(module, Conv1D):
+ in_features, out_features = module.weight.shape
+ else:
+ in_features = module.in_features
+ out_features = module.out_features
+
+ if quantization_config.quantization_method() == "llm_int8":
+ model._modules[name] = bnb.nn.Linear8bitLt(
+ in_features,
+ out_features,
+ module.bias is not None,
+ has_fp16_weights=quantization_config.llm_int8_has_fp16_weight,
+ threshold=quantization_config.llm_int8_threshold,
+ )
+ has_been_replaced = True
+ else:
+ if (
+ quantization_config.llm_int8_skip_modules is not None
+ and name in quantization_config.llm_int8_skip_modules
+ ):
+ pass
+ else:
+ extra_kwargs = (
+ {"quant_storage": quantization_config.bnb_4bit_quant_storage}
+ if "quant_storage" in list(signature(bnb.nn.Linear4bit).parameters)
+ else {}
+ )
+ model._modules[name] = bnb.nn.Linear4bit(
+ in_features,
+ out_features,
+ module.bias is not None,
+ quantization_config.bnb_4bit_compute_dtype,
+ compress_statistics=quantization_config.bnb_4bit_use_double_quant,
+ quant_type=quantization_config.bnb_4bit_quant_type,
+ **extra_kwargs,
+ )
+ has_been_replaced = True
+ # Store the module class in case we need to transpose the weight later
+ model._modules[name].source_cls = type(module)
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = _replace_with_bnb_linear(
+ module,
+ modules_to_not_convert,
+ current_key_name,
+ quantization_config,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
+
+
+def replace_with_bnb_linear(model, modules_to_not_convert=None, current_key_name=None, quantization_config=None):
+ """
+ A helper function to replace all `torch.nn.Linear` modules by `bnb.nn.Linear8bit` modules from the `bitsandbytes`
+ library. This will enable running your models using mixed int8 precision as described by the paper `LLM.int8():
+ 8-bit Matrix Multiplication for Transformers at Scale`. Make sure `bitsandbytes` compiled with the correct CUDA
+ version of your hardware is installed before running this function. `pip install -i https://test.pypi.org/simple/
+ bitsandbytes`
+
+ The function will be run recursively and replace all `torch.nn.Linear` modules except for the `lm_head` that should
+ be kept as a `torch.nn.Linear` module. The replacement is done under `init_empty_weights` context manager so no
+ CPU/GPU memory is required to run this function. Int8 mixed-precision matrix decomposition works by separating a
+ matrix multiplication into two streams: (1) and systematic feature outlier stream matrix multiplied in fp16
+ (0.01%), (2) a regular stream of int8 matrix multiplication (99.9%). With this method, int8 inference with no
+ predictive degradation is possible for very large models (>=176B parameters).
+
+ Parameters:
+ model (`torch.nn.Module`):
+ Input model or `torch.nn.Module` as the function is run recursively.
+ modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`):
+ Names of the modules to not convert in `Linear8bitLt`. In practice we keep the `lm_head` in full precision
+ for numerical stability reasons.
+ current_key_name (`List[`str`]`, *optional*):
+ An array to track the current key of the recursion. This is used to check whether the current key (part of
+ it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
+ `disk`).
+ quantization_config ('transformers.utils.quantization_config.BitsAndBytesConfig'):
+ To configure and manage settings related to quantization, a technique used to compress neural network models
+ by reducing the precision of the weights and activations, thus making models more efficient in terms of both
+ storage and computation.
+ """
+ modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
+ model, has_been_replaced = _replace_with_bnb_linear(
+ model, modules_to_not_convert, current_key_name, quantization_config
+ )
+
+ if not has_been_replaced:
+ logger.warning(
+ "You are loading your model in 8bit or 4bit but no linear modules were found in your model."
+ " Please double check your model architecture, or submit an issue on github if you think this is"
+ " a bug."
+ )
+
+ return model
+
+
+# For backward compatibility
+def replace_8bit_linear(*args, **kwargs):
+ warnings.warn(
+ "`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead",
+ FutureWarning,
+ )
+ return replace_with_bnb_linear(*args, **kwargs)
+
+
+# For backward compatiblity
+def set_module_8bit_tensor_to_device(*args, **kwargs):
+ warnings.warn(
+ "`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead",
+ FutureWarning,
+ )
+ return set_module_quantized_tensor_to_device(*args, **kwargs)
+
+
+def get_keys_to_not_convert(model):
+ r"""
+ An utility function to get the key of the module to keep in full precision if any For example for CausalLM modules
+ we may want to keep the lm_head in full precision for numerical stability reasons. For other architectures, we want
+ to keep the tied weights of the model. The function will return a list of the keys of the modules to not convert in
+ int8.
+
+ Parameters:
+ model (`torch.nn.Module`):
+ Input model
+ """
+ # Create a copy of the model and tie the weights, then
+ # check if it contains tied weights
+ tied_model = deepcopy(model) # this has 0 cost since it is done inside `init_empty_weights` context manager`
+ tied_model.tie_weights()
+
+ tied_params = find_tied_parameters(tied_model)
+ # For compatibility with Accelerate < 0.18
+ if isinstance(tied_params, dict):
+ tied_keys = sum(list(tied_params.values()), []) + list(tied_params.keys())
+ else:
+ tied_keys = sum(tied_params, [])
+ has_tied_params = len(tied_keys) > 0
+
+ # If there is not tied weights, we want to keep the lm_head(output_embedding) in full precision
+ if not has_tied_params:
+ output_emb = model.get_output_embeddings()
+ if output_emb is not None:
+ list_last_module = [name for name, module in model.named_modules() if id(module) == id(output_emb)]
+ return list_last_module
+
+ # otherwise, no tied weights, no output embedding defined, simply keep the last module in full precision
+ list_modules = list(model.named_parameters())
+ list_last_module = [list_modules[-1][0]]
+ # add last module together with tied weights
+ intersection = set(list_last_module) - set(tied_keys)
+ list_untouched = list(set(tied_keys)) + list(intersection)
+
+ # remove ".weight" from the keys
+ names_to_remove = [".weight", ".bias"]
+ filtered_module_names = []
+ for name in list_untouched:
+ for name_to_remove in names_to_remove:
+ if name_to_remove in name:
+ name = name.replace(name_to_remove, "")
+ filtered_module_names.append(name)
+
+ return filtered_module_names
+
+
+# Copied from PEFT: https://github.com/huggingface/peft/blob/47b3712898539569c02ec5b3ed4a6c36811331a1/src/peft/utils/integrations.py#L41
+def dequantize_bnb_weight(weight: "torch.nn.Parameter", dtype: "torch.dtype", state=None):
+ """
+ Helper function to dequantize 4bit or 8bit bnb weights.
+
+ If the weight is not a bnb quantized weight, it will be returned as is.
+ """
+ if not isinstance(weight, torch.nn.Parameter):
+ raise TypeError(f"Input weight should be of type nn.Parameter, got {type(weight)} instead")
+
+ cls_name = weight.__class__.__name__
+ if cls_name not in ("Params4bit", "Int8Params"):
+ return weight
+
+ if cls_name == "Params4bit":
+ output_tensor = bnb.functional.dequantize_4bit(weight.data, weight.quant_state)
+ logger.warning_once(
+ f"The model is going to be dequantized in {output_tensor.dtype} - if you want to upcast it to another dtype, make sure to pass the desired dtype when quantizing the model through `bnb_4bit_quant_type` argument of `BitsAndBytesConfig`"
+ )
+ return output_tensor.to(dtype)
+
+ if state.SCB is None:
+ state.SCB = weight.SCB
+
+ if hasattr(bnb.functional, "int8_vectorwise_dequant"):
+ # Use bitsandbytes API if available (requires v0.45.0+)
+ dequantized = bnb.functional.int8_vectorwise_dequant(weight.data, state.SCB)
+ else:
+ # Multiply by (scale/127) to dequantize.
+ dequantized = weight.data * state.SCB.view(-1, 1) * 7.874015718698502e-3
+
+ return dequantized.to(dtype)
+
+
+def _create_accelerate_new_hook(old_hook):
+ r"""
+ Creates a new hook based on the old hook. Use it only if you know what you are doing !
+ This method is a copy of: https://github.com/huggingface/peft/blob/748f7968f3a31ec06a1c2b0328993319ad9a150a/src/peft/utils/other.py#L245
+ with some changes
+ """
+ old_hook_cls = getattr(accelerate.hooks, old_hook.__class__.__name__)
+ old_hook_attr = old_hook.__dict__
+ filtered_old_hook_attr = {}
+ old_hook_init_signature = inspect.signature(old_hook_cls.__init__)
+ for k in old_hook_attr.keys():
+ if k in old_hook_init_signature.parameters:
+ filtered_old_hook_attr[k] = old_hook_attr[k]
+ new_hook = old_hook_cls(**filtered_old_hook_attr)
+ return new_hook
+
+
+def _dequantize_and_replace(
+ model,
+ dtype,
+ modules_to_not_convert=None,
+ current_key_name=None,
+ quantization_config=None,
+ has_been_replaced=False,
+):
+ """
+ Converts a quantized model into its dequantized original version. The newly converted model will have
+ some performance drop compared to the original model before quantization - use it only for specific usecases
+ such as QLoRA adapters merging.
+
+ Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
+ """
+ quant_method = quantization_config.quantization_method()
+
+ target_cls = bnb.nn.Linear8bitLt if quant_method == "llm_int8" else bnb.nn.Linear4bit
+
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if isinstance(module, target_cls) and name not in modules_to_not_convert:
+ # Check if the current key is not in the `modules_to_not_convert`
+ current_key_name_str = ".".join(current_key_name)
+
+ if not any(
+ (key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
+ ):
+ bias = getattr(module, "bias", None)
+
+ device = module.weight.device
+ with init_empty_weights():
+ new_module = torch.nn.Linear(module.in_features, module.out_features, bias=bias is not None)
+
+ if quant_method == "llm_int8":
+ state = module.state
+ else:
+ state = None
+
+ new_module.weight = torch.nn.Parameter(dequantize_bnb_weight(module.weight, dtype, state))
+
+ if bias is not None:
+ new_module.bias = bias
+
+ # Create a new hook and attach it in case we use accelerate
+ if hasattr(module, "_hf_hook"):
+ old_hook = module._hf_hook
+ new_hook = _create_accelerate_new_hook(old_hook)
+
+ remove_hook_from_module(module)
+ add_hook_to_module(new_module, new_hook)
+
+ new_module.to(device)
+ model._modules[name] = new_module
+ has_been_replaced = True
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = _dequantize_and_replace(
+ module,
+ dtype,
+ modules_to_not_convert,
+ current_key_name,
+ quantization_config,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
+
+
+def dequantize_and_replace(
+ model,
+ modules_to_not_convert=None,
+ quantization_config=None,
+):
+ model, has_been_replaced = _dequantize_and_replace(
+ model,
+ model.dtype,
+ modules_to_not_convert=modules_to_not_convert,
+ quantization_config=quantization_config,
+ )
+
+ if not has_been_replaced:
+ logger.warning(
+ "For some reason the model has not been properly dequantized. You might see unexpected behavior."
+ )
+
+ return model
+
+
+def _validate_bnb_multi_backend_availability(raise_exception):
+ import bitsandbytes as bnb
+
+ bnb_supported_devices = getattr(bnb, "supported_torch_devices", set())
+ available_devices = set(get_available_devices())
+
+ if available_devices == {"cpu"} and not is_ipex_available():
+ from importlib.util import find_spec
+
+ if find_spec("intel_extension_for_pytorch"):
+ logger.warning(
+ "You have Intel IPEX installed but if you're intending to use it for CPU, it might not have the right version. Be sure to double check that your PyTorch and IPEX installs are compatible."
+ )
+
+ available_devices.discard("cpu") # Only Intel CPU is supported by BNB at the moment
+
+ if not available_devices.intersection(bnb_supported_devices):
+ if raise_exception:
+ bnb_supported_devices_with_info = set( # noqa: C401
+ '"cpu" (needs an Intel CPU and intel_extension_for_pytorch installed and compatible with the PyTorch version)'
+ if device == "cpu"
+ else device
+ for device in bnb_supported_devices
+ )
+ err_msg = (
+ f"None of the available devices `available_devices = {available_devices or None}` are supported by the bitsandbytes version you have installed: `bnb_supported_devices = {bnb_supported_devices_with_info}`. "
+ "Please check the docs to see if the backend you intend to use is available and how to install it: https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend"
+ )
+
+ logger.error(err_msg)
+ raise RuntimeError(err_msg)
+
+ logger.warning("No supported devices found for bitsandbytes multi-backend.")
+ return False
+
+ logger.debug("Multi-backend validation successful.")
+ return True
+
+
+def _validate_bnb_cuda_backend_availability(raise_exception):
+ if not is_torch_available():
+ return False
+
+ import torch
+
+ if not torch.cuda.is_available():
+ log_msg = (
+ "CUDA is required but not available for bitsandbytes. Please consider installing the multi-platform enabled version of bitsandbytes, which is currently a work in progress. "
+ "Please check currently supported platforms and installation instructions at https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend"
+ )
+ if raise_exception:
+ logger.error(log_msg)
+ raise RuntimeError(log_msg)
+
+ logger.warning(log_msg)
+ return False
+
+ logger.debug("CUDA backend validation successful.")
+ return True
+
+
+def validate_bnb_backend_availability(raise_exception=False):
+ """
+ Validates if the available devices are supported by bitsandbytes, optionally raising an exception if not.
+ """
+ if not is_bitsandbytes_available():
+ if importlib.util.find_spec("bitsandbytes") and version.parse(
+ importlib.metadata.version("bitsandbytes")
+ ) < version.parse("0.43.1"):
+ return _validate_bnb_cuda_backend_availability(raise_exception)
+ return False
+
+ if is_bitsandbytes_multi_backend_available():
+ return _validate_bnb_multi_backend_availability(raise_exception)
+ return _validate_bnb_cuda_backend_availability(raise_exception)
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/deepspeed.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/deepspeed.py
new file mode 100644
index 0000000000000000000000000000000000000000..c896a5aa865831bc161d481d5de4a6d6e1cc58ad
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/deepspeed.py
@@ -0,0 +1,499 @@
+# 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.
+"""
+Integration with Deepspeed
+"""
+
+import copy
+import importlib.metadata as importlib_metadata
+import importlib.util
+import weakref
+from functools import partialmethod
+
+from ..dependency_versions_check import dep_version_check
+from ..utils import is_accelerate_available, is_torch_available, is_torch_mlu_available, logging
+
+
+if is_torch_available():
+ import torch
+ from torch import nn
+
+
+logger = logging.get_logger(__name__)
+
+
+def is_deepspeed_available():
+ package_exists = importlib.util.find_spec("deepspeed") is not None
+
+ # Check we're not importing a "deepspeed" directory somewhere but the actual library by trying to grab the version
+ # AND checking it has an author field in the metadata that is HuggingFace.
+ if package_exists:
+ try:
+ if is_torch_mlu_available():
+ _ = importlib_metadata.metadata("deepspeed-mlu")
+ return True
+ _ = importlib_metadata.metadata("deepspeed")
+ return True
+ except importlib_metadata.PackageNotFoundError:
+ return False
+
+
+if is_accelerate_available() and is_deepspeed_available():
+ from accelerate.utils.deepspeed import HfDeepSpeedConfig as DeepSpeedConfig
+else:
+ # Inherits from a dummy `object` if accelerate is not available, so that python succeeds to import this file.
+ # Deepspeed glue code will never inherit this dummy object as it checks if accelerate is available.
+ from builtins import object as DeepSpeedConfig
+
+
+class HfDeepSpeedConfig(DeepSpeedConfig):
+ """
+ This object contains a DeepSpeed configuration dictionary and can be quickly queried for things like zero stage.
+
+ A `weakref` of this object is stored in the module's globals to be able to access the config from areas where
+ things like the Trainer object is not available (e.g. `from_pretrained` and `_get_resized_embeddings`). Therefore
+ it's important that this object remains alive while the program is still running.
+
+ [`Trainer`] uses the `HfTrainerDeepSpeedConfig` subclass instead. That subclass has logic to sync the configuration
+ with values of [`TrainingArguments`] by replacing special placeholder values: `"auto"`. Without this special logic
+ the DeepSpeed configuration is not modified in any way.
+
+ Args:
+ config_file_or_dict (`Union[str, Dict]`): path to DeepSpeed config file or dict.
+
+ """
+
+ def __init__(self, config_file_or_dict):
+ # set global weakref object
+ set_hf_deepspeed_config(self)
+ dep_version_check("accelerate")
+ dep_version_check("deepspeed")
+ super().__init__(config_file_or_dict)
+
+
+class HfTrainerDeepSpeedConfig(HfDeepSpeedConfig):
+ """
+ The `HfTrainerDeepSpeedConfig` object is meant to be created during `TrainingArguments` object creation and has the
+ same lifespan as the latter.
+ """
+
+ def __init__(self, config_file_or_dict):
+ super().__init__(config_file_or_dict)
+ self._dtype = None
+ self.mismatches = []
+
+ def dtype(self):
+ if self._dtype is None:
+ raise ValueError("trainer_config_process() wasn't called yet to tell dtype")
+ return self._dtype
+
+ def is_auto(self, ds_key_long):
+ val = self.get_value(ds_key_long)
+ if val is None:
+ return False
+ else:
+ return val == "auto"
+
+ def fill_match(self, ds_key_long, hf_val, hf_key=None, must_match=True):
+ """
+ A utility method that massages the config file and can optionally verify that the values match.
+
+ 1. Replace "auto" values with `TrainingArguments` value.
+
+ 2. If it wasn't "auto" and `must_match` is true, then check that DS config matches Trainer
+ config values and if mismatched add the entry to `self.mismatched` - will assert during
+ `trainer_config_finalize` for one or more mismatches.
+
+ """
+ config, ds_key = self.find_config_node(ds_key_long)
+ if config is None:
+ return
+
+ if config.get(ds_key) == "auto":
+ config[ds_key] = hf_val
+ return
+
+ if not must_match:
+ return
+
+ ds_val = config.get(ds_key)
+ if ds_val is not None and ds_val != hf_val:
+ self.mismatches.append(f"- ds {ds_key_long}={ds_val} vs hf {hf_key}={hf_val}")
+
+ fill_only = partialmethod(fill_match, must_match=False)
+
+ def trainer_config_process(self, args, auto_find_batch_size=False):
+ """
+ Adjust the config with `TrainingArguments` values. This stage is run during `TrainingArguments` object
+ creation.
+ """
+ # DeepSpeed does:
+ # train_batch_size = world_size * train_micro_batch_size_per_gpu * gradient_accumulation_steps
+ train_batch_size = args.world_size * args.per_device_train_batch_size * args.gradient_accumulation_steps
+ self.fill_match(
+ "train_micro_batch_size_per_gpu",
+ args.per_device_train_batch_size,
+ "per_device_train_batch_size",
+ not auto_find_batch_size,
+ )
+ self.fill_match(
+ "gradient_accumulation_steps",
+ args.gradient_accumulation_steps,
+ "gradient_accumulation_steps",
+ )
+ self.fill_match(
+ "train_batch_size",
+ train_batch_size,
+ "train_batch_size (calculated)",
+ not auto_find_batch_size,
+ )
+ self.fill_match("gradient_clipping", args.max_grad_norm, "max_grad_norm")
+
+ self.fill_match("optimizer.params.lr", args.learning_rate, "learning_rate")
+ self.fill_match(
+ "optimizer.params.betas",
+ [args.adam_beta1, args.adam_beta2],
+ "adam_beta1+adam_beta2",
+ )
+ self.fill_match("optimizer.params.eps", args.adam_epsilon, "adam_epsilon")
+ self.fill_match("optimizer.params.weight_decay", args.weight_decay, "weight_decay")
+
+ self.fill_only("scheduler.params.warmup_min_lr", 0) # not a trainer arg
+ self.fill_match("scheduler.params.warmup_max_lr", args.learning_rate, "learning_rate")
+ # total_num_steps - will get set in trainer_config_finalize
+
+ # fp16
+ if args.fp16 or args.fp16_full_eval:
+ fp16_backend = "apex" if args.fp16_backend == "apex" else "amp"
+ else:
+ fp16_backend = None
+
+ if args.save_on_each_node:
+ # deepspeed uses shared storage by default. Let's override this setting if save_on_each_node == True
+ self.config["checkpoint"] = self.config.get("checkpoint", {})
+ self.config["checkpoint"]["use_node_local_storage"] = args.save_on_each_node
+
+ # amp: similar to the pytorch native amp - it has a bunch of optional params but we won't set
+ # any here unless the user did the work
+ self.fill_match(
+ "fp16.enabled",
+ ((args.fp16 or args.fp16_full_eval) and fp16_backend == "amp"),
+ "fp16|fp16_full_eval+fp16_backend(amp)",
+ )
+
+ # apex: delegates amp work to apex (which needs to be available), but it cannot be used with any
+ # ZeRO features
+ self.fill_match("amp.enabled", fp16_backend == "apex", "fp16+fp16_backend(apex)")
+ self.fill_match("amp.opt_level", args.fp16_opt_level, "fp16_opt_level")
+
+ self.fill_match("bf16.enabled", (args.bf16 or args.bf16_full_eval), "bf16|bf16_full_eval")
+
+ # deepspeed's default mode is fp16 unless there is a config that says differently
+ if self.is_true("bf16.enabled"):
+ self._dtype = torch.bfloat16
+ elif self.is_false("fp16.enabled"):
+ self._dtype = torch.float32
+ else:
+ self._dtype = torch.float16
+
+ def trainer_config_finalize(self, args, model, num_training_steps):
+ """
+ This stage is run after we have the model and know num_training_steps.
+
+ Now we can complete the configuration process.
+ """
+ # zero
+
+ # deal with config keys that use `auto` value and rely on model's hidden_size
+ hidden_size_based_keys = [
+ "zero_optimization.reduce_bucket_size",
+ "zero_optimization.stage3_prefetch_bucket_size",
+ "zero_optimization.stage3_param_persistence_threshold",
+ ]
+ hidden_size_auto_keys = [x for x in hidden_size_based_keys if self.is_auto(x)]
+
+ if len(hidden_size_auto_keys) > 0:
+ if hasattr(model.config, "hidden_size"):
+ hidden_size = model.config.hidden_size
+ elif hasattr(model.config, "hidden_sizes"):
+ # if there are many hidden sizes pick the largest one
+ hidden_size = max(model.config.hidden_sizes)
+ elif hasattr(model.config, "text_config") and hasattr(model.config.text_config, "hidden_size"):
+ hidden_size = model.config.text_config.hidden_size
+ elif hasattr(model.config, "text_config") and hasattr(model.config.text_config, "hidden_sizes"):
+ # if there are many hidden sizes pick the largest one
+ hidden_size = max(model.config.text_config.hidden_sizes)
+ else:
+ raise ValueError(
+ "The model's config file has neither `hidden_size` nor `hidden_sizes` entry, "
+ "therefore it's not possible to automatically fill out the following `auto` entries "
+ f"in the DeepSpeed config file: {hidden_size_auto_keys}. You can fix that by replacing "
+ "`auto` values for these keys with an integer value of your choice."
+ )
+
+ self.fill_only("zero_optimization.reduce_bucket_size", hidden_size * hidden_size)
+ if self.is_zero3():
+ # automatically assign the optimal config values based on model config
+ self.fill_only(
+ "zero_optimization.stage3_prefetch_bucket_size",
+ int(0.9 * hidden_size * hidden_size),
+ )
+ self.fill_only(
+ "zero_optimization.stage3_param_persistence_threshold",
+ 10 * hidden_size,
+ )
+
+ # scheduler
+ self.fill_match(
+ "scheduler.params.total_num_steps",
+ num_training_steps,
+ "num_training_steps (calculated)",
+ )
+ self.fill_match(
+ "scheduler.params.warmup_num_steps",
+ args.get_warmup_steps(num_training_steps),
+ "warmup_steps",
+ )
+
+ if len(self.mismatches) > 0:
+ mismatches = "\n".join(self.mismatches)
+ raise ValueError(
+ "Please correct the following DeepSpeed config values that mismatch TrainingArguments"
+ f" values:\n{mismatches}\nThe easiest method is to set these DeepSpeed config values to 'auto'."
+ )
+
+
+# keep the config object global to be able to access it anywhere during TrainingArguments life-cycle
+_hf_deepspeed_config_weak_ref = None
+
+
+def set_hf_deepspeed_config(hf_deepspeed_config_obj):
+ # this is a special weakref global object to allow us to get to Deepspeed config from APIs
+ # that don't have an easy way to get to the Deepspeed config outside of the Trainer domain.
+ global _hf_deepspeed_config_weak_ref
+ # will go away automatically when HfDeepSpeedConfig is destroyed (when TrainingArguments is destroyed)
+ _hf_deepspeed_config_weak_ref = weakref.ref(hf_deepspeed_config_obj)
+
+
+def unset_hf_deepspeed_config():
+ # useful for unit tests to ensure the global state doesn't leak - call from `tearDown` method
+ global _hf_deepspeed_config_weak_ref
+ _hf_deepspeed_config_weak_ref = None
+
+
+def is_deepspeed_zero3_enabled():
+ if _hf_deepspeed_config_weak_ref is not None and _hf_deepspeed_config_weak_ref() is not None:
+ return _hf_deepspeed_config_weak_ref().is_zero3()
+ else:
+ return False
+
+
+def deepspeed_config():
+ if _hf_deepspeed_config_weak_ref is not None and _hf_deepspeed_config_weak_ref() is not None:
+ return _hf_deepspeed_config_weak_ref().config
+ else:
+ return None
+
+
+def _load_state_dict_into_zero3_model(model_to_load, state_dict, assign_to_params_buffers=False):
+ """
+ Loads state dict into a model specifically for Zero3, since DeepSpeed does not support the `transformers`
+ tensor parallelism API.
+
+ Nearly identical code to PyTorch's `_load_from_state_dict`
+ """
+ # copy state_dict so `_load_state_dict_into_zero3_model` can modify it
+ metadata = getattr(state_dict, "_metadata", None)
+ state_dict = state_dict.copy()
+ if metadata is not None:
+ state_dict._metadata = metadata
+
+ error_msgs = []
+
+ # PyTorch's `_load_from_state_dict` does not copy parameters in a module's descendants
+ # so we need to apply the function recursively.
+ def load(module: nn.Module, state_dict, prefix="", assign_to_params_buffers=False):
+ local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})
+ local_metadata["assign_to_params_buffers"] = assign_to_params_buffers
+
+ args = (state_dict, prefix, local_metadata, True, [], [], error_msgs)
+ # Parameters of module and children will start with prefix. We can exit early if there are none in this
+ # state_dict
+ if is_deepspeed_zero3_enabled() and len([key for key in state_dict if key.startswith(prefix)]) > 0:
+ import deepspeed
+
+ # In sharded models, each shard has only part of the full state_dict, so only gather
+ # parameters that are in the current state_dict.
+ named_parameters = dict(module.named_parameters(prefix=prefix[:-1], recurse=False))
+ params_to_gather = [named_parameters[k] for k in state_dict.keys() if k in named_parameters]
+ if len(params_to_gather) > 0:
+ # because zero3 puts placeholders in model params, this context
+ # manager gathers (unpartitions) the params of the current layer, then loads from
+ # the state dict and then re-partitions them again
+ with deepspeed.zero.GatheredParameters(params_to_gather, modifier_rank=0):
+ if torch.distributed.get_rank() == 0:
+ module._load_from_state_dict(*args)
+
+ for name, child in module._modules.items():
+ if child is not None:
+ load(child, state_dict, prefix + name + ".", assign_to_params_buffers)
+
+ load(model_to_load, state_dict, assign_to_params_buffers=assign_to_params_buffers)
+ # Delete `state_dict` so it could be collected by GC earlier. Note that `state_dict` is a copy of the argument, so
+ # it's safe to delete it.
+ del state_dict
+
+ return error_msgs
+
+
+def deepspeed_optim_sched(trainer, hf_deepspeed_config, args, num_training_steps, model_parameters):
+ """
+ A convenience wrapper that deals with optimizer and lr scheduler configuration.
+ """
+ from accelerate.utils import DummyOptim, DummyScheduler
+
+ config = hf_deepspeed_config.config
+
+ # Mixing and matching DS schedulers and optimizers is supported unless Offload is enabled in which case it's:
+ # 1. DS scheduler + DS optimizer: Yes
+ # 2. HF scheduler + HF optimizer: Mostly*
+ # 3. DS scheduler + HF optimizer: Mostly*
+ # 4. HF scheduler + DS optimizer: Yes
+ #
+ # Mostly*: All non-native DeepSpeed optimizers that have both CPU and GPU implementation should work (except LAMB)
+
+ optimizer = None
+ if "optimizer" in config:
+ if args.adafactor:
+ raise ValueError(
+ "--adafactor was passed, but also found `optimizer` configured in the DeepSpeed config. "
+ "Only one optimizer can be configured."
+ )
+ optimizer = DummyOptim(params=model_parameters)
+ else:
+ if hf_deepspeed_config.is_offload():
+ logger.info(
+ "Detected ZeRO Offload and non-DeepSpeed optimizers: This combination should work as long as the"
+ " custom optimizer has both CPU and GPU implementation (except LAMB)"
+ )
+
+ # ds supports Adam, OneBitAdam, and Lamb optimizers and can import other optimizers from torch.
+ # But trainer uses AdamW by default.
+ optimizer = trainer.create_optimizer()
+ # To use other optimizers requires voiding warranty with: `zero_allow_untested_optimizer`
+ config["zero_allow_untested_optimizer"] = True
+
+ lr_scheduler = None
+ if "scheduler" in config:
+ lr_scheduler = DummyScheduler(optimizer)
+ else:
+ if isinstance(optimizer, DummyOptim):
+
+ def _lr_scheduler_callable(optimizer):
+ # create a shallow copy first, so later modifications do not affect original trainer
+ trainer_copy = copy.copy(trainer)
+ # at the time _lr_scheduler_callable is called, trainer.lr_scheduler has been set
+ # update it to None so that we can re-create a new scheduler
+ trainer_copy.lr_scheduler = None
+ lr_scheduler = trainer_copy.create_scheduler(
+ num_training_steps=num_training_steps, optimizer=optimizer
+ )
+ return lr_scheduler
+
+ lr_scheduler = DummyScheduler(optimizer, lr_scheduler_callable=_lr_scheduler_callable)
+ else:
+ lr_scheduler = trainer.create_scheduler(num_training_steps=num_training_steps, optimizer=optimizer)
+
+ return optimizer, lr_scheduler
+
+
+def deepspeed_init(trainer, num_training_steps, inference=False):
+ """
+ Init DeepSpeed, after updating the DeepSpeed configuration with any relevant Trainer's args.
+
+ If `resume_from_checkpoint` was passed then an attempt to resume from a previously saved checkpoint will be made.
+
+ Args:
+ trainer: Trainer object
+ num_training_steps: per single gpu
+ resume_from_checkpoint: path to a checkpoint if to resume from after normal DeepSpeedEngine load
+ inference: launch in inference mode (no optimizer and no lr scheduler)
+ auto_find_batch_size: whether to ignore the `train_micro_batch_size_per_gpu` argument as it's being
+ set automatically by the auto batch size finder
+
+ Returns: optimizer, lr_scheduler
+
+ We may use `deepspeed_init` more than once during the life of Trainer, when we do - it's a temp hack based on:
+ https://github.com/deepspeedai/DeepSpeed/issues/1394#issuecomment-937405374 until Deepspeed fixes a bug where it
+ can't resume from a checkpoint after it did some stepping https://github.com/deepspeedai/DeepSpeed/issues/1612
+
+ """
+ from deepspeed.utils import logger as ds_logger
+
+ model = trainer.model
+ args = trainer.args
+
+ hf_deepspeed_config = trainer.accelerator.state.deepspeed_plugin.hf_ds_config
+
+ # resume config update - some bits like `model` and `num_training_steps` only become available during train
+ hf_deepspeed_config.trainer_config_finalize(args, model, num_training_steps)
+
+ # set the Deepspeed log level consistent with the Trainer
+ ds_logger.setLevel(args.get_process_log_level())
+
+ if inference:
+ # only Z3 makes sense for the inference
+ if not hf_deepspeed_config.is_zero3():
+ raise ValueError("ZeRO inference only makes sense with ZeRO Stage 3 - please adjust your config")
+
+ # in case the training config is re-used for inference
+ hf_deepspeed_config.del_config_sub_tree("optimizer")
+ hf_deepspeed_config.del_config_sub_tree("lr_scheduler")
+ optimizer, lr_scheduler = None, None
+ model_parameters = None
+ else:
+ trainer.optimizer = None # important for when deepspeed_init is used as re-init
+ model_parameters = list(filter(lambda p: p.requires_grad, model.parameters()))
+ optimizer, lr_scheduler = deepspeed_optim_sched(
+ trainer, hf_deepspeed_config, args, num_training_steps, model_parameters
+ )
+
+ # keep for quick debug:
+ # from pprint import pprint; pprint(config)
+
+ return optimizer, lr_scheduler
+
+
+def deepspeed_load_checkpoint(deepspeed_engine, checkpoint_path, load_module_strict=True):
+ # it's possible that the user is trying to resume from model_path, which doesn't necessarily
+ # contain a deepspeed checkpoint. e.g. examples just check if the dir exists and assume it's
+ # a resume from a checkpoint and not just a local pretrained weight. So we check here if the
+ # path contains what looks like a deepspeed checkpoint
+ import glob
+
+ deepspeed_checkpoint_dirs = sorted(glob.glob(f"{checkpoint_path}/global_step*"))
+
+ if len(deepspeed_checkpoint_dirs) > 0:
+ logger.info(f"Attempting to resume from {checkpoint_path}")
+ # this magically updates self.optimizer and self.lr_scheduler
+ load_path, _ = deepspeed_engine.load_checkpoint(
+ checkpoint_path,
+ load_module_strict=load_module_strict,
+ load_optimizer_states=True,
+ load_lr_scheduler_states=True,
+ )
+ if load_path is None:
+ raise ValueError(f"[deepspeed] failed to resume from checkpoint {checkpoint_path}")
+ else:
+ raise ValueError(f"Can't find a valid checkpoint at {checkpoint_path}")
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/eetq.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/eetq.py
new file mode 100644
index 0000000000000000000000000000000000000000..97698cf1aa37c6279d4f6932ef496ed708e324a7
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/eetq.py
@@ -0,0 +1,121 @@
+# coding=utf-8
+# Copyright 2024 NetEase, Inc. 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.
+from ..utils import is_accelerate_available, is_eetq_available, logging
+
+
+if is_eetq_available():
+ import eetq
+ import torch.nn as nn
+
+if is_accelerate_available():
+ from accelerate import init_empty_weights
+
+logger = logging.get_logger(__name__)
+
+
+def _replace_with_eetq_linear(
+ model,
+ modules_to_not_convert=None,
+ current_key_name=None,
+ quantization_config=None,
+ has_been_replaced=False,
+ pre_quantized=False,
+):
+ """
+ Private method that wraps the recursion for module replacement.
+
+ Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
+ """
+ if current_key_name is None:
+ current_key_name = []
+
+ for name, module in model.named_children():
+ current_key_name.append(name)
+
+ if (isinstance(module, nn.Linear)) and name not in modules_to_not_convert:
+ # Check if the current key is not in the `modules_to_not_convert`
+ current_key_name_str = ".".join(current_key_name)
+ if not any(
+ (key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
+ ):
+ with init_empty_weights():
+ in_features = module.in_features
+ out_features = module.out_features
+ model._modules[name] = eetq.EetqLinear(
+ in_features, out_features, module.bias is not None, module.weight.device
+ )
+ if pre_quantized:
+ model._modules[name].register_scale(module.weight.device)
+ has_been_replaced = True
+
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = _replace_with_eetq_linear(
+ module,
+ modules_to_not_convert,
+ current_key_name,
+ quantization_config,
+ has_been_replaced=has_been_replaced,
+ pre_quantized=pre_quantized,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
+
+
+def replace_with_eetq_linear(
+ model, modules_to_not_convert=None, current_key_name=None, quantization_config=None, pre_quantized=False
+):
+ """
+ A helper function to replace all `torch.nn.Linear` modules by `eetq.EetqLinear` modules from the `eetq`
+ library. This will enable running your models using high performance int8 weight-only gemm kerner from
+ FasterTransformer and TensorRT-LLM. Make sure `eetq` compiled with the correct CUDA
+ version of your hardware is installed before running this function. EETQ shall be installed via the source
+ 'https://github.com/NetEase-FuXi/EETQ'
+
+ The function will be run recursively and replace all `torch.nn.Linear` modules except for the `lm_head` that should
+ be kept as a `torch.nn.Linear` module. The replacement is done under `init_empty_weights` context manager so no
+ CPU/GPU memory is required to run this function. Each weight will be quantized along the channel.
+
+ Parameters:
+ model (`torch.nn.Module`):
+ Input model or `torch.nn.Module` as the function is run recursively.
+ modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`):
+ Names of the modules to not convert in `EetqLinear`. In practice we keep the `lm_head` in full precision
+ for numerical stability reasons.
+ current_key_name (`List[`str`]`, *optional*):
+ An array to track the current key of the recursion. This is used to check whether the current key (part of
+ it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
+ `disk`).
+ """
+
+ modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
+
+ if quantization_config.modules_to_not_convert is not None:
+ modules_to_not_convert.extend(quantization_config.modules_to_not_convert)
+ modules_to_not_convert = list(set(modules_to_not_convert))
+ model, has_been_replaced = _replace_with_eetq_linear(
+ model, modules_to_not_convert, current_key_name, quantization_config, pre_quantized=pre_quantized
+ )
+
+ if not has_been_replaced:
+ logger.warning(
+ "You are loading your model using eetq but no linear modules were found in your model."
+ " Please double check your model architecture, or submit an issue on github if you think this is"
+ " a bug."
+ )
+
+ return model
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/executorch.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/executorch.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ee525ddf8e182b3b1a80020fee09f5862208269
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/executorch.py
@@ -0,0 +1,218 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# 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 torch
+
+from ..utils.import_utils import is_torch_available
+
+
+if is_torch_available():
+ from transformers import PreTrainedModel, StaticCache
+ from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_3
+
+
+class TorchExportableModuleWithStaticCache(torch.nn.Module):
+ """
+ A wrapper module designed to make a `PreTrainedModel` exportable with `torch.export`,
+ specifically for use with static caching. This module ensures that the exported model
+ is compatible with further lowering and execution in `ExecuTorch`.
+
+ Note:
+ This class is specifically designed to support export process using `torch.export`
+ in a way that ensures the model can be further lowered and run efficiently in `ExecuTorch`.
+ """
+
+ def __init__(self, model: PreTrainedModel):
+ """
+ Initializes the wrapper module with the pretrained model.
+
+ Args:
+ model (`PreTrainedModel`): The pretrained model to wrap. The model must have caching
+ enabled and use a 'static' caching implementation.
+
+ Raises:
+ AssertionError: If the pretrained model does not have caching enabled or if it does
+ not use a 'static' caching implementation in `model.generation_config`.
+ """
+ super().__init__()
+
+ # Sanity checks
+ if model.generation_config is None:
+ raise AssertionError(
+ "The model must have a generation config to be exported with static caching. "
+ "Please set `generation_config`."
+ )
+
+ if not model.generation_config.use_cache:
+ raise AssertionError(
+ "The model must have caching enabled to be exported with static caching. "
+ "Please set `generation_config.use_cache=True`."
+ )
+
+ if model.generation_config.cache_implementation != "static":
+ raise AssertionError(
+ "The model must use a 'static' caching implementation to be exported with static caching. "
+ "Please set `generation_config.cache_implementation='static'`."
+ )
+
+ self.model = model
+ self.static_cache = StaticCache(
+ config=self.model.config,
+ batch_size=self.model.generation_config.cache_config.batch_size,
+ max_cache_len=self.model.generation_config.cache_config.max_cache_len,
+ device=self.model.generation_config.cache_config.device,
+ dtype=self.model.dtype,
+ )
+ for i in range(len(self.static_cache.key_cache)):
+ self.register_buffer(f"key_cache_{i}", self.static_cache.key_cache[i], persistent=False)
+ self.register_buffer(f"value_cache_{i}", self.static_cache.value_cache[i], persistent=False)
+
+ self.is_causal = any("CausalLM" in arch for arch in self.model.config.architectures)
+ if self.is_causal:
+ causal_mask = torch.tril(
+ torch.ones(
+ self.static_cache.max_cache_len,
+ self.static_cache.max_cache_len,
+ dtype=torch.bool,
+ )
+ )
+ self.register_buffer("mask", causal_mask, persistent=False)
+
+ def forward(self, input_ids: torch.Tensor, cache_position: torch.Tensor):
+ """
+ Forward pass of the module, which is compatible with the ExecuTorch runtime.
+
+ Args:
+ input_ids (`torch.Tensor`): Tensor representing current input token id to the module.
+ cache_position (`torch.Tensor`): Tensor representing current input position in the cache.
+
+ Returns:
+ torch.Tensor: Logits output from the model.
+
+ This forward adapter serves two primary purposes:
+
+ 1. **Making the Model `torch.export`-Compatible**:
+ The adapter hides unsupported objects, such as the `Cache`, from the graph inputs and outputs,
+ enabling the model to be exportable using `torch.export` without encountering issues.
+
+ 2. **Ensuring Compatibility with `ExecuTorch` runtime**:
+ The adapter matches the model's forward signature with that in `executorch/extension/llm/runner`,
+ ensuring that the exported model can be executed in `ExecuTorch` out-of-the-box.
+ """
+ _, seqlen = input_ids.shape
+ attn_mask = self.mask[cache_position, :seqlen] if self.is_causal else None
+ position_ids = cache_position.unsqueeze(0)
+ past_key_values = self.static_cache
+
+ outs = self.model(
+ input_ids=input_ids,
+ attention_mask=attn_mask,
+ position_ids=position_ids,
+ cache_position=cache_position,
+ past_key_values=past_key_values,
+ use_cache=True,
+ )
+ return outs.logits
+
+ @staticmethod
+ def generate(
+ exported_program: torch.export.ExportedProgram, prompt_token_ids: torch.Tensor, max_new_tokens: int
+ ) -> torch.Tensor:
+ """
+ Generate a sequence of tokens using an exported program.
+
+ This util function is designed to test exported models by simulating the generation process.
+ It processes the input prompt tokens sequentially (no parallel prefill).
+ This generate function is not intended to replace the original `generate` method, and the support
+ for leveraging the original `generate` is potentially planed!
+
+ Args:
+ exported_program (`torch.export.ExportedProgram`): The exported program generated via `torch.export`.
+ prompt_token_ids (`torch.Tensor`): Tensor representing the input prompt token IDs.
+ max_new_tokens (`int`): Maximum number of new tokens to generate. Note that the total generation
+ length is limited by both `max_new_tokens` and the model's cache size.
+
+ Returns:
+ torch.Tensor: A tensor containing the generated sequence of token IDs, including the original prompt tokens.
+ """
+ prompt_token_len = prompt_token_ids.shape[-1]
+ max_generation_length = prompt_token_len + max_new_tokens
+ for buffer_name, buffer in exported_program.named_buffers():
+ if buffer_name.startswith("key_cache"):
+ max_cache_len = buffer.shape[2]
+ max_generation_length = min(max_generation_length, max_cache_len)
+ break
+
+ response_tokens = []
+ for input_pos in range(min(max_generation_length, prompt_token_len)):
+ result = exported_program.module().forward(
+ input_ids=prompt_token_ids[:, input_pos : input_pos + 1],
+ cache_position=torch.tensor([input_pos], dtype=torch.long),
+ )
+ response_tokens.append(prompt_token_ids[0][input_pos].item())
+
+ current_token = torch.argmax(result[:, -1, :], dim=-1).item()
+ response_tokens.append(current_token)
+
+ while len(response_tokens) < max_generation_length:
+ result = exported_program.module().forward(
+ input_ids=torch.tensor([[current_token]], dtype=torch.long),
+ cache_position=torch.tensor([len(response_tokens)], dtype=torch.long),
+ )
+ current_token = torch.argmax(result[:, -1, :], dim=-1).item()
+ response_tokens.append(current_token)
+
+ return torch.tensor([response_tokens], dtype=torch.long)
+
+
+def convert_and_export_with_cache(
+ model: PreTrainedModel,
+ example_input_ids: torch.Tensor = None,
+ example_cache_position: torch.Tensor = None,
+):
+ """
+ Convert a `PreTrainedModel` into an exportable module and export it using `torch.export`,
+ ensuring the exported model is compatible with `ExecuTorch`.
+
+ Args:
+ model (`PreTrainedModel`): The pretrained model to be exported.
+ example_input_ids (`torch.Tensor`): Example input token id used by `torch.export`.
+ example_cache_position (`torch.Tensor`): Example current cache position used by `torch.export`.
+
+ Returns:
+ Exported program (`torch.export.ExportedProgram`): The exported program generated via `torch.export`.
+ """
+
+ if not is_torch_greater_or_equal_than_2_3:
+ raise ImportError("torch >= 2.3 is required.")
+
+ import torch.export._trace
+
+ with torch.no_grad():
+ # TODO: The default inputs only work for text models. We need to add support for vision/audio models.
+ example_input_ids = (
+ example_input_ids if example_input_ids is not None else torch.tensor([[1]], dtype=torch.long)
+ )
+ example_cache_position = (
+ example_cache_position if example_cache_position is not None else torch.tensor([0], dtype=torch.long)
+ )
+
+ # Due to issue https://github.com/pytorch/pytorch/issues/128394, we need to switch to use an internal
+ # export API and pre_dispatch=False. Switch to use the public API once the issue is included in 2.5 release.
+ exported_program = torch.export._trace._export(
+ TorchExportableModuleWithStaticCache(model),
+ args=(example_input_ids,),
+ kwargs={"cache_position": example_cache_position},
+ pre_dispatch=False,
+ strict=True,
+ )
+ return exported_program
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/fbgemm_fp8.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/fbgemm_fp8.py
new file mode 100644
index 0000000000000000000000000000000000000000..71c2b570cc0a7381c66a3b7797a4f72f442d0b6a
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/fbgemm_fp8.py
@@ -0,0 +1,164 @@
+# 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.
+
+from ..utils import is_accelerate_available, is_fbgemm_gpu_available, is_torch_available, logging
+
+
+if is_torch_available():
+ import torch
+ from torch import nn
+
+if is_accelerate_available():
+ from accelerate import init_empty_weights
+
+if is_fbgemm_gpu_available():
+ import fbgemm_gpu.experimental.gen_ai # noqa: F401
+
+logger = logging.get_logger(__name__)
+
+
+class FbgemmFp8Linear(torch.nn.Module):
+ def __init__(self, in_features, out_features, bias, weight_dtype=torch.float32):
+ super().__init__()
+ self.in_features = in_features
+ self.out_features = out_features
+
+ self.register_buffer("weight", torch.zeros((out_features, in_features), dtype=torch.float8_e4m3fn))
+ self.register_buffer("weight_scale", torch.zeros((out_features, 1), dtype=weight_dtype))
+ self.register_buffer("input_scale_ub", torch.zeros([1], dtype=torch.float), persistent=False)
+
+ if bias:
+ self.register_buffer("bias", torch.zeros((self.out_features), dtype=weight_dtype))
+ else:
+ self.bias = None
+
+ def forward(self, x):
+ num_tokens = None
+ # quantize_fp8_per_row will squash the leading dimensions, so save the desired shape here
+ output_shape = (*x.shape[:-1], -1)
+ # x_quantized and x_scale are not necessarily on the same device as x, this is an issue.
+ # https://github.com/pytorch/FBGEMM/blob/e08af8539c391437f447173863df0f3f6f6f1855/fbgemm_gpu/experimental/gen_ai/src/quantize/quantize.cu#L1237C3-L1237C45
+ x_quantized, x_scale = torch.ops.fbgemm.quantize_fp8_per_row(
+ x.view(-1, x.shape[-1]), num_tokens, self.input_scale_ub
+ )
+ # moving x_quantized, x_scale here creates glibberish output ... However, if we move the output, it works
+ # x_quantized, x_scale = x_quantized.to(x.device), x_scale.to(x.device)
+
+ # The computation still happens on the device where self.weight is even if x_quantized is not on the same device as self.weight
+ output = torch.ops.fbgemm.f8f8bf16_rowwise(
+ x_quantized, self.weight, x_scale, self.weight_scale, use_fast_accum=True
+ )
+ output = output + self.bias if self.bias is not None else output
+ # Hacky for now, we have the output to the device of x
+ output = output.to(x.device)
+ output = output.reshape(output_shape)
+ del x_quantized, x_scale
+ return output
+
+
+def _replace_with_fbgemm_fp8_linear(
+ model,
+ modules_to_not_convert=None,
+ current_key_name=None,
+ quantization_config=None,
+ has_been_replaced=False,
+ pre_quantized=False,
+):
+ """
+ Private method that wraps the recursion for module replacement.
+
+ Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
+ """
+ if current_key_name is None:
+ current_key_name = []
+
+ for name, module in model.named_children():
+ current_key_name.append(name)
+
+ if (isinstance(module, nn.Linear)) and name not in modules_to_not_convert:
+ # Check if the current key is not in the `modules_to_not_convert`
+ current_key_name_str = ".".join(current_key_name)
+ if not any(
+ (key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
+ ):
+ with init_empty_weights(include_buffers=True):
+ in_features = module.in_features
+ out_features = module.out_features
+ model._modules[name] = FbgemmFp8Linear(
+ in_features,
+ out_features,
+ module.bias is not None,
+ )
+ has_been_replaced = True
+
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+ # set non persistant buffer outside of init_empty_weights
+ model._modules[name].input_scale_ub = torch.tensor(
+ [quantization_config.activation_scale_ub], dtype=torch.float
+ )
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = _replace_with_fbgemm_fp8_linear(
+ module,
+ modules_to_not_convert,
+ current_key_name,
+ quantization_config,
+ has_been_replaced=has_been_replaced,
+ pre_quantized=pre_quantized,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
+
+
+def replace_with_fbgemm_fp8_linear(
+ model, modules_to_not_convert=None, current_key_name=None, quantization_config=None, pre_quantized=False
+):
+ """
+ A helper function to replace all `torch.nn.Linear` modules by `FbgemmFp8Linear` modules.
+ This will enable running your models using high performance fp8 kernel from FBGEMM library.
+
+ The function will be run recursively and replace all `torch.nn.Linear` modules except for the `lm_head` that should
+ be kept as a `torch.nn.Linear` module. The replacement is done under `init_empty_weights` context manager so no
+ CPU/GPU memory is required to run this function. Each weight will be quantized along the channel.
+
+ Parameters:
+ model (`torch.nn.Module`):
+ Input model or `torch.nn.Module` as the function is run recursively.
+ modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`):
+ Names of the modules to not convert in `FP8Linear`. In practice we keep the `lm_head` in full precision
+ for numerical stability reasons.
+ current_key_name (`List[`str`]`, *optional*):
+ An array to track the current key of the recursion. This is used to check whether the current key (part of
+ it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
+ `disk`).
+ """
+
+ modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
+
+ if quantization_config.modules_to_not_convert is not None:
+ modules_to_not_convert.extend(quantization_config.modules_to_not_convert)
+ modules_to_not_convert = list(set(modules_to_not_convert))
+ model, has_been_replaced = _replace_with_fbgemm_fp8_linear(
+ model, modules_to_not_convert, current_key_name, quantization_config, pre_quantized=pre_quantized
+ )
+
+ if not has_been_replaced:
+ logger.warning(
+ "You are loading your model using FP8 quantization but no linear modules were found in your model."
+ " Please double check your model architecture, or submit an issue on github if you think this is"
+ " a bug."
+ )
+
+ return model
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/finegrained_fp8.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/finegrained_fp8.py
new file mode 100644
index 0000000000000000000000000000000000000000..0815df43445306b6b4aefd2c2d9a4ea35169a044
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/finegrained_fp8.py
@@ -0,0 +1,420 @@
+# 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.
+
+from typing import List, Optional, Tuple
+
+from ..utils import is_accelerate_available, is_torch_available, logging
+
+
+if is_torch_available():
+ import torch
+ import torch.nn as nn
+ import triton
+ import triton.language as tl
+ from torch.nn import functional as F
+
+if is_accelerate_available():
+ from accelerate import init_empty_weights
+
+
+logger = logging.get_logger(__name__)
+
+
+# Copied from https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/inference/kernel.py
+@triton.jit
+def act_quant_kernel(x_ptr, y_ptr, s_ptr, BLOCK_SIZE: tl.constexpr):
+ pid = tl.program_id(axis=0)
+ offs = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
+ x = tl.load(x_ptr + offs).to(tl.float32)
+ s = tl.max(tl.abs(x)) / 448.0
+ y = x / s
+ y = y.to(y_ptr.dtype.element_ty)
+ tl.store(y_ptr + offs, y)
+ tl.store(s_ptr + pid, s)
+
+
+def act_quant(x: torch.Tensor, block_size: int = 128) -> Tuple[torch.Tensor, torch.Tensor]:
+ assert x.is_contiguous()
+ assert x.shape[-1] % block_size == 0
+ y = torch.empty_like(x, dtype=torch.float8_e4m3fn)
+ s = x.new_empty(*x.size()[:-1], x.size(-1) // block_size, dtype=torch.float32)
+
+ def grid(meta):
+ return (triton.cdiv(x.numel(), meta["BLOCK_SIZE"]),)
+
+ act_quant_kernel[grid](x, y, s, BLOCK_SIZE=block_size)
+ return y, s
+
+
+# Adapted from https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/layers/quantization/fp8_kernel.py
+@triton.jit
+def _w8a8_block_fp8_matmul(
+ # Pointers to inputs and output
+ A,
+ B,
+ C,
+ As,
+ Bs,
+ # Shape for matmul
+ M,
+ N,
+ K,
+ # Block size for block-wise quantization
+ group_n,
+ group_k,
+ # Stride for inputs and output
+ stride_am,
+ stride_ak,
+ stride_bk,
+ stride_bn,
+ stride_cm,
+ stride_cn,
+ stride_As_m,
+ stride_As_k,
+ stride_Bs_k,
+ stride_Bs_n,
+ # Meta-parameters
+ BLOCK_SIZE_M: tl.constexpr,
+ BLOCK_SIZE_N: tl.constexpr,
+ BLOCK_SIZE_K: tl.constexpr,
+ GROUP_SIZE_M: tl.constexpr,
+):
+ """Triton-accelerated function used to perform linear operations (dot
+ product) on input tensors `A` and `B` with block-wise quantization, and
+ store the result in output tensor `C`.
+ """
+
+ pid = tl.program_id(axis=0)
+ num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
+ num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
+ num_pid_in_group = GROUP_SIZE_M * num_pid_n
+ group_id = pid // num_pid_in_group
+ first_pid_m = group_id * GROUP_SIZE_M
+ group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
+ pid_m = first_pid_m + (pid % group_size_m)
+ pid_n = (pid % num_pid_in_group) // group_size_m
+
+ offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
+ offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
+ offs_k = tl.arange(0, BLOCK_SIZE_K)
+ a_ptrs = A + (offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak)
+ b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
+
+ As_ptrs = As + offs_am * stride_As_m
+ offs_bsn = offs_bn // group_n
+ Bs_ptrs = Bs + offs_bsn * stride_Bs_n
+
+ accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
+ for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
+ a = tl.load(a_ptrs, mask=offs_k[None, :] < K - k * BLOCK_SIZE_K, other=0.0)
+ b = tl.load(b_ptrs, mask=offs_k[:, None] < K - k * BLOCK_SIZE_K, other=0.0)
+
+ k_start = k * BLOCK_SIZE_K
+ offs_ks = k_start // group_k
+ a_s = tl.load(As_ptrs + offs_ks * stride_As_k)
+ b_s = tl.load(Bs_ptrs + offs_ks * stride_Bs_k)
+
+ accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
+ a_ptrs += BLOCK_SIZE_K * stride_ak
+ b_ptrs += BLOCK_SIZE_K * stride_bk
+
+ if C.dtype.element_ty == tl.bfloat16:
+ c = accumulator.to(tl.bfloat16)
+ elif C.dtype.element_ty == tl.float16:
+ c = accumulator.to(tl.float16)
+ else:
+ c = accumulator.to(tl.float32)
+
+ offs_cm = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
+ offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
+ c_ptrs = C + stride_cm * offs_cm[:, None] + stride_cn * offs_cn[None, :]
+ c_mask = (offs_cm[:, None] < M) & (offs_cn[None, :] < N)
+ tl.store(c_ptrs, c, mask=c_mask)
+
+
+def w8a8_block_fp8_matmul_triton(
+ A: torch.Tensor,
+ B: torch.Tensor,
+ As: torch.Tensor,
+ Bs: torch.Tensor,
+ block_size: List[int],
+ output_dtype: torch.dtype = torch.float32,
+) -> torch.Tensor:
+ """This function performs matrix multiplication with block-wise
+ quantization.
+ It takes two input tensors `A` and `B` with scales `As` and `Bs`.
+ The output is returned in the specified `output_dtype`.
+ Args:
+ A: The input tensor, e.g., activation.
+ B: The input tensor, e.g., weight.
+ As: The per-token-group quantization scale for `A`.
+ Bs: The per-block quantization scale for `B`.
+ block_size: The block size for per-block quantization. It should
+ be 2-dim, e.g., [128, 128].
+ output_dytpe: The dtype of the returned tensor.
+ Returns:
+ torch.Tensor: The result of matmul.
+ """
+ assert len(block_size) == 2
+ block_n, block_k = block_size[0], block_size[1]
+
+ assert A.shape[-1] == B.shape[-1]
+ assert A.shape[:-1] == As.shape[:-1] and A.is_contiguous()
+ assert triton.cdiv(A.shape[-1], block_k) == As.shape[-1]
+ M = A.numel() // A.shape[-1]
+
+ assert B.ndim == 2 and B.is_contiguous() and Bs.ndim == 2
+ N, K = B.shape
+ assert triton.cdiv(N, block_n) == Bs.shape[0]
+ assert triton.cdiv(K, block_k) == Bs.shape[1]
+
+ C_shape = A.shape[:-1] + (N,)
+ C = A.new_empty(C_shape, dtype=output_dtype)
+
+ BLOCK_SIZE_M = 128
+ if M < BLOCK_SIZE_M:
+ BLOCK_SIZE_M = triton.next_power_of_2(M)
+ BLOCK_SIZE_M = max(BLOCK_SIZE_M, 16)
+ BLOCK_SIZE_K = block_k
+ assert block_k % BLOCK_SIZE_K == 0
+ BLOCK_SIZE_N = block_n
+
+ def grid(META):
+ return (triton.cdiv(M, META["BLOCK_SIZE_M"]) * triton.cdiv(N, META["BLOCK_SIZE_N"]),)
+
+ _w8a8_block_fp8_matmul[grid](
+ A,
+ B,
+ C,
+ As,
+ Bs,
+ M,
+ N,
+ K,
+ block_n,
+ block_k,
+ A.stride(-2),
+ A.stride(-1),
+ B.stride(1),
+ B.stride(0),
+ C.stride(-2),
+ C.stride(-1),
+ As.stride(-2),
+ As.stride(-1),
+ Bs.stride(1),
+ Bs.stride(0),
+ BLOCK_SIZE_M=BLOCK_SIZE_M,
+ BLOCK_SIZE_N=BLOCK_SIZE_N,
+ BLOCK_SIZE_K=BLOCK_SIZE_K,
+ GROUP_SIZE_M=8,
+ )
+
+ return C
+
+
+# Python version of the above triton function, it's much slower than the triton version, for testing
+@torch.compile
+def w8a8_block_fp8_matmul_compile(
+ input_q: torch.Tensor, # [batch, seq_len, hidden_dim]
+ weight_q: torch.Tensor, # [out_features, hidden_dim]
+ input_scale: torch.Tensor, # [batch * seq_len, num_input_groups]
+ weight_scale: torch.Tensor, # [num_weight_blocks_m, num_weight_blocks_n]
+ block_size: Optional[Tuple[int, int]] = None, # (M=128, N=128) for weights for example
+ output_dtype: torch.dtype = torch.float32,
+) -> torch.Tensor:
+ """
+ Performs blocked matrix multiplication with FP8 quantized matrices.
+
+ Args:
+ input_q: Quantized input tensor with 1x128 block quantization
+ weight_q: Quantized weight tensor with 128x128 block quantization
+ input_scale: Scaling factors for input blocks
+ weight_scale: Scaling factors for weight blocks
+ block_size: Tuple of (M, N) for weight block dimensions
+ output_dtype: Desired output dtype
+ """
+ batch_size, seq_len, hidden_dim = input_q.shape if input_q.ndim == 3 else (1, input_q.shape[0], input_q.shape[1])
+ out_features = weight_q.shape[0]
+
+ # Reshape input for batched matmul
+ input_reshaped = input_q.view(-1, hidden_dim) # [batch*seq_len, hidden_dim]
+ input_scale_reshaped = input_scale.view(input_scale.shape[0], -1) # [batch*seq_len, 1]
+ # Calculate number of blocks
+ num_weight_blocks_m = out_features // block_size[0]
+ num_weight_blocks_n = hidden_dim // block_size[1]
+
+ output = torch.zeros((batch_size * seq_len, out_features), dtype=torch.float32, device=input_q.device)
+
+ for i in range(num_weight_blocks_m):
+ m_start = i * block_size[0]
+ m_end = m_start + block_size[0]
+
+ for j in range(num_weight_blocks_n):
+ n_start = j * block_size[1]
+ n_end = n_start + block_size[1]
+
+ # Extract current blocks
+ input_block = input_reshaped[:, n_start:n_end]
+ weight_block = weight_q[m_start:m_end, n_start:n_end]
+
+ # Get corresponding scales
+ curr_input_scale = input_scale_reshaped[:, j : j + 1] # [batch*seq_len, 1]
+ curr_weight_scale = weight_scale[i, j] # scalar
+
+ block_result = (
+ torch._scaled_mm(
+ input_block,
+ weight_block.t(),
+ scale_a=torch.tensor(1, dtype=torch.float32, device=input_q.device),
+ scale_b=curr_weight_scale,
+ out_dtype=output_dtype,
+ )
+ * curr_input_scale
+ )
+
+ output[:, m_start:m_end] += block_result
+
+ output = output.view(batch_size, seq_len, out_features)
+
+ return output.to(output_dtype)
+
+
+class FP8Linear(nn.Module):
+ dtype = torch.float8_e4m3fn
+
+ def __init__(
+ self,
+ in_features: int,
+ out_features: int,
+ bias: bool = False,
+ dtype=None,
+ block_size: Optional[Tuple[int, int]] = None,
+ device=None,
+ activation_scheme="dynamic",
+ ):
+ super().__init__()
+ self.in_features = in_features
+ self.out_features = out_features
+
+ self.register_buffer("weight", torch.empty(out_features, in_features, dtype=FP8Linear.dtype, device=device))
+
+ scale_out_features = (out_features + block_size[0] - 1) // block_size[0]
+ scale_in_features = (in_features + block_size[1] - 1) // block_size[1]
+ self.register_buffer(
+ "weight_scale_inv", torch.empty(scale_out_features, scale_in_features, dtype=torch.float32, device=device)
+ )
+
+ self.block_size = block_size
+
+ self.activation_scheme = activation_scheme
+
+ if bias:
+ self.bias = nn.Parameter(torch.empty(self.out_features))
+ else:
+ self.register_parameter("bias", None)
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ if self.weight.element_size() > 1:
+ return F.linear(input, self.weight, self.bias)
+ else:
+ # Context manager used to switch among the available cuda devices
+ with torch.cuda.device(input.device):
+ qinput, scale = act_quant(input, self.block_size[1])
+ # Blocks the CPU until all CUDA operations on the specified device are complete. It is used to ensure that the results of the
+ # preceding operations are ready before proceeding
+ torch.cuda.synchronize(device=input.device)
+ with torch.cuda.device(input.device):
+ output = w8a8_block_fp8_matmul_triton(
+ qinput,
+ self.weight,
+ scale,
+ self.weight_scale_inv,
+ self.block_size,
+ output_dtype=input.dtype,
+ )
+ torch.cuda.synchronize(device=input.device)
+ if self.bias is not None:
+ output = output + self.bias
+ return output.to(dtype=input.dtype)
+
+
+def _replace_with_fp8_linear(
+ model,
+ modules_to_not_convert=None,
+ current_key_name=None,
+ quantization_config=None,
+ has_been_replaced=False,
+):
+ """Replace Linear layers with FP8Linear."""
+ if current_key_name is None:
+ current_key_name = []
+
+ for name, module in model.named_children():
+ current_key_name.append(name)
+
+ if isinstance(module, nn.Linear) and name not in (modules_to_not_convert or []):
+ current_key_name_str = ".".join(current_key_name)
+ if not any(key in current_key_name_str for key in (modules_to_not_convert or [])):
+ with init_empty_weights():
+ model._modules[name] = FP8Linear(
+ in_features=module.in_features,
+ out_features=module.out_features,
+ bias=module.bias is not None,
+ device=module.weight.device,
+ dtype=module.weight.dtype,
+ activation_scheme=quantization_config.activation_scheme,
+ block_size=quantization_config.weight_block_size,
+ )
+ has_been_replaced = True
+
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = _replace_with_fp8_linear(
+ module,
+ modules_to_not_convert,
+ current_key_name,
+ quantization_config,
+ has_been_replaced=has_been_replaced,
+ )
+
+ current_key_name.pop(-1)
+
+ return model, has_been_replaced
+
+
+def replace_with_fp8_linear(
+ model,
+ modules_to_not_convert=None,
+ quantization_config=None,
+):
+ """Helper function to replace model layers with FP8 versions."""
+ modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
+
+ if quantization_config.modules_to_not_convert is not None:
+ modules_to_not_convert.extend(quantization_config.modules_to_not_convert)
+ modules_to_not_convert = list(set(modules_to_not_convert))
+
+ model, has_been_replaced = _replace_with_fp8_linear(
+ model,
+ modules_to_not_convert=modules_to_not_convert,
+ quantization_config=quantization_config,
+ )
+
+ if not has_been_replaced:
+ logger.warning(
+ "You are loading your model using fp8 but no linear modules were found in your model."
+ " Please double check your model architecture."
+ )
+
+ return model
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/flash_attention.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/flash_attention.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3ca4bea484d22176f49dd74d93666ce7c7e2e40
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/flash_attention.py
@@ -0,0 +1,66 @@
+from typing import Optional, Tuple
+
+import torch
+
+from ..modeling_flash_attention_utils import _flash_attention_forward
+from ..utils import is_flash_attn_greater_or_equal_2_10
+
+
+_use_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
+
+
+def flash_attention_forward(
+ module: torch.nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: Optional[torch.Tensor],
+ dropout: float = 0.0,
+ scaling: Optional[float] = None,
+ sliding_window: Optional[int] = None,
+ softcap: Optional[float] = None,
+ **kwargs,
+) -> Tuple[torch.Tensor, None]:
+ # This is before the transpose
+ seq_len = query.shape[2]
+
+ # FA2 uses non-transposed inputs
+ query = query.transpose(1, 2)
+ key = key.transpose(1, 2)
+ value = value.transpose(1, 2)
+
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
+ # cast them back in the correct dtype just to be sure everything works as expected.
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
+ # in fp32. (usually our RMSNorm modules handle it correctly)
+ target_dtype = None
+ if query.dtype == torch.float32:
+ if torch.is_autocast_enabled():
+ target_dtype = torch.get_autocast_gpu_dtype()
+ # Handle the case where the model is quantized
+ elif hasattr(module.config, "_pre_quantization_dtype"):
+ target_dtype = module.config._pre_quantization_dtype
+ else:
+ target_dtype = next(layer for layer in module.modules() if isinstance(layer, torch.nn.Linear)).weight.dtype
+
+ # FA2 always relies on the value set in the module, so remove it if present in kwargs to avoid passing it twice
+ kwargs.pop("is_causal", None)
+
+ attn_output = _flash_attention_forward(
+ query,
+ key,
+ value,
+ attention_mask,
+ query_length=seq_len,
+ is_causal=module.is_causal,
+ dropout=dropout,
+ softmax_scale=scaling,
+ sliding_window=sliding_window,
+ softcap=softcap,
+ use_top_left_mask=_use_top_left_mask,
+ target_dtype=target_dtype,
+ **kwargs,
+ )
+
+ return attn_output, None
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/flex_attention.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/flex_attention.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0a054998c8a3121fae1cbe9196475b92cbc9a16
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/flex_attention.py
@@ -0,0 +1,193 @@
+"""
+Partially inspired by torchtune's flex attention implementation
+
+Citation:
+@software{torchtune,
+ title = {torchtune: PyTorch's finetuning library},
+ author = {torchtune maintainers and contributors},
+ url = {https//github.com/pytorch/torchtune},
+ license = {BSD-3-Clause},
+ month = apr,
+ year = {2024}
+}
+"""
+# coding=utf-8
+# Copyright 2025 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.
+
+from typing import Optional, Tuple, Union
+
+import torch
+
+from ..utils import is_torch_flex_attn_available
+
+
+if is_torch_flex_attn_available():
+ from torch.nn.attention.flex_attention import (
+ BlockMask,
+ flex_attention,
+ )
+ from torch.nn.attention.flex_attention import (
+ create_block_mask as create_block_causal_mask_flex,
+ )
+
+
+class WrappedFlexAttention:
+ """
+ We are doing a singleton class so that flex attention is compiled once when it's first called.
+ """
+
+ _instance = None
+ _is_flex_compiled = False
+ _compiled_flex_attention = None
+
+ def __new__(cls, *args, **kwargs):
+ if cls._instance is None:
+ # Create a new instance if one doesn't already exist
+ cls._instance = super().__new__(cls)
+ return cls._instance
+
+ @torch.compiler.disable(recursive=False)
+ def __init__(self):
+ """
+ Initialize or update the singleton instance.
+ """
+ if self._is_flex_compiled is False:
+ self._compiled_flex_attention = torch.compile(flex_attention, dynamic=False)
+ self._is_flex_compiled = True
+
+ def __call__(self):
+ return self._compiled_flex_attention
+
+
+def make_flex_block_causal_mask(attention_mask_2d: torch.Tensor) -> "BlockMask":
+ """
+ Create a block causal document mask for a batch of sequences, both packed and unpacked.
+ Create Block causal logic and passing it into :func:`torch.nn.attention.flex_attention.create_block_mask`.
+ The resultant BlockMask is a compressed representation of the full block causal
+ mask. BlockMask is essential for performant computation of flex attention.
+ See: https://pytorch.org/blog/flexattention/
+
+ Args:
+ attention_mask_2d (torch.Tensor): Attention mask for packed and padded sequences
+ of shape (batch_size, total_seq_len). e.g.
+
+ For unpacked sequence:
+ [[1, 1, 1, 1, 0, 0, 0],
+ [1, 1, 1, 1, 1, 0, 0]]
+
+ For packed sequence:
+ [[1, 1, 1, 2, 2, 2, 0],
+ [1, 1, 2, 2, 2, 3, 3]]
+
+ Returns:
+ BlockMask
+ """
+ device = attention_mask_2d.device
+
+ document_ids = attention_mask_2d
+ batch_size, total_seq_len = document_ids.shape
+
+ # Instead of passing a tensor mask, flex attention requires a mask_mod function
+ # that determines which elements of QK^T should be included in the attention
+ # computation prior to the softmax. For sample packing, we need both the
+ # logic for both causal mask and document mask. See PyTorch's official
+ # blog post for more details: https://pytorch.org/blog/flexattention/#mask-mods
+ def causal_mask_mod(batch_idx, head_idx, q_idx, kv_idx):
+ """
+ Defines the logic of a block causal mask by combining both a standard causal mask
+ and a block diagonal document mask.
+
+ See :func:`~torchtune.modules.attention_utils.create_block_causal_mask`
+ for an illustration.
+ """
+ causal_mask = q_idx >= kv_idx
+ document_mask = document_ids[batch_idx, q_idx] == document_ids[batch_idx, kv_idx]
+ padding_mask = document_ids[batch_idx, q_idx] > 0
+ return causal_mask & document_mask & padding_mask
+
+ return create_block_causal_mask_flex(
+ mask_mod=causal_mask_mod,
+ B=batch_size,
+ H=None, # attention head
+ Q_LEN=total_seq_len,
+ KV_LEN=total_seq_len,
+ device=device,
+ )
+
+
+@torch.compiler.disable(recursive=False)
+def compile_friendly_flex_attention(
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ **kwargs,
+) -> torch.Tensor:
+ # First call initialise singleton wrapper object, second call invokes the object method to return compiled flex attention
+ flex_attention_compiled = WrappedFlexAttention()()
+ return flex_attention_compiled(
+ query,
+ key,
+ value,
+ **kwargs,
+ )
+
+
+def flex_attention_forward(
+ module: torch.nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: Union[torch.Tensor, "BlockMask"],
+ scaling: Optional[float] = None,
+ softcap: Optional[float] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ **kwargs,
+) -> Tuple[torch.Tensor, torch.Tensor]:
+ block_mask = None
+ causal_mask = None
+ if isinstance(attention_mask, BlockMask):
+ block_mask = attention_mask
+ else:
+ causal_mask = attention_mask
+
+ if causal_mask is not None:
+ causal_mask = causal_mask[:, :, :, : key.shape[-2]]
+
+ def score_mod(score, batch_idx, head_idx, q_idx, kv_idx):
+ if softcap is not None:
+ score = softcap * torch.tanh(score / softcap)
+ if causal_mask is not None:
+ score = score + causal_mask[batch_idx][0][q_idx][kv_idx]
+ if head_mask is not None:
+ score = score + head_mask[batch_idx][head_idx][0][0]
+ return score
+
+ attn_output, attention_weights = compile_friendly_flex_attention(
+ query,
+ key,
+ value,
+ score_mod=score_mod,
+ block_mask=block_mask,
+ enable_gqa=True,
+ scale=scaling,
+ # Last time checked on PyTorch == 2.5.1: Flex Attention always computes the lse regardless.
+ # For simplification, we thus always return it as no additional computations are introduced.
+ return_lse=True,
+ )
+ # lse is returned in float32
+ attention_weights = attention_weights.to(value.dtype)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attention_weights
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/fsdp.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/fsdp.py
new file mode 100644
index 0000000000000000000000000000000000000000..332231c04f433f4ebd1364347c5cbce62dd498e6
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/fsdp.py
@@ -0,0 +1,38 @@
+# 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.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from ..utils import is_torch_available
+
+
+if TYPE_CHECKING:
+ from torch import nn
+
+
+def is_fsdp_managed_module(module: nn.Module) -> bool:
+ if not is_torch_available():
+ return False
+
+ import torch
+
+ if not torch.distributed.is_available():
+ return False
+
+ import torch.distributed.fsdp
+
+ return isinstance(module, torch.distributed.fsdp.FullyShardedDataParallel) or getattr(
+ module, "_is_fsdp_managed_module", False
+ )
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/ggml.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/ggml.py
new file mode 100644
index 0000000000000000000000000000000000000000..db7d93cad0427acd2c12683edd177bf28c1ceb07
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/ggml.py
@@ -0,0 +1,692 @@
+# coding=utf-8
+# Copyright 2024 The ggml.ai team and The HuggingFace Inc. team. and pygguf author (github.com/99991)
+# https://github.com/99991/pygguf
+#
+# 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.
+"""
+Integration with GGML / The file is copied and adapted from https://github.com/99991/pygguf
+with extra methods beings exposed
+"""
+
+from array import array
+
+import numpy as np
+from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
+from tokenizers.models import BPE, Unigram
+
+from .. import AddedToken
+from ..convert_slow_tokenizer import GemmaConverter, GPT2Converter, LlamaConverter, Qwen2Converter, T5Converter
+from ..utils import logging
+from ..utils.logging import tqdm
+
+
+logger = logging.get_logger(__name__)
+
+
+GGUF_CONFIG_MAPPING = {
+ "general": {
+ "architecture": "model_type",
+ "name": "_model_name_or_path",
+ },
+ "llama": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ # NOTE: rope.dimension_count==head_dim only suitable for llama/mistral
+ "rope.dimension_count": "head_dim",
+ "rope.freq_base": "rope_theta",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_rms_epsilon": "rms_norm_eps",
+ "vocab_size": "vocab_size",
+ },
+ "mistral": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ # NOTE: rope.dimension_count==head_dim only suitable for llama/mistral
+ "rope.dimension_count": "head_dim",
+ "rope.freq_base": "rope_theta",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_rms_epsilon": "rms_norm_eps",
+ "vocab_size": "vocab_size",
+ },
+ "qwen2": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ "rope.dimension_count": None,
+ "rope.freq_base": "rope_theta",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_rms_epsilon": "rms_norm_eps",
+ "vocab_size": "vocab_size",
+ },
+ "qwen2moe": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ "rope.dimension_count": None,
+ "rope.freq_base": "rope_theta",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_rms_epsilon": "rms_norm_eps",
+ "vocab_size": "vocab_size",
+ "expert_count": "num_experts",
+ "expert_used_count": "num_experts_per_tok",
+ },
+ "falcon": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ "rope.dimension_count": None,
+ "rope.freq_base": "rope_theta",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_rms_epsilon": "rms_norm_eps",
+ "vocab_size": "vocab_size",
+ },
+ "tokenizer": {
+ "ggml.bos_token_id": "bos_token_id",
+ "ggml.eos_token_id": "eos_token_id",
+ "ggml.unknown_token_id": "unk_token_id",
+ "ggml.padding_token_id": "pad_token_id",
+ },
+ "phi3": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ "rope.dimension_count": None,
+ "rope.freq_base": "rope_theta",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_rms_epsilon": "rms_norm_eps",
+ "vocab_size": "vocab_size",
+ },
+ "bloom": {
+ "block_count": "n_layer",
+ "embedding_length": "hidden_size",
+ "attention.head_count": "n_head",
+ "vocab_size": "vocab_size",
+ "attention.layer_norm_epsilon": "layer_norm_epsilon",
+ },
+ "t5": {
+ "context_length": "n_positions",
+ "block_count": "num_layers",
+ "feed_forward_length": "d_ff",
+ "embedding_length": "d_model",
+ "attention.key_length": "d_kv",
+ "attention.head_count": "num_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_epsilon": "layer_norm_epsilon",
+ "attention.relative_buckets_count": "relative_attention_num_buckets",
+ "decoder_start_token_id": "decoder_start_token_id",
+ "vocab_size": "vocab_size",
+ },
+ "stablelm": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ "rope.dimension_count": None,
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_epsilon": "layer_norm_eps",
+ "vocab_size": "vocab_size",
+ },
+ "gpt2": {
+ "block_count": "n_layer",
+ "context_length": "n_ctx",
+ "embedding_length": "n_embd",
+ "feed_forward_length": "feed_forward_length",
+ "attention.head_count": "n_head",
+ "attention.layer_norm_epsilon": "layer_norm_epsilon",
+ },
+ "starcoder2": {
+ "block_count": "num_hidden_layers",
+ "context_length": "max_position_embeddings",
+ "embedding_length": "hidden_size",
+ "feed_forward_length": "intermediate_size",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_epsilon": "norm_epsilon",
+ },
+ "mamba": {
+ "vocab_size": "vocab_size",
+ "context_length": "max_position_embeddings",
+ "embedding_length": "hidden_size",
+ "attention.layer_norm_rms_epsilon": "layer_norm_epsilon",
+ "block_count": "num_hidden_layers",
+ "ssm.conv_kernel": "conv_kernel",
+ "ssm.state_size": "state_size",
+ "ssm.time_step_rank": "time_step_rank",
+ "ssm.inner_size": "intermediate_size",
+ },
+ "nemotron": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ "rope.dimension_count": None,
+ "rope.freq_base": "rope_theta",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_rms_epsilon": "norm_eps",
+ "vocab_size": "vocab_size",
+ },
+ "gemma2": {
+ "context_length": "max_position_embeddings",
+ "block_count": "num_hidden_layers",
+ "feed_forward_length": "intermediate_size",
+ "embedding_length": "hidden_size",
+ "rope.dimension_count": None,
+ "rope.freq_base": "rope_theta",
+ # NOTE: Gemma2 has key_length==value_length==head_dim
+ # See: https://github.com/ggerganov/llama.cpp/blob/2e2f8f093cd4fb6bbb87ba84f6b9684fa082f3fa/convert_hf_to_gguf.py#L3293-L3294
+ "attention.key_length": "head_dim",
+ "attention.head_count": "num_attention_heads",
+ "attention.head_count_kv": "num_key_value_heads",
+ "attention.layer_norm_rms_epsilon": "rms_norm_eps",
+ "vocab_size": "vocab_size",
+ },
+}
+
+GGUF_TOKENIZER_MAPPING = {
+ "tokenizer": {
+ "ggml.model": "tokenizer_type",
+ "ggml.tokens": "tokens",
+ "ggml.scores": "scores",
+ "ggml.token_type": "token_type",
+ "ggml.merges": "merges",
+ "ggml.bos_token_id": "bos_token_id",
+ "ggml.eos_token_id": "eos_token_id",
+ "ggml.unknown_token_id": "unk_token_id",
+ "ggml.padding_token_id": "pad_token_id",
+ "ggml.add_space_prefix": "add_prefix_space",
+ },
+ "tokenizer_config": {
+ "chat_template": "chat_template",
+ "ggml.model": "model_type",
+ "ggml.bos_token_id": "bos_token_id",
+ "ggml.eos_token_id": "eos_token_id",
+ "ggml.unknown_token_id": "unk_token_id",
+ "ggml.padding_token_id": "pad_token_id",
+ },
+}
+
+
+def _gguf_parse_value(_value, data_type):
+ if not isinstance(data_type, list):
+ data_type = [data_type]
+ if len(data_type) == 1:
+ data_type = data_type[0]
+ array_data_type = None
+ else:
+ if data_type[0] != 9:
+ raise ValueError("Received multiple types, therefore expected the first type to indicate an array.")
+ data_type, array_data_type = data_type
+
+ if data_type in [0, 1, 2, 3, 4, 5, 10, 11]:
+ _value = int(_value[0])
+ elif data_type in [6, 12]:
+ _value = float(_value[0])
+ elif data_type in [7]:
+ _value = bool(_value[0])
+ elif data_type in [8]:
+ _value = array("B", list(_value)).tobytes().decode()
+ elif data_type in [9]:
+ _value = _gguf_parse_value(_value, array_data_type)
+ return _value
+
+
+class GGUFTokenizerSkeleton:
+ def __init__(self, dict_):
+ for k, v in dict_.items():
+ setattr(self, k, v)
+
+ if not hasattr(self, "merges"):
+ if not hasattr(self, "tokens") or not hasattr(self, "scores"):
+ raise ValueError(
+ "tokens and scores need to be passed for a LLaMa tokenizer without merges to be instantiated."
+ )
+ tokens = self.tokens
+ scores = self.scores
+ vocab = {t: scores[i] for i, t in enumerate(tokens)}
+
+ logger.warning("Merges were not in checkpoint, building merges on the fly.")
+ merges = []
+ for merge, piece_score in tqdm(vocab.items()):
+ local = []
+ for index in range(1, len(merge)):
+ piece_l, piece_r = merge[:index], merge[index:]
+ if piece_l in tokens and piece_r in tokens:
+ local.append((piece_l, piece_r, piece_score))
+ local = sorted(local, key=lambda x: (vocab[x[0]], vocab[x[1]]), reverse=True)
+ merges.extend(local)
+ merges = sorted(merges, key=lambda val: val[2], reverse=True)
+ merges = [(val[0], val[1]) for val in merges]
+ self.merges = merges
+ else:
+ self.merges = [tuple(merge.split(" ")) for merge in self.merges]
+ if not hasattr(self, "scores"):
+ self.scores = [None for _ in range(len(self.tokens))]
+
+ if not hasattr(self, "added_tokens"):
+ self.added_tokens = []
+
+ if not hasattr(self, "unk_token_id"):
+ self.unk_token_id = None
+
+ # Llama2 uses the field `unknown_token_id`
+ if hasattr(self, "unknown_token_id") and self.unk_token_id is None:
+ self.unk_token_id = self.unknown_token_id
+
+
+class GGUFLlamaConverter(LlamaConverter):
+ def __init__(self, tokenizer_dict):
+ self.proto = GGUFTokenizerSkeleton(tokenizer_dict)
+ self.original_tokenizer = self.proto
+ self.additional_kwargs = {}
+ self.is_llama_3_tokenizer = getattr(self.proto, "tokenizer_type", "llama") != "llama"
+
+ def vocab(self, proto):
+ return list(zip(proto.tokens, proto.scores))
+
+ def merges(self, proto):
+ return proto.merges
+
+ def tokenizer(self, proto):
+ vocab_scores = self.vocab(self.proto)
+ merges = self.merges(self.proto)
+ bpe_vocab = {word: i for i, (word, _score) in enumerate(vocab_scores)}
+
+ unk_token = proto.tokens[proto.unk_token_id] if proto.unk_token_id is not None else None
+ bos_token = proto.tokens[proto.bos_token_id] if getattr(proto, "bos_token_id", None) is not None else None
+ eos_token = proto.tokens[proto.bos_token_id] if getattr(proto, "eos_token_id", None) is not None else None
+
+ tokenizer = Tokenizer(
+ BPE(
+ bpe_vocab,
+ merges,
+ unk_token=unk_token,
+ fuse_unk=True,
+ byte_fallback=True,
+ )
+ )
+
+ special_tokens = []
+
+ if not hasattr(self.proto, "token_type"):
+ if unk_token is not None:
+ special_tokens.append(AddedToken(unk_token, normalized=False, special=True))
+
+ if bos_token is not None:
+ special_tokens.append(AddedToken(bos_token, normalized=False, special=True))
+
+ if eos_token is not None:
+ special_tokens.append(AddedToken(eos_token, normalized=False, special=True))
+ else:
+ # 3 stands for special tokens
+ special_tokens_idx = np.where(np.array(self.proto.token_type) == 3)[0]
+
+ for idx in special_tokens_idx:
+ special_tokens.append(AddedToken(self.proto.tokens[idx], normalized=False, special=True))
+
+ if len(special_tokens) != 0:
+ tokenizer.add_special_tokens(special_tokens)
+
+ if len(self.proto.added_tokens) != 0:
+ tokenizer.add_tokens(
+ [AddedToken(added_token, normalized=False, special=False) for added_token in self.proto.added_tokens]
+ )
+
+ self.additional_kwargs["unk_token"] = unk_token
+ self.additional_kwargs["eos_token"] = bos_token
+ self.additional_kwargs["bos_token"] = eos_token
+
+ if self.is_llama_3_tokenizer:
+ self.additional_kwargs["add_prefix_space"] = None
+ self.additional_kwargs["clean_up_tokenization_spaces"] = True
+
+ self.additional_kwargs["legacy"] = False
+ self.original_tokenizer.legacy = False
+
+ return tokenizer
+
+ def decoder(self, replacement, add_prefix_space):
+ sequence = [
+ decoders.ByteFallback(),
+ decoders.Fuse(),
+ decoders.Replace("▁", " "),
+ ]
+
+ if self.is_llama_3_tokenizer:
+ sequence += [decoders.ByteLevel(add_prefix_space=False, trim_offsets=False, use_regex=True)]
+
+ if add_prefix_space:
+ sequence += [decoders.Strip(content=" ", left=1)]
+ return decoders.Sequence(sequence)
+
+ def converted(self):
+ # Copied partly from converted method in SpmConverter class
+ tokenizer = self.tokenizer(self.proto)
+
+ # Tokenizer assemble
+ normalizer = self.normalizer(self.proto)
+ if normalizer is not None:
+ tokenizer.normalizer = normalizer
+
+ replacement = "▁"
+ add_prefix_space = True
+ if hasattr(self.original_tokenizer, "add_prefix_space"):
+ add_prefix_space = self.original_tokenizer.add_prefix_space
+
+ pre_tokenizer = self.pre_tokenizer(replacement, add_prefix_space)
+ if pre_tokenizer is not None:
+ tokenizer.pre_tokenizer = pre_tokenizer
+
+ tokenizer.decoder = self.decoder(replacement, add_prefix_space)
+ post_processor = self.post_processor()
+ if post_processor:
+ tokenizer.post_processor = post_processor
+
+ # HACK: patch the llama-3 tokenizer to use the correspinding pre-tokenizer
+ # and normalizer
+ if self.is_llama_3_tokenizer:
+ tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(
+ add_prefix_space=False, trim_offsets=False, use_regex=True
+ )
+ # This is tricky as the additional kwargs are passed after legacy is force-set in LlamaTokenizer's
+ # init.
+ tokenizer.normalizer = normalizers.Sequence([])
+
+ return tokenizer
+
+
+class GGUFQwen2Converter(Qwen2Converter):
+ def __init__(self, tokenizer_dict):
+ self.original_tokenizer = GGUFTokenizerSkeleton(tokenizer_dict)
+ self.additional_kwargs = {}
+
+ def converted(self) -> Tokenizer:
+ vocab = {word: i for i, word in enumerate(self.original_tokenizer.tokens)}
+ merges = self.original_tokenizer.merges
+ tokenizer = super().converted(vocab, merges)
+
+ tokenizer.add_special_tokens(
+ [
+ AddedToken("<|endoftext|>", normalized=False, special=True),
+ AddedToken("<|im_start|>", normalized=False, special=True),
+ AddedToken("<|im_end|>", normalized=False, special=True),
+ ]
+ )
+ return tokenizer
+
+
+class GGUFPhi3Converter(LlamaConverter):
+ def __init__(self, tokenizer_dict):
+ self.proto = GGUFTokenizerSkeleton(tokenizer_dict)
+ self.original_tokenizer = self.proto
+ self.additional_kwargs = {}
+
+ def vocab(self, proto):
+ return list(zip(proto.tokens, proto.scores))
+
+ def merges(self, proto):
+ return proto.merges
+
+ def tokenizer(self, proto):
+ vocab_scores = self.vocab(self.proto)
+ merges = self.merges(self.proto)
+ bpe_vocab = {word: i for i, (word, _score) in enumerate(vocab_scores)}
+
+ tokenizer = Tokenizer(BPE(bpe_vocab, merges))
+ # add the special tokens from phi3 tokenizer config
+ tokenizer.add_special_tokens(
+ [
+ AddedToken("", rstrip=True, lstrip=False, normalized=False, special=True),
+ AddedToken("<|endoftext|>", normalized=False, special=True),
+ AddedToken("<|assistant|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|placeholder1|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|placeholder2|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|placeholder3|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|placeholder4|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|system|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|end|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|placeholder5|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|placeholder6|>", rstrip=True, normalized=False, special=True),
+ AddedToken("<|user|>", rstrip=True, normalized=False, special=True),
+ ]
+ )
+
+ self.additional_kwargs["unk_token"] = (
+ proto.tokens[proto.unk_token_id] if proto.unk_token_id is not None else None
+ )
+ self.additional_kwargs["eos_token"] = (
+ proto.tokens[proto.eos_token_id] if proto.eos_token_id is not None else None
+ )
+ self.additional_kwargs["bos_token"] = (
+ proto.tokens[proto.bos_token_id] if proto.bos_token_id is not None else None
+ )
+ self.additional_kwargs["pad_token"] = (
+ proto.tokens[proto.pad_token_id] if proto.pad_token_id is not None else None
+ )
+
+ return tokenizer
+
+ def decoder(self, replacement, add_prefix_space):
+ sequence = [
+ decoders.ByteFallback(),
+ decoders.Fuse(),
+ decoders.Replace(replacement, " "),
+ ]
+
+ if add_prefix_space:
+ sequence += [decoders.Strip(content=" ", left=1)]
+ return decoders.Sequence(sequence)
+
+ def converted(self) -> Tokenizer:
+ tokenizer = self.tokenizer(self.proto)
+
+ replacement = "▁"
+ add_prefix_space = True
+ if hasattr(self.original_tokenizer, "add_prefix_space"):
+ add_prefix_space = self.original_tokenizer.add_prefix_space
+
+ tokenizer.decoder = self.decoder(replacement, add_prefix_space)
+
+ return tokenizer
+
+
+class GGUFGPTConverter(GPT2Converter):
+ def __init__(self, tokenizer_dict):
+ self.original_tokenizer = GGUFTokenizerSkeleton(tokenizer_dict)
+ self.additional_kwargs = {}
+
+ def converted(self) -> Tokenizer:
+ vocab = {word: i for i, word in enumerate(self.original_tokenizer.tokens)}
+ merges = self.original_tokenizer.merges
+ tokenizer = super().converted(vocab, merges)
+ return tokenizer
+
+
+class GGUFT5Converter(T5Converter):
+ def __init__(self, tokenizer_dict):
+ # set dummy data to avoid unnecessary merges calculation
+ tokenizer_dict["merges"] = ["dummy text"]
+
+ self.proto = GGUFTokenizerSkeleton(tokenizer_dict)
+ self.token2id = {k: v for v, k in enumerate(self.proto.tokens)}
+ self.original_tokenizer = self.proto
+ self.additional_kwargs = {}
+
+ def vocab(self, proto):
+ return list(zip(proto.tokens, proto.scores))
+
+ def normalizer(self, proto):
+ if getattr(self.original_tokenizer, "legacy", True):
+ sequence = []
+ if getattr(self.original_tokenizer, "add_prefix_space", True):
+ sequence += [normalizers.Prepend(prepend="▁")]
+ sequence += [normalizers.Replace(pattern=" ", content="▁")]
+ return normalizers.Sequence(sequence)
+ return None # non-legacy, no normalizer
+
+ def post_processor(self):
+ return processors.TemplateProcessing(
+ single=["$A", ""],
+ pair=["$A", "", "$B", ""],
+ special_tokens=[
+ ("", self.token2id[""]),
+ ],
+ )
+
+ def converted(self) -> Tokenizer:
+ vocab_scores = self.vocab(self.proto)
+ tokenizer = Tokenizer(
+ Unigram(
+ vocab_scores,
+ unk_id=self.proto.unk_token_id,
+ byte_fallback=False,
+ )
+ )
+
+ # Tokenizer assemble
+ normalizer = self.normalizer(self.proto)
+ if normalizer is not None:
+ tokenizer.normalizer = normalizer
+
+ replacement = "▁"
+ add_prefix_space = True
+ if hasattr(self.original_tokenizer, "add_prefix_space"):
+ add_prefix_space = self.original_tokenizer.add_prefix_space
+
+ pre_tokenizer = self.pre_tokenizer(replacement, add_prefix_space)
+ if pre_tokenizer is not None:
+ tokenizer.pre_tokenizer = pre_tokenizer
+
+ tokenizer.decoder = self.decoder(replacement, add_prefix_space)
+ post_processor = self.post_processor()
+ if post_processor:
+ tokenizer.post_processor = post_processor
+
+ return tokenizer
+
+
+class GGUFGemmaConverter(GemmaConverter):
+ def __init__(self, tokenizer_dict):
+ # set dummy data to avoid unnecessary merges calculation
+ tokenizer_dict["merges"] = ["dummy text"]
+
+ self.proto = GGUFTokenizerSkeleton(tokenizer_dict)
+ self.original_tokenizer = self.proto
+ self.additional_kwargs = {}
+
+ def vocab(self, proto):
+ original_vocab = list(zip(proto.tokens, proto.scores))
+ updated_vocab = []
+
+ for token, score in original_vocab:
+ if token == "<0x09>":
+ updated_vocab.append(("\t", score))
+ elif " " in token and len(token.strip()) == 0:
+ underscores = "▁" * len(token)
+ updated_vocab.append((underscores, score))
+ else:
+ updated_vocab.append((token, score))
+
+ return updated_vocab
+
+ def normalizer(self, proto):
+ return normalizers.Replace(" ", "▁")
+
+ def decoder(self, replacement, add_prefix_space):
+ sequence = [
+ decoders.Replace("▁", " "),
+ decoders.ByteFallback(),
+ decoders.Fuse(),
+ ]
+
+ if add_prefix_space:
+ sequence += [decoders.Strip(content=" ", left=1)]
+ return decoders.Sequence(sequence)
+
+ def converted(self) -> Tokenizer:
+ vocab_scores = self.vocab(self.proto)
+ tokenizer = Tokenizer(
+ Unigram(
+ vocab_scores,
+ unk_id=self.proto.unk_token_id,
+ byte_fallback=self.handle_byte_fallback,
+ )
+ )
+
+ normalizer = self.normalizer(self.proto)
+ if normalizer is not None:
+ tokenizer.normalizer = normalizer
+
+ replacement = "▁"
+ add_prefix_space = True
+ if hasattr(self.original_tokenizer, "add_prefix_space"):
+ add_prefix_space = self.original_tokenizer.add_prefix_space
+
+ tokenizer.decoder = self.decoder(replacement, add_prefix_space)
+ pre_tokenizer = self.pre_tokenizer(replacement, add_prefix_space)
+ if pre_tokenizer is not None:
+ tokenizer.pre_tokenizer = pre_tokenizer
+
+ return tokenizer
+
+
+GGUF_TO_FAST_CONVERTERS = {
+ "llama": GGUFLlamaConverter,
+ "qwen2": GGUFQwen2Converter,
+ "qwen2_moe": GGUFQwen2Converter,
+ "phi3": GGUFPhi3Converter,
+ "bloom": GGUFGPTConverter,
+ "falcon": GGUFGPTConverter,
+ "stablelm": GGUFGPTConverter,
+ "gpt2": GGUFGPTConverter,
+ "starcoder2": GGUFGPTConverter,
+ "t5": GGUFT5Converter,
+ "mamba": GGUFGPTConverter,
+ "nemotron": GGUFGPTConverter,
+ "gemma2": GGUFGemmaConverter,
+}
+
+
+def convert_gguf_tokenizer(architecture, tokenizer_dict) -> Tokenizer:
+ """
+ Utilities to convert a slow tokenizer instance in a fast tokenizer instance.
+
+ Args:
+ architecture (`str`): The model architecture derived from gguf file.
+ transformer_tokenizer ([`~tokenization_utils_base.PreTrainedTokenizer`]):
+ Instance of a slow tokenizer to convert in the backend tokenizer for
+ [`~tokenization_utils_base.PreTrainedTokenizerFast`].
+
+ Return:
+ A instance of [`~tokenizers.Tokenizer`] to be used as the backend tokenizer of a
+ [`~tokenization_utils_base.PreTrainedTokenizerFast`]
+ """
+ tokenizer_class_name = architecture
+ converter = GGUF_TO_FAST_CONVERTERS[tokenizer_class_name](tokenizer_dict)
+ fast_tokenizer = converter.converted()
+ return fast_tokenizer, converter.additional_kwargs
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/higgs.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/higgs.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ba35eb4e4fd052c610beaab16211b2b43d2e01b
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/higgs.py
@@ -0,0 +1,655 @@
+# 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.
+"HIGGS through FLUTE (Flexible Lookup Table Engine for LUT-quantized LLMs) integration file"
+
+from math import sqrt
+
+from ..utils import (
+ is_flute_available,
+ is_hadamard_available,
+ is_torch_available,
+)
+
+
+if is_torch_available():
+ import torch
+ from torch import nn
+
+
+if is_flute_available():
+ from flute.integrations.higgs import prepare_data_transposed
+ from flute.tune import TuneMetaData, qgemm_v2
+
+if is_hadamard_available():
+ from fast_hadamard_transform import hadamard_transform
+
+
+def pad_to_block(tensor, dims, had_block_size, value=0):
+ pad_dims = [0 for _ in range(2 * len(tensor.shape))]
+ for dim in dims:
+ size = tensor.shape[dim]
+ next_multiple_of_1024 = ((size - 1) // had_block_size + 1) * had_block_size
+ delta = next_multiple_of_1024 - size
+ pad_dims[-2 * dim - 1] = delta
+
+ return nn.functional.pad(tensor, pad_dims, "constant", value)
+
+
+def get_higgs_grid(p: int, n: int):
+ if (p, n) == (2, 256):
+ return torch.tensor(
+ [
+ [-2.501467704772949, 0.17954708635807037],
+ [-0.6761789321899414, 1.2728623151779175],
+ [-1.8025816679000854, 0.7613157629966736],
+ [-0.538287878036499, -2.6028504371643066],
+ [0.8415029644966125, -0.8600977659225464],
+ [0.7023013234138489, 3.3138747215270996],
+ [0.5699077844619751, 2.5782253742218018],
+ [3.292393207550049, -0.6016128063201904],
+ [0.5561617016792297, -1.7723814249038696],
+ [-2.1012380123138428, 0.020958125591278076],
+ [0.46085724234580994, 0.8428705334663391],
+ [1.4548040628433228, -0.6156039237976074],
+ [3.210029363632202, 0.3546904921531677],
+ [0.8893890976905823, -0.5967988967895508],
+ [0.8618854284286499, -3.2061192989349365],
+ [1.1360996961593628, -0.23852407932281494],
+ [1.6646337509155273, -0.9265465140342712],
+ [1.4767773151397705, 1.2476022243499756],
+ [-1.0511897802352905, 1.94503915309906],
+ [-1.56318998336792, -0.3264186680316925],
+ [-0.1829211413860321, 0.2922491431236267],
+ [-0.8950616717338562, -1.3887052536010742],
+ [-0.08206957578659058, -1.329533576965332],
+ [-0.487422913312912, 1.4817842245101929],
+ [-1.6769757270812988, -2.8269758224487305],
+ [-1.5057679414749146, 1.8905963897705078],
+ [1.8335362672805786, 1.0515104532241821],
+ [0.3273945450782776, 1.0491033792495728],
+ [-3.295924186706543, -0.7021600008010864],
+ [-1.8428784608840942, -1.2315762042999268],
+ [-0.8575026392936707, -1.7005949020385742],
+ [-1.120667815208435, 0.6467998027801514],
+ [-0.1588846743106842, -1.804071068763733],
+ [-0.8539647459983826, 0.5645008683204651],
+ [-1.4192019701004028, -0.6175029873847961],
+ [1.0799058675765991, 1.7871345281600952],
+ [1.171311855316162, 0.7511613965034485],
+ [2.162078380584717, 0.8044339418411255],
+ [1.3969420194625854, -1.243762493133545],
+ [-0.23818807303905487, 0.053944624960422516],
+ [2.304199457168579, -1.2667627334594727],
+ [1.4225027561187744, 0.568610668182373],
+ [0.376836895942688, -0.7134661674499512],
+ [2.0404467582702637, 0.4087389409542084],
+ [0.7639489769935608, -1.1367933750152588],
+ [0.3622530400753021, -1.4827953577041626],
+ [0.4100743532180786, 0.36108437180519104],
+ [-1.5867475271224976, -1.618212342262268],
+ [-2.2769672870635986, -1.2132309675216675],
+ [0.9184022545814514, -0.34428009390830994],
+ [-0.3902314603328705, 0.21785245835781097],
+ [3.120687484741211, 1.3077973127365112],
+ [1.587440848350525, -1.6506884098052979],
+ [-1.718808889389038, -0.038405973464250565],
+ [-0.6888407468795776, -0.8402308821678162],
+ [-0.7981445789337158, -1.1117373704910278],
+ [-2.4124443531036377, 1.3419722318649292],
+ [-0.6611530184745789, 0.9939885139465332],
+ [-0.33103418350219727, -0.16702833771705627],
+ [-2.4091389179229736, -2.326857566833496],
+ [1.6610108613967896, -2.159703254699707],
+ [0.014884627424180508, 0.3887578248977661],
+ [0.029668325558304787, 1.8786455392837524],
+ [1.180362582206726, 2.699317216873169],
+ [1.821286678314209, -0.5960053205490112],
+ [-0.44835323095321655, 3.327436685562134],
+ [-0.3714401423931122, -2.1466753482818604],
+ [-1.1103475093841553, -2.4536871910095215],
+ [-0.39110705256462097, 0.6670510172843933],
+ [0.474752813577652, -1.1959707736968994],
+ [-0.013110585510730743, -2.52519154548645],
+ [-2.0836575031280518, -1.703289270401001],
+ [-1.1077687740325928, -0.1252644956111908],
+ [-0.4138077199459076, 1.1837692260742188],
+ [-1.977599024772644, 1.688241720199585],
+ [-1.659559965133667, -2.1387736797332764],
+ [0.03242531046271324, 0.6526556015014648],
+ [0.9127950072288513, 0.6099498867988586],
+ [-0.38478314876556396, 0.433487206697464],
+ [0.27454206347465515, -0.27719801664352417],
+ [0.10388526320457458, 2.2812814712524414],
+ [-0.014394169673323631, -3.177137613296509],
+ [-1.2871228456497192, -0.8961855173110962],
+ [0.5720916986465454, -0.921597957611084],
+ [1.1159656047821045, -0.7609877586364746],
+ [2.4383342266082764, -2.2983546257019043],
+ [-0.294057160615921, -0.9770799875259399],
+ [-0.9342701435089111, 1.107579231262207],
+ [-1.549338698387146, 3.090520143508911],
+ [2.6076579093933105, 2.051239013671875],
+ [-0.9259037375450134, 1.407211184501648],
+ [-0.1747353971004486, 0.540488600730896],
+ [-0.8963701725006104, 0.8271111249923706],
+ [0.6480194926261902, 1.0128909349441528],
+ [0.980783998966217, -0.06156221032142639],
+ [-0.16883476078510284, 1.0601658821105957],
+ [0.5839992761611938, 0.004697148688137531],
+ [-0.34228450059890747, -1.2423977851867676],
+ [2.500824451446533, 0.3665279746055603],
+ [-0.17641609907150269, 1.3529551029205322],
+ [0.05378641560673714, 2.817232847213745],
+ [-1.2391047477722168, 2.354328155517578],
+ [0.630434513092041, -0.668536365032196],
+ [1.7576488256454468, 0.6738647818565369],
+ [0.4435231387615204, 0.6000469326972961],
+ [-0.08794835954904556, -0.11511358618736267],
+ [1.6540337800979614, 0.33995017409324646],
+ [-0.04202975332736969, -0.5375117063522339],
+ [-0.4247745871543884, -0.7897617220878601],
+ [0.06695003807544708, 1.2000739574432373],
+ [-3.2508881092071533, 0.28734830021858215],
+ [-1.613816261291504, 0.4944162368774414],
+ [1.3598989248275757, 0.26117825508117676],
+ [2.308382511138916, 1.3462618589401245],
+ [-1.2137469053268433, -1.9254342317581177],
+ [-0.4889402985572815, 1.8136259317398071],
+ [-0.1870335340499878, -0.3480615019798279],
+ [1.0766386985778809, -1.0627082586288452],
+ [0.4651014506816864, 2.131748914718628],
+ [-0.1306295394897461, -0.7811847925186157],
+ [0.06433182954788208, -1.5397958755493164],
+ [-0.2894323468208313, -0.5789554715156555],
+ [-0.6081662178039551, 0.4845278263092041],
+ [2.697964668273926, -0.18515698611736298],
+ [0.1277363896369934, -0.7221432328224182],
+ [0.8700758218765259, 0.35042452812194824],
+ [0.22088994085788727, 0.495242178440094],
+ [-2.5843818187713623, -0.8000828623771667],
+ [0.6732649803161621, -1.4362232685089111],
+ [-1.5286413431167603, 1.0417330265045166],
+ [-1.1222513914108276, -0.6269875764846802],
+ [-0.9752035140991211, -0.8750635385513306],
+ [-2.6369473934173584, 0.6918523907661438],
+ [0.14478731155395508, -0.041986867785453796],
+ [-1.5629483461380005, 1.4369450807571411],
+ [0.38952457904815674, -2.16428804397583],
+ [-0.16885095834732056, 0.7976621985435486],
+ [-3.12416934967041, 1.256506085395813],
+ [0.6843105554580688, -0.4203019142150879],
+ [1.9345275163650513, 1.934950351715088],
+ [0.012184220366179943, -2.1080918312072754],
+ [-0.6350273489952087, 0.7358828186988831],
+ [-0.837304949760437, -0.6214472651481628],
+ [0.08211923390626907, -0.9472538232803345],
+ [2.9332995414733887, -1.4956780672073364],
+ [1.3806978464126587, -0.2916182279586792],
+ [0.06773144006729126, 0.9285762310028076],
+ [-1.1943119764328003, 1.5963770151138306],
+ [1.6395620107650757, -0.32285431027412415],
+ [-1.390851378440857, -0.08273141086101532],
+ [1.816330909729004, -1.2812227010726929],
+ [0.7921574711799622, -2.1135804653167725],
+ [0.5817914605140686, 1.2644577026367188],
+ [1.929347038269043, -0.2386285960674286],
+ [0.8877345323562622, 1.190008521080017],
+ [1.4732073545455933, 0.8935023546218872],
+ [-2.8518524169921875, -1.5478795766830444],
+ [0.2439267635345459, 0.7576767802238464],
+ [0.5246709585189819, -2.606659412384033],
+ [1.150876760482788, 1.4073830842971802],
+ [-0.2643202245235443, 2.0634236335754395],
+ [1.555483341217041, -0.0023102816194295883],
+ [2.0830578804016113, -1.7225427627563477],
+ [-0.5424830317497253, -1.070199728012085],
+ [0.9168899655342102, 0.8955540060997009],
+ [-0.8120972514152527, 2.696739912033081],
+ [-0.29908373951911926, -1.5310651063919067],
+ [1.2320337295532227, -1.556247353553772],
+ [1.8612544536590576, 0.08704725652933121],
+ [0.22133447229862213, -1.8091708421707153],
+ [-0.4403655230998993, -0.38571012020111084],
+ [-1.88539457321167, 1.192205786705017],
+ [2.239687919616699, 0.004709010478109121],
+ [1.139495611190796, 0.45733731985092163],
+ [-1.507995367050171, 0.19716016948223114],
+ [0.46986445784568787, 1.5422041416168213],
+ [-1.2573751211166382, -0.35984551906585693],
+ [-1.7415345907211304, -0.6020717024803162],
+ [1.0751984119415283, 0.19006384909152985],
+ [2.24186635017395, -0.46343153715133667],
+ [0.3610347509384155, -0.07658443599939346],
+ [-1.3111497163772583, 0.432013601064682],
+ [0.6164408326148987, 0.24538464844226837],
+ [-1.9266542196273804, -0.3256155550479889],
+ [-0.5870336890220642, -0.1879584938287735],
+ [-1.0476511716842651, 0.3677721917629242],
+ [-1.229940414428711, 1.2433830499649048],
+ [0.18550436198711395, 0.22753673791885376],
+ [-0.017921989783644676, 0.12625974416732788],
+ [1.1659504175186157, -0.5020995736122131],
+ [-0.5983408093452454, -1.40438973903656],
+ [0.7519024014472961, -0.16282692551612854],
+ [0.9920787811279297, -1.344896912574768],
+ [-0.8103678226470947, 0.3064485788345337],
+ [0.6956969499588013, 1.8208192586898804],
+ [-2.7830491065979004, -0.2299390584230423],
+ [-0.34681546688079834, 2.4890666007995605],
+ [-1.4452646970748901, -1.2216600179672241],
+ [-2.1872897148132324, 0.8926076292991638],
+ [1.706072211265564, -2.8440372943878174],
+ [1.1119003295898438, -2.4923460483551025],
+ [-2.582794666290283, 2.0973289012908936],
+ [0.04987720400094986, -0.2964983284473419],
+ [-2.063807487487793, -0.7847916483879089],
+ [-0.4068813621997833, 0.9135897755622864],
+ [-0.9814359545707703, -0.3874954879283905],
+ [-1.4227229356765747, 0.7337291240692139],
+ [0.3065044581890106, 1.3125417232513428],
+ [1.2160996198654175, -1.9643305540084839],
+ [-1.2163853645324707, 0.14608727395534515],
+ [-2.3030710220336914, -0.37558120489120483],
+ [0.9232977628707886, 2.1843791007995605],
+ [-0.1989777386188507, 1.651851773262024],
+ [-0.714374840259552, -0.39365994930267334],
+ [-0.7805715799331665, -2.099881887435913],
+ [0.9015759229660034, -1.7053706645965576],
+ [0.1033422127366066, 1.5256654024124146],
+ [-1.8773194551467896, 2.324174165725708],
+ [1.9227174520492554, 2.7441604137420654],
+ [-0.5994020104408264, 0.23984014987945557],
+ [1.3496100902557373, -0.9126054644584656],
+ [-0.8765304088592529, -3.1877026557922363],
+ [-1.2040035724639893, -1.5169521570205688],
+ [1.4261796474456787, 2.150200128555298],
+ [1.463774561882019, 1.6656692028045654],
+ [0.20364105701446533, -0.4988172650337219],
+ [0.5195154547691345, -0.24067887663841248],
+ [-1.1116786003112793, -1.1599653959274292],
+ [-0.8490808606147766, -0.1681060940027237],
+ [0.3189965784549713, -0.9641751646995544],
+ [-0.5664751529693604, -0.5951744318008423],
+ [-1.6347930431365967, -0.9137664437294006],
+ [0.44048091769218445, -0.47259435057640076],
+ [-2.147747039794922, 0.47442489862442017],
+ [1.834734320640564, 1.4462147951126099],
+ [1.1777573823928833, 1.0659226179122925],
+ [-0.9568989872932434, 0.09495053440332413],
+ [-1.838529348373413, 0.2950586676597595],
+ [-0.4800611734390259, 0.014894310384988785],
+ [-0.5235516428947449, -1.7687653303146362],
+ [2.0735011100769043, -0.8825281262397766],
+ [2.637502431869507, 0.8455678224563599],
+ [2.606602907180786, -0.7848446369171143],
+ [-1.1886937618255615, 0.9330510497093201],
+ [0.38082656264305115, 0.13328030705451965],
+ [0.6847941875457764, 0.7384101152420044],
+ [1.2638574838638306, -0.007309418171644211],
+ [0.18292222917079926, -1.22371244430542],
+ [0.8143821954727173, 1.4976691007614136],
+ [0.6571850776672363, 0.48368802666664124],
+ [-0.6991601586341858, 2.150190830230713],
+ [0.8101756572723389, 0.10206498205661774],
+ [-0.08768226951360703, -1.084917664527893],
+ [-0.7208092212677002, 0.03657956421375275],
+ [0.3211449086666107, 1.803687334060669],
+ [-0.7835946083068848, 1.6869111061096191],
+ ]
+ )
+ if (p, n) == (2, 64):
+ return torch.tensor(
+ [
+ [-2.7216711044311523, 0.14431366324424744],
+ [-0.766914427280426, 1.7193410396575928],
+ [-2.2575762271881104, 1.2476624250411987],
+ [1.233758807182312, -2.3560616970062256],
+ [0.8701965808868408, -0.2649352252483368],
+ [1.4506438970565796, 2.1776366233825684],
+ [-0.06305818259716034, 1.9049758911132812],
+ [2.536226511001587, 0.563927412033081],
+ [0.4599496126174927, -1.8745561838150024],
+ [-1.900517225265503, -0.30703988671302795],
+ [0.09386251866817474, 0.8755807280540466],
+ [1.946500539779663, -0.6743080615997314],
+ [2.1338934898376465, 1.4581491947174072],
+ [0.9429940581321716, -0.8038390278816223],
+ [2.0697755813598633, -1.614896535873413],
+ [0.772676408290863, 0.22017823159694672],
+ [1.0689979791641235, -1.525044322013855],
+ [0.6813604831695557, 1.1345642805099487],
+ [0.4706456661224365, 2.606626272201538],
+ [-1.294018030166626, -0.4372096061706543],
+ [-0.09134224057197571, 0.4610418677330017],
+ [-0.7907772064208984, -0.48412787914276123],
+ [0.060459110885858536, -0.9172890186309814],
+ [-0.5855047702789307, 2.56172513961792],
+ [0.11484206467866898, -2.659848213195801],
+ [-1.5893300771713257, 2.188580274581909],
+ [1.6750942468643188, 0.7089915871620178],
+ [-0.445697546005249, 0.7452405095100403],
+ [-1.8539940118789673, -1.8377939462661743],
+ [-1.5791912078857422, -1.017285943031311],
+ [-1.030419945716858, -1.5746369361877441],
+ [-1.9511750936508179, 0.43696075677871704],
+ [-0.3446580767631531, -1.8953213691711426],
+ [-1.4219647645950317, 0.7676230669021606],
+ [-0.9191089272499084, 0.5021472573280334],
+ [0.20464491844177246, 1.3684605360031128],
+ [0.5402919054031372, 0.6699410676956177],
+ [1.8903915882110596, 0.03638288006186485],
+ [0.4723062515258789, -0.6216739416122437],
+ [-0.41345009207725525, -0.22752176225185394],
+ [2.7119064331054688, -0.5111885070800781],
+ [1.065286636352539, 0.6950305700302124],
+ [0.40629103779792786, -0.14339995384216309],
+ [1.2815024852752686, 0.17108257114887238],
+ [0.01785222627222538, -0.43778058886528015],
+ [0.054590027779340744, -1.4225547313690186],
+ [0.3076786696910858, 0.30697619915008545],
+ [-0.9498570561408997, -0.9576997756958008],
+ [-2.4640724658966064, -0.9660449028015137],
+ [1.3714425563812256, -0.39760473370552063],
+ [-0.4857747256755829, 0.2386789172887802],
+ [1.2797833681106567, 1.3097363710403442],
+ [0.5508887767791748, -1.1777795553207397],
+ [-1.384316325187683, 0.1465839296579361],
+ [-0.46556955575942993, -1.2442727088928223],
+ [-0.3915477693080902, -0.7319604158401489],
+ [-1.4005504846572876, 1.3890998363494873],
+ [-0.8647305965423584, 1.0617644786834717],
+ [-0.8901953101158142, -0.01650036871433258],
+ [-0.9893633723258972, -2.4662880897521973],
+ [1.445534110069275, -1.049334168434143],
+ [-0.041650623083114624, 0.012734669260680676],
+ [-0.3302375078201294, 1.26217782497406],
+ [0.6934980154037476, 1.7714335918426514],
+ ]
+ )
+ elif (p, n) == (2, 16):
+ return torch.tensor(
+ [
+ [-0.8996632695198059, -1.6360418796539307],
+ [-0.961183488368988, 1.5999565124511719],
+ [-1.882026195526123, 0.678778350353241],
+ [0.36300793290138245, -1.9667866230010986],
+ [-0.6814072728157043, -0.576818585395813],
+ [0.7270012497901917, 0.6186859607696533],
+ [0.3359416127204895, 1.8371193408966064],
+ [1.859930396080017, 0.036668598651885986],
+ [0.17208248376846313, -0.9401724338531494],
+ [-1.7599700689315796, -0.6244229674339294],
+ [-0.8993809223175049, 0.32267823815345764],
+ [0.839488685131073, -0.3017036020755768],
+ [1.5314953327178955, 1.2942044734954834],
+ [-0.0011779458727687597, 0.00022069070837460458],
+ [1.4274526834487915, -1.207889199256897],
+ [-0.16123905777931213, 0.8787511587142944],
+ ]
+ )
+ elif (p, n) == (1, 16):
+ return torch.tensor(
+ [
+ [-2.7325894832611084],
+ [-2.069017171859741],
+ [-1.6180464029312134],
+ [-1.2562311887741089],
+ [-0.9423404335975647],
+ [-0.6567591428756714],
+ [-0.38804829120635986],
+ [-0.12839503586292267],
+ [0.12839503586292267],
+ [0.38804829120635986],
+ [0.6567591428756714],
+ [0.9423404335975647],
+ [1.2562311887741089],
+ [1.6180464029312134],
+ [2.069017171859741],
+ [2.7325894832611084],
+ ]
+ )
+ elif (p, n) == (1, 8):
+ return torch.tensor(
+ [
+ [-2.1519455909729004],
+ [-1.3439092636108398],
+ [-0.7560052871704102],
+ [-0.2450941801071167],
+ [0.2450941801071167],
+ [0.7560052871704102],
+ [1.3439092636108398],
+ [2.1519455909729004],
+ ]
+ )
+ elif (p, n) == (1, 4):
+ return torch.tensor([[-1.5104175806045532], [-0.4527800381183624], [0.4527800381183624], [1.5104175806045532]])
+ else:
+ raise NotImplementedError(f"Unsupported p={p}, n={n}")
+
+
+def quantize_with_higgs(weight, bits: int = 4, p: int = 2, group_size: int = 256, hadamard_size: int = 1024):
+ assert len(weight.shape) == 2, "Only 2D weights are supported for now"
+
+ grid = get_higgs_grid(p, 2 ** (p * bits)).to(weight.device)
+ grid_norm_2 = torch.linalg.norm(grid, axis=-1) ** 2
+
+ device = weight.device
+ dtype = weight.dtype
+ weight = weight.clone().float()
+ # Pad to Hadamard transform size
+ weight = pad_to_block(weight, [1], hadamard_size)
+
+ # Scale and Hadamard transform
+ mult = weight.shape[1] // hadamard_size
+ weight = weight.reshape(-1, mult, hadamard_size)
+ scales = torch.linalg.norm(weight, axis=-1)
+ weight = hadamard_transform(weight, 1) / scales[:, :, None]
+
+ # Pad to edenn_d and project
+ weight = pad_to_block(weight, [2], p).reshape(weight.shape[0], mult, -1, p)
+
+ # Quantize
+ codes = torch.empty(weight.shape[:-1], device=device, dtype=torch.uint8)
+ for i in range(0, weight.shape[0], 16):
+ codes[i : i + 16] = torch.argmax(2 * weight[i : i + 16] @ grid.T - grid_norm_2, dim=-1).to(torch.uint8)
+ del weight
+
+ codes = codes.reshape(codes.shape[0], -1)
+ scales = scales / sqrt(hadamard_size)
+
+ weight, scales, tables, tables2, tune_metadata = prepare_data_transposed(
+ codes,
+ torch.repeat_interleave(scales.to(dtype), hadamard_size // group_size, dim=1),
+ grid.to(dtype),
+ num_bits=bits,
+ group_size=group_size,
+ vector_size=p,
+ dtype=dtype,
+ device=device,
+ check_correctness=False,
+ )
+
+ return {
+ "weight": weight,
+ "scales": scales,
+ "tables": tables,
+ "tables2": tables2.view(dtype=torch.float16),
+ "tune_metadata": tune_metadata,
+ }
+
+
+class HiggsLinear(torch.nn.Module):
+ def __init__(
+ self,
+ in_features: int,
+ out_features: int,
+ num_bits: int,
+ bias=True,
+ dtype: torch.dtype = None,
+ device: torch.device = None,
+ group_size: int = 256,
+ hadamard_size: int = 1024,
+ ):
+ super().__init__()
+ self.in_features = in_features
+ self.out_features = out_features
+ self.num_bits = num_bits
+ self.group_size = group_size
+ self.hadamard_size = hadamard_size
+
+ assert in_features % group_size == 0
+ assert num_bits in [2, 3, 4]
+
+ self.weight = nn.Parameter(
+ torch.empty((out_features * num_bits // 16, in_features), dtype=torch.int16, device=device),
+ requires_grad=False,
+ )
+ self.scales = nn.Parameter(
+ torch.empty((out_features, in_features // group_size), dtype=dtype, device=device), requires_grad=False
+ )
+ self.tables = nn.Parameter(torch.empty((2**num_bits,), dtype=dtype, device=device), requires_grad=False)
+ self.tables2 = nn.Parameter(
+ torch.empty((2**num_bits, 2**num_bits, 2), dtype=dtype, device=device), requires_grad=False
+ )
+
+ if bias:
+ self.bias = nn.Parameter(torch.empty(out_features, device=device, dtype=dtype), requires_grad=False)
+ else:
+ self.register_parameter("bias", None)
+
+ self.workspace = None # must be set externally to be reused among layers
+ self.tune_metadata: TuneMetaData = None # must be set externally because architecture dependent
+
+ def forward(self, x):
+ x = pad_to_block(x, [-1], self.hadamard_size)
+
+ if self.workspace is None:
+ raise Exception("Workspace must be set before calling forward")
+
+ return qgemm_v2(
+ x,
+ self.weight,
+ self.scales,
+ self.tables,
+ self.tables2.view(dtype=torch.float32),
+ self.workspace,
+ self.tune_metadata,
+ hadamard_size=self.hadamard_size,
+ )
+
+
+def replace_with_higgs_linear(
+ model,
+ quantization_config=None,
+ current_key_name=None,
+ has_been_replaced=False,
+):
+ """
+ Public method that recursively replaces the Linear layers of the given model with HIGGS quantized layers.
+ `accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the
+ conversion has been successfull or not.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to convert, can be any `torch.nn.Module` instance.
+ quantization_config (`HiggsConfig`):
+ The quantization config object that contains the quantization parameters.
+ current_key_name (`list`, *optional*):
+ A list that contains the current key name. This is used for recursion and should not be passed by the user.
+ has_been_replaced (`bool`, *optional*):
+ A boolean that indicates if the conversion has been successful or not. This is used for recursion and
+ should not be passed by the user.
+ """
+
+ from accelerate import init_empty_weights
+
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if isinstance(module, nn.Linear):
+ # Check if the current key is not in the `quantization_config.modules_to_not_convert`
+ current_key_name_str = ".".join(current_key_name)
+ if not any(current_key_name_str.endswith(key) for key in quantization_config.modules_to_not_convert):
+ with init_empty_weights():
+ in_features = module.in_features
+ out_features = module.out_features
+
+ model._modules[name] = HiggsLinear(
+ in_features,
+ out_features,
+ bias=module.bias is not None,
+ num_bits=quantization_config.bits,
+ hadamard_size=quantization_config.hadamard_size,
+ group_size=quantization_config.group_size,
+ )
+ has_been_replaced = True
+
+ # Store the module class in case we need to transpose the weight later
+ model._modules[name].source_cls = type(module)
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = replace_with_higgs_linear(
+ module,
+ quantization_config=quantization_config,
+ current_key_name=current_key_name,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
+
+
+def dequantize_higgs(model, current_key_name=None):
+ """
+ Dequantizes the HiggsLinear layers in the given model by replacing them with standard torch.nn.Linear layers.
+ Args:
+ model (torch.nn.Module): The model containing HiggsLinear layers to be dequantized.
+ current_key_name (list, optional): A list to keep track of the current module names during recursion. Defaults to None.
+ Returns:
+ torch.nn.Module: The model with HiggsLinear layers replaced by torch.nn.Linear layers.
+ """
+
+ with torch.no_grad():
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if isinstance(module, HiggsLinear):
+ in_features = module.in_features
+ out_features = module.out_features
+
+ model._modules[name] = torch.nn.Linear(
+ in_features,
+ out_features,
+ bias=module.bias is not None,
+ device=module.scales.device,
+ dtype=module.scales.dtype,
+ )
+
+ model._modules[name].weight.data = module(
+ torch.eye(in_features, device=module.scales.device, dtype=module.scales.dtype)
+ ).T.contiguous()
+
+ if len(list(module.children())) > 0:
+ _ = dequantize_higgs(
+ module,
+ current_key_name=current_key_name,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/hqq.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/hqq.py
new file mode 100644
index 0000000000000000000000000000000000000000..162b365668a0474fc4b109627019546e21fb3b85
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/hqq.py
@@ -0,0 +1,129 @@
+# 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.
+"HQQ (Half-Quadratic Quantization) integration file"
+
+from ..utils import is_hqq_available, is_torch_available, logging
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+# Name all modules inside the model
+def autoname_modules(model):
+ for name, module in model.named_modules():
+ module.name = name
+
+
+# Get the linear_tag from a modul name. For example: model.layers.31.self_attn.k_proj -> self_attn.k_proj
+def name_to_linear_tag(name):
+ return ".".join([n for n in name.split(".") if ((n not in ["model", "layers"]) and (not n.isnumeric()))])
+
+
+# Get all linear tags available
+def get_linear_tags(model):
+ if is_hqq_available():
+ from hqq.core.quantize import HQQLinear
+
+ linear_tags = set()
+ for name, module in model.named_modules():
+ if isinstance(module, (torch.nn.Linear, HQQLinear)):
+ linear_tags.add(name_to_linear_tag(name))
+ return list(linear_tags)
+
+
+def _prepare_for_hqq_linear(model, patch_params, has_been_replaced, current_key_name=None):
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if isinstance(module, torch.nn.Linear):
+ # Get linear tag
+ linear_tag = name_to_linear_tag(module.name)
+
+ # We put the module quant_config into the nn.Linear layer so we can access it later in quantizer_hqq.create_quantized_param()
+ if linear_tag in patch_params:
+ if patch_params[linear_tag] is not None:
+ model._modules[name].quant_config = patch_params[linear_tag]
+ # Store the module class in case we need to transpose the weight later
+ model._modules[name].source_cls = type(module)
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+
+ has_been_replaced = True
+
+ # Add these fake parameters to avoid loading fail
+ for att in ["W_q", "meta"]:
+ setattr(module, att, None)
+
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = _prepare_for_hqq_linear(
+ module,
+ patch_params=patch_params,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+
+ return model, has_been_replaced
+
+
+def prepare_for_hqq_linear(model, quantization_config=None, modules_to_not_convert=None, has_been_replaced=False):
+ """
+ Prepares nn.Linear layers for HQQ quantization.
+ Since each layer type can have separate quantization parameters, we need to do the following:
+ 1- tag each module with its neme via autoname_modules()
+ 2- Extract linear_tags (e.g. ['self_attn.q_proj', ...])
+ 3- Map quantization parameters as a dictionary linear_tag -> quant_params as HQQLinear exepects it, this is referred to as patch_params
+ """
+
+ modules_to_not_convert = [] if modules_to_not_convert is None else modules_to_not_convert
+
+ # Add name to module
+ autoname_modules(model)
+
+ # Get linear tags. This allows us to use different quant params to different layer types
+ linear_tags = get_linear_tags(model)
+
+ # Convert quantization_config to layer-wise config
+ skip_modules = quantization_config.skip_modules
+ quant_config = quantization_config.quant_config
+ linear_tags = list(set(linear_tags) - set(skip_modules) - set(modules_to_not_convert))
+
+ if any(key in linear_tags for key in quant_config.keys()):
+ # If the user doesn't specify a key from get_linear_tags, the layer is not quantized via (key, None)
+ patch_params = {key: None for key in linear_tags}
+ patch_params.update(quant_config)
+ else:
+ # Same quant_config for all layers
+ patch_params = {k: quant_config for k in linear_tags}
+
+ model, has_been_replaced = _prepare_for_hqq_linear(
+ model, patch_params=patch_params, has_been_replaced=has_been_replaced
+ )
+
+ # We store quantization config as linear_tag -> hqq quant config
+ model.config.quantization_config = {
+ "quant_config": quant_config,
+ "quant_method": quantization_config.quant_method,
+ "skip_modules": skip_modules,
+ }
+
+ if not has_been_replaced:
+ logger.warning("No linear modules were found in your model for quantization.")
+
+ return model
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/integration_utils.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/integration_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..95668fefd7b201513852b2e6077dfae44da5cb40
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/integration_utils.py
@@ -0,0 +1,2348 @@
+# 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.
+"""
+Integrations with other Python libraries.
+"""
+
+import functools
+import importlib.metadata
+import importlib.util
+import json
+import numbers
+import os
+import pickle
+import shutil
+import sys
+import tempfile
+from dataclasses import asdict, fields
+from enum import Enum
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Dict, Literal, Optional, Union
+
+import numpy as np
+import packaging.version
+
+from .. import PreTrainedModel, TFPreTrainedModel
+from .. import __version__ as version
+from ..utils import (
+ PushToHubMixin,
+ flatten_dict,
+ is_datasets_available,
+ is_pandas_available,
+ is_tf_available,
+ is_torch_available,
+ logging,
+)
+
+
+logger = logging.get_logger(__name__)
+
+if is_torch_available():
+ import torch
+
+# comet_ml requires to be imported before any ML frameworks
+_MIN_COMET_VERSION = "3.43.2"
+try:
+ _comet_version = importlib.metadata.version("comet_ml")
+ _is_comet_installed = True
+
+ _is_comet_recent_enough = packaging.version.parse(_comet_version) >= packaging.version.parse(_MIN_COMET_VERSION)
+
+ # Check if the Comet API Key is set
+ import comet_ml
+
+ if comet_ml.config.get_config("comet.api_key") is not None:
+ _is_comet_configured = True
+ else:
+ _is_comet_configured = False
+except (importlib.metadata.PackageNotFoundError, ImportError, ValueError, TypeError, AttributeError, KeyError):
+ _comet_version = None
+ _is_comet_installed = False
+ _is_comet_recent_enough = False
+ _is_comet_configured = False
+
+_has_neptune = (
+ importlib.util.find_spec("neptune") is not None or importlib.util.find_spec("neptune-client") is not None
+)
+if TYPE_CHECKING and _has_neptune:
+ try:
+ _neptune_version = importlib.metadata.version("neptune")
+ logger.info(f"Neptune version {_neptune_version} available.")
+ except importlib.metadata.PackageNotFoundError:
+ try:
+ _neptune_version = importlib.metadata.version("neptune-client")
+ logger.info(f"Neptune-client version {_neptune_version} available.")
+ except importlib.metadata.PackageNotFoundError:
+ _has_neptune = False
+
+from .. import modelcard # noqa: E402
+from ..trainer_callback import ProgressCallback, TrainerCallback # noqa: E402
+from ..trainer_utils import PREFIX_CHECKPOINT_DIR, BestRun, IntervalStrategy # noqa: E402
+from ..training_args import ParallelMode # noqa: E402
+from ..utils import ENV_VARS_TRUE_VALUES, is_torch_xla_available # noqa: E402
+
+
+# Integration functions:
+def is_wandb_available():
+ # any value of WANDB_DISABLED disables wandb
+ if os.getenv("WANDB_DISABLED", "").upper() in ENV_VARS_TRUE_VALUES:
+ logger.warning(
+ "Using the `WANDB_DISABLED` environment variable is deprecated and will be removed in v5. Use the "
+ "--report_to flag to control the integrations used for logging result (for instance --report_to none)."
+ )
+ return False
+ return importlib.util.find_spec("wandb") is not None
+
+
+def is_clearml_available():
+ return importlib.util.find_spec("clearml") is not None
+
+
+def is_comet_available():
+ if os.getenv("COMET_MODE", "").upper() == "DISABLED":
+ logger.warning(
+ "Using the `COMET_MODE=DISABLED` environment variable is deprecated and will be removed in v5. Use the "
+ "--report_to flag to control the integrations used for logging result (for instance --report_to none)."
+ )
+ return False
+
+ if _is_comet_installed is False:
+ return False
+
+ if _is_comet_recent_enough is False:
+ logger.warning(
+ "comet_ml version %s is installed, but version %s or higher is required. "
+ "Please update comet_ml to the latest version to enable Comet logging with pip install 'comet-ml>=%s'.",
+ _comet_version,
+ _MIN_COMET_VERSION,
+ _MIN_COMET_VERSION,
+ )
+ return False
+
+ if _is_comet_configured is False:
+ logger.warning(
+ "comet_ml is installed but the Comet API Key is not configured. "
+ "Please set the `COMET_API_KEY` environment variable to enable Comet logging. "
+ "Check out the documentation for other ways of configuring it: "
+ "https://www.comet.com/docs/v2/guides/experiment-management/configure-sdk/#set-the-api-key"
+ )
+ return False
+
+ return True
+
+
+def is_tensorboard_available():
+ return importlib.util.find_spec("tensorboard") is not None or importlib.util.find_spec("tensorboardX") is not None
+
+
+def is_optuna_available():
+ return importlib.util.find_spec("optuna") is not None
+
+
+def is_ray_available():
+ return importlib.util.find_spec("ray") is not None
+
+
+def is_ray_tune_available():
+ if not is_ray_available():
+ return False
+ return importlib.util.find_spec("ray.tune") is not None
+
+
+def is_sigopt_available():
+ return importlib.util.find_spec("sigopt") is not None
+
+
+def is_azureml_available():
+ if importlib.util.find_spec("azureml") is None:
+ return False
+ if importlib.util.find_spec("azureml.core") is None:
+ return False
+ return importlib.util.find_spec("azureml.core.run") is not None
+
+
+def is_mlflow_available():
+ if os.getenv("DISABLE_MLFLOW_INTEGRATION", "FALSE").upper() == "TRUE":
+ return False
+ return importlib.util.find_spec("mlflow") is not None
+
+
+def is_dagshub_available():
+ return None not in [importlib.util.find_spec("dagshub"), importlib.util.find_spec("mlflow")]
+
+
+def is_neptune_available():
+ return _has_neptune
+
+
+def is_codecarbon_available():
+ return importlib.util.find_spec("codecarbon") is not None
+
+
+def is_flytekit_available():
+ return importlib.util.find_spec("flytekit") is not None
+
+
+def is_flyte_deck_standard_available():
+ if not is_flytekit_available():
+ return False
+ return importlib.util.find_spec("flytekitplugins.deck") is not None
+
+
+def is_dvclive_available():
+ return importlib.util.find_spec("dvclive") is not None
+
+
+def is_swanlab_available():
+ return importlib.util.find_spec("swanlab") is not None
+
+
+def hp_params(trial):
+ if is_optuna_available():
+ import optuna
+
+ if isinstance(trial, optuna.trial.BaseTrial):
+ return trial.params
+ if is_ray_tune_available():
+ if isinstance(trial, dict):
+ return trial
+
+ if is_sigopt_available():
+ if isinstance(trial, dict):
+ return trial
+
+ if is_wandb_available():
+ if isinstance(trial, dict):
+ return trial
+
+ raise RuntimeError(f"Unknown type for trial {trial.__class__}")
+
+
+def run_hp_search_optuna(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
+ import optuna
+ from accelerate.utils.memory import release_memory
+
+ if trainer.args.process_index == 0:
+
+ def _objective(trial: optuna.Trial, checkpoint_dir=None):
+ checkpoint = None
+ if checkpoint_dir:
+ for subdir in os.listdir(checkpoint_dir):
+ if subdir.startswith(PREFIX_CHECKPOINT_DIR):
+ checkpoint = os.path.join(checkpoint_dir, subdir)
+ trainer.objective = None
+ if trainer.args.world_size > 1:
+ if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED:
+ raise RuntimeError("only support DDP optuna HPO for ParallelMode.DISTRIBUTED currently.")
+ trainer.hp_space(trial)
+ fixed_trial = optuna.trial.FixedTrial(trial.params, trial.number)
+ trial_main_rank_list = [fixed_trial]
+ torch.distributed.broadcast_object_list(trial_main_rank_list, src=0)
+ trainer.train(resume_from_checkpoint=checkpoint, trial=trial)
+ else:
+ trainer.train(resume_from_checkpoint=checkpoint, trial=trial)
+ # If there hasn't been any evaluation during the training loop.
+ if getattr(trainer, "objective", None) is None:
+ metrics = trainer.evaluate()
+ trainer.objective = trainer.compute_objective(metrics)
+
+ # Free GPU memory
+ trainer.model_wrapped, trainer.model = release_memory(trainer.model_wrapped, trainer.model)
+ trainer.accelerator.clear()
+
+ return trainer.objective
+
+ timeout = kwargs.pop("timeout", None)
+ n_jobs = kwargs.pop("n_jobs", 1)
+ gc_after_trial = kwargs.pop("gc_after_trial", False)
+ directions = direction if isinstance(direction, list) else None
+ direction = None if directions is not None else direction
+ study = optuna.create_study(direction=direction, directions=directions, **kwargs)
+ study.optimize(_objective, n_trials=n_trials, timeout=timeout, n_jobs=n_jobs, gc_after_trial=gc_after_trial)
+ if not study._is_multi_objective():
+ best_trial = study.best_trial
+ return BestRun(str(best_trial.number), best_trial.value, best_trial.params)
+ else:
+ best_trials = study.best_trials
+ return [BestRun(str(best.number), best.values, best.params) for best in best_trials]
+ else:
+ for i in range(n_trials):
+ trainer.objective = None
+ trial_main_rank_list = [None]
+ if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED:
+ raise RuntimeError("only support DDP optuna HPO for ParallelMode.DISTRIBUTED currently.")
+ torch.distributed.broadcast_object_list(trial_main_rank_list, src=0)
+ trainer.train(resume_from_checkpoint=None, trial=trial_main_rank_list[0])
+ # If there hasn't been any evaluation during the training loop.
+ if getattr(trainer, "objective", None) is None:
+ metrics = trainer.evaluate()
+ trainer.objective = trainer.compute_objective(metrics)
+ return None
+
+
+def run_hp_search_ray(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
+ import ray
+ import ray.train
+
+ def _objective(trial: dict, local_trainer):
+ try:
+ from transformers.utils.notebook import NotebookProgressCallback
+
+ if local_trainer.pop_callback(NotebookProgressCallback):
+ local_trainer.add_callback(ProgressCallback)
+ except ModuleNotFoundError:
+ pass
+
+ local_trainer.objective = None
+
+ checkpoint = ray.train.get_checkpoint()
+ if checkpoint:
+ # Upon trial resume, the local_trainer's objective gets reset to None.
+ # If `local_trainer.train` is a noop (training has already reached
+ # the target number of epochs/steps), then this would
+ # trigger an unnecessary extra checkpoint at the end of training.
+ # -> Set the objective to a dummy value upon resume as a workaround.
+ local_trainer.objective = "objective"
+
+ with checkpoint.as_directory() as checkpoint_dir:
+ checkpoint_path = next(Path(checkpoint_dir).glob(f"{PREFIX_CHECKPOINT_DIR}*")).as_posix()
+ local_trainer.train(resume_from_checkpoint=checkpoint_path, trial=trial)
+ else:
+ local_trainer.train(trial=trial)
+
+ # If there hasn't been any evaluation during the training loop.
+ if getattr(local_trainer, "objective", None) is None:
+ metrics = local_trainer.evaluate()
+ local_trainer.objective = local_trainer.compute_objective(metrics)
+
+ metrics.update({"objective": local_trainer.objective, "done": True})
+
+ with tempfile.TemporaryDirectory() as temp_checkpoint_dir:
+ local_trainer._tune_save_checkpoint(checkpoint_dir=temp_checkpoint_dir)
+ checkpoint = ray.train.Checkpoint.from_directory(temp_checkpoint_dir)
+ ray.train.report(metrics, checkpoint=checkpoint)
+
+ if not trainer._memory_tracker.skip_memory_metrics:
+ from ..trainer_utils import TrainerMemoryTracker
+
+ logger.warning(
+ "Memory tracking for your Trainer is currently "
+ "enabled. Automatically disabling the memory tracker "
+ "since the memory tracker is not serializable."
+ )
+ trainer._memory_tracker = TrainerMemoryTracker(skip_memory_metrics=True)
+
+ # The model and TensorBoard writer do not pickle so we have to remove them (if they exists)
+ # while doing the ray hp search.
+ _tb_writer = trainer.pop_callback(TensorBoardCallback)
+ trainer.model = None
+
+ # Setup default `resources_per_trial`.
+ if "resources_per_trial" not in kwargs:
+ # Default to 1 CPU and 1 GPU (if applicable) per trial.
+ kwargs["resources_per_trial"] = {"cpu": 1}
+ if trainer.args.n_gpu > 0:
+ kwargs["resources_per_trial"]["gpu"] = 1
+ resource_msg = "1 CPU" + (" and 1 GPU" if trainer.args.n_gpu > 0 else "")
+ logger.info(
+ "No `resources_per_trial` arg was passed into "
+ "`hyperparameter_search`. Setting it to a default value "
+ f"of {resource_msg} for each trial."
+ )
+ # Make sure each trainer only uses GPUs that were allocated per trial.
+ gpus_per_trial = kwargs["resources_per_trial"].get("gpu", 0)
+ trainer.args._n_gpu = gpus_per_trial
+
+ # Setup default `progress_reporter`.
+ if "progress_reporter" not in kwargs:
+ from ray.tune import CLIReporter
+
+ kwargs["progress_reporter"] = CLIReporter(metric_columns=["objective"])
+
+ if "scheduler" in kwargs:
+ from ray.tune.schedulers import ASHAScheduler, HyperBandForBOHB, MedianStoppingRule, PopulationBasedTraining
+
+ # Check for `do_eval` and `eval_during_training` for schedulers that require intermediate reporting.
+ if isinstance(
+ kwargs["scheduler"], (ASHAScheduler, MedianStoppingRule, HyperBandForBOHB, PopulationBasedTraining)
+ ) and (not trainer.args.do_eval or trainer.args.eval_strategy == IntervalStrategy.NO):
+ raise RuntimeError(
+ "You are using {cls} as a scheduler but you haven't enabled evaluation during training. "
+ "This means your trials will not report intermediate results to Ray Tune, and "
+ "can thus not be stopped early or used to exploit other trials parameters. "
+ "If this is what you want, do not use {cls}. If you would like to use {cls}, "
+ "make sure you pass `do_eval=True` and `eval_strategy='steps'` in the "
+ "Trainer `args`.".format(cls=type(kwargs["scheduler"]).__name__)
+ )
+
+ trainable = ray.tune.with_parameters(_objective, local_trainer=trainer)
+
+ @functools.wraps(trainable)
+ def dynamic_modules_import_trainable(*args, **kwargs):
+ """
+ Wrapper around `tune.with_parameters` to ensure datasets_modules are loaded on each Actor.
+
+ Without this, an ImportError will be thrown. See https://github.com/huggingface/transformers/issues/11565.
+
+ Assumes that `_objective`, defined above, is a function.
+ """
+ if is_datasets_available():
+ import datasets.load
+
+ dynamic_modules_path = os.path.join(datasets.load.init_dynamic_modules(), "__init__.py")
+ # load dynamic_modules from path
+ spec = importlib.util.spec_from_file_location("datasets_modules", dynamic_modules_path)
+ datasets_modules = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = datasets_modules
+ spec.loader.exec_module(datasets_modules)
+ return trainable(*args, **kwargs)
+
+ # special attr set by tune.with_parameters
+ if hasattr(trainable, "__mixins__"):
+ dynamic_modules_import_trainable.__mixins__ = trainable.__mixins__
+
+ analysis = ray.tune.run(
+ dynamic_modules_import_trainable,
+ config=trainer.hp_space(None),
+ num_samples=n_trials,
+ **kwargs,
+ )
+ best_trial = analysis.get_best_trial(metric="objective", mode=direction[:3], scope=trainer.args.ray_scope)
+ best_run = BestRun(best_trial.trial_id, best_trial.last_result["objective"], best_trial.config, analysis)
+ if _tb_writer is not None:
+ trainer.add_callback(_tb_writer)
+ return best_run
+
+
+def run_hp_search_sigopt(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
+ import sigopt
+
+ if trainer.args.process_index == 0:
+ if importlib.metadata.version("sigopt") >= "8.0.0":
+ sigopt.set_project("huggingface")
+
+ experiment = sigopt.create_experiment(
+ name="huggingface-tune",
+ type="offline",
+ parameters=trainer.hp_space(None),
+ metrics=[{"name": "objective", "objective": direction, "strategy": "optimize"}],
+ parallel_bandwidth=1,
+ budget=n_trials,
+ )
+
+ logger.info(f"created experiment: https://app.sigopt.com/experiment/{experiment.id}")
+
+ for run in experiment.loop():
+ with run:
+ trainer.objective = None
+ if trainer.args.world_size > 1:
+ if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED:
+ raise RuntimeError("only support DDP Sigopt HPO for ParallelMode.DISTRIBUTED currently.")
+ trainer._hp_search_setup(run.run)
+ torch.distributed.broadcast_object_list(pickle.dumps(trainer.args), src=0)
+ trainer.train(resume_from_checkpoint=None)
+ else:
+ trainer.train(resume_from_checkpoint=None, trial=run.run)
+ # If there hasn't been any evaluation during the training loop.
+ if getattr(trainer, "objective", None) is None:
+ metrics = trainer.evaluate()
+ trainer.objective = trainer.compute_objective(metrics)
+ run.log_metric("objective", trainer.objective)
+
+ best = list(experiment.get_best_runs())[0]
+ best_run = BestRun(best.id, best.values["objective"].value, best.assignments)
+ else:
+ from sigopt import Connection
+
+ conn = Connection()
+ proxies = kwargs.pop("proxies", None)
+ if proxies is not None:
+ conn.set_proxies(proxies)
+
+ experiment = conn.experiments().create(
+ name="huggingface-tune",
+ parameters=trainer.hp_space(None),
+ metrics=[{"name": "objective", "objective": direction, "strategy": "optimize"}],
+ parallel_bandwidth=1,
+ observation_budget=n_trials,
+ project="huggingface",
+ )
+ logger.info(f"created experiment: https://app.sigopt.com/experiment/{experiment.id}")
+
+ while experiment.progress.observation_count < experiment.observation_budget:
+ suggestion = conn.experiments(experiment.id).suggestions().create()
+ trainer.objective = None
+ if trainer.args.world_size > 1:
+ if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED:
+ raise RuntimeError("only support DDP Sigopt HPO for ParallelMode.DISTRIBUTED currently.")
+ trainer._hp_search_setup(suggestion)
+ torch.distributed.broadcast_object_list(pickle.dumps(trainer.args), src=0)
+ trainer.train(resume_from_checkpoint=None)
+ else:
+ trainer.train(resume_from_checkpoint=None, trial=suggestion)
+ # If there hasn't been any evaluation during the training loop.
+ if getattr(trainer, "objective", None) is None:
+ metrics = trainer.evaluate()
+ trainer.objective = trainer.compute_objective(metrics)
+
+ values = [{"name": "objective", "value": trainer.objective}]
+ obs = conn.experiments(experiment.id).observations().create(suggestion=suggestion.id, values=values)
+ logger.info(f"[suggestion_id, observation_id]: [{suggestion.id}, {obs.id}]")
+ experiment = conn.experiments(experiment.id).fetch()
+
+ best = list(conn.experiments(experiment.id).best_assignments().fetch().iterate_pages())[0]
+ best_run = BestRun(best.id, best.value, best.assignments)
+ return best_run
+ else:
+ for i in range(n_trials):
+ trainer.objective = None
+ args_main_rank = list(pickle.dumps(trainer.args))
+ if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED:
+ raise RuntimeError("only support DDP Sigopt HPO for ParallelMode.DISTRIBUTED currently.")
+ torch.distributed.broadcast_object_list(args_main_rank, src=0)
+ args = pickle.loads(bytes(args_main_rank))
+ for key, value in asdict(args).items():
+ if key != "local_rank":
+ setattr(trainer.args, key, value)
+ trainer.train(resume_from_checkpoint=None)
+ # If there hasn't been any evaluation during the training loop.
+ if getattr(trainer, "objective", None) is None:
+ metrics = trainer.evaluate()
+ trainer.objective = trainer.compute_objective(metrics)
+ return None
+
+
+def run_hp_search_wandb(trainer, n_trials: int, direction: str, **kwargs) -> BestRun:
+ from ..integrations import is_wandb_available
+
+ if not is_wandb_available():
+ raise ImportError("This function needs wandb installed: `pip install wandb`")
+ import wandb
+
+ # add WandbCallback if not already added in trainer callbacks
+ reporting_to_wandb = False
+ for callback in trainer.callback_handler.callbacks:
+ if isinstance(callback, WandbCallback):
+ reporting_to_wandb = True
+ break
+ if not reporting_to_wandb:
+ trainer.add_callback(WandbCallback())
+ trainer.args.report_to = ["wandb"]
+ best_trial = {"run_id": None, "objective": None, "hyperparameters": None}
+ sweep_id = kwargs.pop("sweep_id", None)
+ project = kwargs.pop("project", None)
+ name = kwargs.pop("name", None)
+ entity = kwargs.pop("entity", None)
+ metric = kwargs.pop("metric", "eval/loss")
+
+ sweep_config = trainer.hp_space(None)
+ sweep_config["metric"]["goal"] = direction
+ sweep_config["metric"]["name"] = metric
+ if name:
+ sweep_config["name"] = name
+
+ def _objective():
+ run = wandb.run if wandb.run else wandb.init()
+ trainer.state.trial_name = run.name
+ run.config.update({"assignments": {}, "metric": metric})
+ config = wandb.config
+
+ trainer.objective = None
+
+ trainer.train(resume_from_checkpoint=None, trial=vars(config)["_items"])
+ # If there hasn't been any evaluation during the training loop.
+ if getattr(trainer, "objective", None) is None:
+ metrics = trainer.evaluate()
+ trainer.objective = trainer.compute_objective(metrics)
+ format_metrics = rewrite_logs(metrics)
+ if metric not in format_metrics:
+ logger.warning(
+ f"Provided metric {metric} not found. This might result in unexpected sweeps charts. The available"
+ f" metrics are {format_metrics.keys()}"
+ )
+ best_score = False
+ if best_trial["run_id"] is not None:
+ if direction == "minimize":
+ best_score = trainer.objective < best_trial["objective"]
+ elif direction == "maximize":
+ best_score = trainer.objective > best_trial["objective"]
+
+ if best_score or best_trial["run_id"] is None:
+ best_trial["run_id"] = run.id
+ best_trial["objective"] = trainer.objective
+ best_trial["hyperparameters"] = dict(config)
+
+ return trainer.objective
+
+ if not sweep_id:
+ sweep_id = wandb.sweep(sweep_config, project=project, entity=entity)
+ else:
+ import wandb.env
+
+ if entity:
+ wandb.env.set_entity(entity)
+ wandb.env.set_project(project)
+
+ logger.info(f"wandb sweep id - {sweep_id}")
+ wandb.agent(sweep_id, function=_objective, count=n_trials)
+
+ return BestRun(best_trial["run_id"], best_trial["objective"], best_trial["hyperparameters"], sweep_id)
+
+
+def get_available_reporting_integrations():
+ integrations = []
+ if is_azureml_available() and not is_mlflow_available():
+ integrations.append("azure_ml")
+ if is_comet_available():
+ integrations.append("comet_ml")
+ if is_dagshub_available():
+ integrations.append("dagshub")
+ if is_dvclive_available():
+ integrations.append("dvclive")
+ if is_mlflow_available():
+ integrations.append("mlflow")
+ if is_neptune_available():
+ integrations.append("neptune")
+ if is_tensorboard_available():
+ integrations.append("tensorboard")
+ if is_wandb_available():
+ integrations.append("wandb")
+ if is_codecarbon_available():
+ integrations.append("codecarbon")
+ if is_clearml_available():
+ integrations.append("clearml")
+ if is_swanlab_available():
+ integrations.append("swanlab")
+ return integrations
+
+
+def rewrite_logs(d):
+ new_d = {}
+ eval_prefix = "eval_"
+ eval_prefix_len = len(eval_prefix)
+ test_prefix = "test_"
+ test_prefix_len = len(test_prefix)
+ for k, v in d.items():
+ if k.startswith(eval_prefix):
+ new_d["eval/" + k[eval_prefix_len:]] = v
+ elif k.startswith(test_prefix):
+ new_d["test/" + k[test_prefix_len:]] = v
+ else:
+ new_d["train/" + k] = v
+ return new_d
+
+
+class TensorBoardCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that sends the logs to [TensorBoard](https://www.tensorflow.org/tensorboard).
+
+ Args:
+ tb_writer (`SummaryWriter`, *optional*):
+ The writer to use. Will instantiate one if not set.
+ """
+
+ def __init__(self, tb_writer=None):
+ has_tensorboard = is_tensorboard_available()
+ if not has_tensorboard:
+ raise RuntimeError(
+ "TensorBoardCallback requires tensorboard to be installed. Either update your PyTorch version or"
+ " install tensorboardX."
+ )
+ if has_tensorboard:
+ try:
+ from torch.utils.tensorboard import SummaryWriter # noqa: F401
+
+ self._SummaryWriter = SummaryWriter
+ except ImportError:
+ try:
+ from tensorboardX import SummaryWriter
+
+ self._SummaryWriter = SummaryWriter
+ except ImportError:
+ self._SummaryWriter = None
+ else:
+ self._SummaryWriter = None
+ self.tb_writer = tb_writer
+
+ def _init_summary_writer(self, args, log_dir=None):
+ log_dir = log_dir or args.logging_dir
+ if self._SummaryWriter is not None:
+ self.tb_writer = self._SummaryWriter(log_dir=log_dir)
+
+ def on_train_begin(self, args, state, control, **kwargs):
+ if not state.is_world_process_zero:
+ return
+
+ log_dir = None
+
+ if state.is_hyper_param_search:
+ trial_name = state.trial_name
+ if trial_name is not None:
+ log_dir = os.path.join(args.logging_dir, trial_name)
+
+ if self.tb_writer is None:
+ self._init_summary_writer(args, log_dir)
+
+ if self.tb_writer is not None:
+ self.tb_writer.add_text("args", args.to_json_string())
+ if "model" in kwargs:
+ model = kwargs["model"]
+ if hasattr(model, "config") and model.config is not None:
+ model_config_json = model.config.to_json_string()
+ self.tb_writer.add_text("model_config", model_config_json)
+
+ def on_log(self, args, state, control, logs=None, **kwargs):
+ if not state.is_world_process_zero:
+ return
+
+ if self.tb_writer is None:
+ self._init_summary_writer(args)
+
+ if self.tb_writer is not None:
+ logs = rewrite_logs(logs)
+ for k, v in logs.items():
+ if isinstance(v, (int, float)):
+ self.tb_writer.add_scalar(k, v, state.global_step)
+ elif isinstance(v, str):
+ self.tb_writer.add_text(k, v, state.global_step)
+ else:
+ logger.warning(
+ "Trainer is attempting to log a value of "
+ f'"{v}" of type {type(v)} for key "{k}" as a scalar. '
+ "This invocation of Tensorboard's writer.add_scalar() "
+ "is incorrect so we dropped this attribute."
+ )
+ self.tb_writer.flush()
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if self.tb_writer:
+ self.tb_writer.close()
+ self.tb_writer = None
+
+
+def save_model_architecture_to_file(model: Any, output_dir: str):
+ with open(f"{output_dir}/model_architecture.txt", "w+") as f:
+ if isinstance(model, PreTrainedModel):
+ print(model, file=f)
+ elif is_tf_available() and isinstance(model, TFPreTrainedModel):
+
+ def print_to_file(s):
+ print(s, file=f)
+
+ model.summary(print_fn=print_to_file)
+ elif is_torch_available() and (
+ isinstance(model, (torch.nn.Module, PushToHubMixin)) and hasattr(model, "base_model")
+ ):
+ print(model, file=f)
+
+
+class WandbLogModel(str, Enum):
+ """Enum of possible log model values in W&B."""
+
+ CHECKPOINT = "checkpoint"
+ END = "end"
+ FALSE = "false"
+
+ @property
+ def is_enabled(self) -> bool:
+ """Check if the value corresponds to a state where the `WANDB_LOG_MODEL` setting is enabled."""
+ return self in (WandbLogModel.CHECKPOINT, WandbLogModel.END)
+
+ @classmethod
+ def _missing_(cls, value: Any) -> "WandbLogModel":
+ if not isinstance(value, str):
+ raise ValueError(f"Expecting to have a string `WANDB_LOG_MODEL` setting, but got {type(value)}")
+ if value.upper() in ENV_VARS_TRUE_VALUES:
+ raise DeprecationWarning(
+ f"Setting `WANDB_LOG_MODEL` as {os.getenv('WANDB_LOG_MODEL')} is deprecated and will be removed in "
+ "version 5 of transformers. Use one of `'end'` or `'checkpoint'` instead."
+ )
+ logger.info(f"Setting `WANDB_LOG_MODEL` from {os.getenv('WANDB_LOG_MODEL')} to `end` instead")
+ return WandbLogModel.END
+ logger.warning(
+ f"Received unrecognized `WANDB_LOG_MODEL` setting value={value}; so disabling `WANDB_LOG_MODEL`"
+ )
+ return WandbLogModel.FALSE
+
+
+class WandbCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that logs metrics, media, model checkpoints to [Weight and Biases](https://www.wandb.com/).
+ """
+
+ def __init__(self):
+ has_wandb = is_wandb_available()
+ if not has_wandb:
+ raise RuntimeError("WandbCallback requires wandb to be installed. Run `pip install wandb`.")
+ if has_wandb:
+ import wandb
+
+ self._wandb = wandb
+ self._initialized = False
+ self._log_model = WandbLogModel(os.getenv("WANDB_LOG_MODEL", "false"))
+
+ def setup(self, args, state, model, **kwargs):
+ """
+ Setup the optional Weights & Biases (*wandb*) integration.
+
+ One can subclass and override this method to customize the setup if needed. Find more information
+ [here](https://docs.wandb.ai/guides/integrations/huggingface). You can also override the following environment
+ variables:
+
+ Environment:
+ - **WANDB_LOG_MODEL** (`str`, *optional*, defaults to `"false"`):
+ Whether to log model and checkpoints during training. Can be `"end"`, `"checkpoint"` or `"false"`. If set
+ to `"end"`, the model will be uploaded at the end of training. If set to `"checkpoint"`, the checkpoint
+ will be uploaded every `args.save_steps` . If set to `"false"`, the model will not be uploaded. Use along
+ with [`~transformers.TrainingArguments.load_best_model_at_end`] to upload best model.
+
+
+
+ Setting `WANDB_LOG_MODEL` as `bool` will be deprecated in version 5 of 🤗 Transformers.
+
+
+ - **WANDB_WATCH** (`str`, *optional* defaults to `"false"`):
+ Can be `"gradients"`, `"all"`, `"parameters"`, or `"false"`. Set to `"all"` to log gradients and
+ parameters.
+ - **WANDB_PROJECT** (`str`, *optional*, defaults to `"huggingface"`):
+ Set this to a custom string to store results in a different project.
+ - **WANDB_DISABLED** (`bool`, *optional*, defaults to `False`):
+ Whether to disable wandb entirely. Set `WANDB_DISABLED=true` to disable.
+ """
+ if self._wandb is None:
+ return
+ self._initialized = True
+
+ # prepare to handle potential configuration issues during setup
+ from wandb.sdk.lib.config_util import ConfigError as WandbConfigError
+
+ if state.is_world_process_zero:
+ logger.info(
+ 'Automatic Weights & Biases logging enabled, to disable set os.environ["WANDB_DISABLED"] = "true"'
+ )
+ combined_dict = {**args.to_dict()}
+
+ if hasattr(model, "config") and model.config is not None:
+ model_config = model.config if isinstance(model.config, dict) else model.config.to_dict()
+ combined_dict = {**model_config, **combined_dict}
+ if hasattr(model, "peft_config") and model.peft_config is not None:
+ peft_config = model.peft_config
+ combined_dict = {**{"peft_config": peft_config}, **combined_dict}
+ trial_name = state.trial_name
+ init_args = {}
+ if trial_name is not None:
+ init_args["name"] = trial_name
+ init_args["group"] = args.run_name
+ elif args.run_name is not None:
+ init_args["name"] = args.run_name
+ if args.run_name == args.output_dir:
+ self._wandb.termwarn(
+ "The `run_name` is currently set to the same value as `TrainingArguments.output_dir`. If this was "
+ "not intended, please specify a different run name by setting the `TrainingArguments.run_name` parameter.",
+ repeat=False,
+ )
+
+ if self._wandb.run is None:
+ self._wandb.init(
+ project=os.getenv("WANDB_PROJECT", "huggingface"),
+ **init_args,
+ )
+ # add config parameters (run may have been created manually)
+ self._wandb.config.update(combined_dict, allow_val_change=True)
+
+ # define default x-axis (for latest wandb versions)
+ if getattr(self._wandb, "define_metric", None):
+ self._wandb.define_metric("train/global_step")
+ self._wandb.define_metric("*", step_metric="train/global_step", step_sync=True)
+
+ # keep track of model topology and gradients, unsupported on TPU
+ _watch_model = os.getenv("WANDB_WATCH", "false")
+ if not is_torch_xla_available() and _watch_model in ("all", "parameters", "gradients"):
+ self._wandb.watch(model, log=_watch_model, log_freq=max(100, state.logging_steps))
+ self._wandb.run._label(code="transformers_trainer")
+
+ # add number of model parameters to wandb config
+ try:
+ self._wandb.config["model/num_parameters"] = model.num_parameters()
+ except AttributeError:
+ logger.info(
+ "Could not log the number of model parameters in Weights & Biases due to an AttributeError."
+ )
+ except WandbConfigError:
+ logger.warning(
+ "A ConfigError was raised whilst setting the number of model parameters in Weights & Biases config."
+ )
+
+ # log the initial model architecture to an artifact
+ if self._log_model.is_enabled:
+ with tempfile.TemporaryDirectory() as temp_dir:
+ model_name = (
+ f"model-{self._wandb.run.id}"
+ if (args.run_name is None or args.run_name == args.output_dir)
+ else f"model-{self._wandb.run.name}"
+ )
+ model_artifact = self._wandb.Artifact(
+ name=model_name,
+ type="model",
+ metadata={
+ "model_config": model.config.to_dict() if hasattr(model, "config") else None,
+ "num_parameters": self._wandb.config.get("model/num_parameters"),
+ "initial_model": True,
+ },
+ )
+ # add the architecture to a separate text file
+ save_model_architecture_to_file(model, temp_dir)
+
+ for f in Path(temp_dir).glob("*"):
+ if f.is_file():
+ with model_artifact.new_file(f.name, mode="wb") as fa:
+ fa.write(f.read_bytes())
+ self._wandb.run.log_artifact(model_artifact, aliases=["base_model"])
+
+ badge_markdown = (
+ f'[
]({self._wandb.run.get_url()})'
+ )
+
+ modelcard.AUTOGENERATED_TRAINER_COMMENT += f"\n{badge_markdown}"
+
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
+ if self._wandb is None:
+ return
+ hp_search = state.is_hyper_param_search
+ if hp_search:
+ self._wandb.finish()
+ self._initialized = False
+ args.run_name = None
+ if not self._initialized:
+ self.setup(args, state, model, **kwargs)
+
+ def on_train_end(self, args, state, control, model=None, processing_class=None, **kwargs):
+ if self._wandb is None:
+ return
+ if self._log_model.is_enabled and self._initialized and state.is_world_process_zero:
+ from ..trainer import Trainer
+
+ fake_trainer = Trainer(args=args, model=model, processing_class=processing_class, eval_dataset=["fake"])
+ with tempfile.TemporaryDirectory() as temp_dir:
+ fake_trainer.save_model(temp_dir)
+ metadata = (
+ {
+ k: v
+ for k, v in dict(self._wandb.summary).items()
+ if isinstance(v, numbers.Number) and not k.startswith("_")
+ }
+ if not args.load_best_model_at_end
+ else {
+ f"eval/{args.metric_for_best_model}": state.best_metric,
+ "train/total_floss": state.total_flos,
+ "model/num_parameters": self._wandb.config.get("model/num_parameters"),
+ }
+ )
+ metadata["final_model"] = True
+ logger.info("Logging model artifacts. ...")
+ model_name = (
+ f"model-{self._wandb.run.id}"
+ if (args.run_name is None or args.run_name == args.output_dir)
+ else f"model-{self._wandb.run.name}"
+ )
+ # add the model architecture to a separate text file
+ save_model_architecture_to_file(model, temp_dir)
+
+ artifact = self._wandb.Artifact(name=model_name, type="model", metadata=metadata)
+ for f in Path(temp_dir).glob("*"):
+ if f.is_file():
+ with artifact.new_file(f.name, mode="wb") as fa:
+ fa.write(f.read_bytes())
+ self._wandb.run.log_artifact(artifact, aliases=["final_model"])
+
+ def on_log(self, args, state, control, model=None, logs=None, **kwargs):
+ single_value_scalars = [
+ "train_runtime",
+ "train_samples_per_second",
+ "train_steps_per_second",
+ "train_loss",
+ "total_flos",
+ ]
+
+ if self._wandb is None:
+ return
+ if not self._initialized:
+ self.setup(args, state, model)
+ if state.is_world_process_zero:
+ for k, v in logs.items():
+ if k in single_value_scalars:
+ self._wandb.run.summary[k] = v
+ non_scalar_logs = {k: v for k, v in logs.items() if k not in single_value_scalars}
+ non_scalar_logs = rewrite_logs(non_scalar_logs)
+ self._wandb.log({**non_scalar_logs, "train/global_step": state.global_step})
+
+ def on_save(self, args, state, control, **kwargs):
+ if self._log_model == WandbLogModel.CHECKPOINT and self._initialized and state.is_world_process_zero:
+ checkpoint_metadata = {
+ k: v
+ for k, v in dict(self._wandb.summary).items()
+ if isinstance(v, numbers.Number) and not k.startswith("_")
+ }
+ checkpoint_metadata["model/num_parameters"] = self._wandb.config.get("model/num_parameters")
+
+ ckpt_dir = f"checkpoint-{state.global_step}"
+ artifact_path = os.path.join(args.output_dir, ckpt_dir)
+ logger.info(f"Logging checkpoint artifacts in {ckpt_dir}. ...")
+ checkpoint_name = (
+ f"model-{self._wandb.run.id}"
+ if (args.run_name is None or args.run_name == args.output_dir)
+ else f"model-{self._wandb.run.name}"
+ )
+ artifact = self._wandb.Artifact(name=checkpoint_name, type="model", metadata=checkpoint_metadata)
+ artifact.add_dir(artifact_path)
+ self._wandb.log_artifact(
+ artifact, aliases=[f"epoch_{round(state.epoch, 2)}", f"checkpoint_global_step_{state.global_step}"]
+ )
+
+ def on_predict(self, args, state, control, metrics, **kwargs):
+ if self._wandb is None:
+ return
+ if not self._initialized:
+ self.setup(args, state, **kwargs)
+ if state.is_world_process_zero:
+ metrics = rewrite_logs(metrics)
+ self._wandb.log(metrics)
+
+
+class CometCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that sends the logs to [Comet ML](https://www.comet.com/site/).
+ """
+
+ def __init__(self):
+ if _is_comet_installed is False or _is_comet_recent_enough is False:
+ raise RuntimeError(
+ f"CometCallback requires comet-ml>={_MIN_COMET_VERSION} to be installed. Run `pip install comet-ml>={_MIN_COMET_VERSION}`."
+ )
+ self._initialized = False
+ self._log_assets = False
+ self._experiment = None
+
+ def setup(self, args, state, model):
+ """
+ Setup the optional Comet integration.
+
+ Environment:
+ - **COMET_MODE** (`str`, *optional*, default to `get_or_create`):
+ Control whether to create and log to a new Comet experiment or append to an existing experiment.
+ It accepts the following values:
+ * `get_or_create`: Decides automatically depending if
+ `COMET_EXPERIMENT_KEY` is set and whether an Experiment
+ with that key already exists or not.
+ * `create`: Always create a new Comet Experiment.
+ * `get`: Always try to append to an Existing Comet Experiment.
+ Requires `COMET_EXPERIMENT_KEY` to be set.
+ * `ONLINE`: **deprecated**, used to create an online
+ Experiment. Use `COMET_START_ONLINE=1` instead.
+ * `OFFLINE`: **deprecated**, used to created an offline
+ Experiment. Use `COMET_START_ONLINE=0` instead.
+ * `DISABLED`: **deprecated**, used to disable Comet logging.
+ Use the `--report_to` flag to control the integrations used
+ for logging result instead.
+ - **COMET_PROJECT_NAME** (`str`, *optional*):
+ Comet project name for experiments.
+ - **COMET_LOG_ASSETS** (`str`, *optional*, defaults to `TRUE`):
+ Whether or not to log training assets (tf event logs, checkpoints, etc), to Comet. Can be `TRUE`, or
+ `FALSE`.
+
+ For a number of configurable items in the environment, see
+ [here](https://www.comet.com/docs/v2/guides/experiment-management/configure-sdk/#explore-comet-configuration-options).
+ """
+ self._initialized = True
+ log_assets = os.getenv("COMET_LOG_ASSETS", "FALSE").upper()
+ if log_assets in {"TRUE", "1"}:
+ self._log_assets = True
+ if state.is_world_process_zero:
+ comet_old_mode = os.getenv("COMET_MODE")
+
+ mode = None
+ online = None
+
+ if comet_old_mode is not None:
+ comet_old_mode = comet_old_mode.lower()
+
+ if comet_old_mode == "online":
+ online = True
+ elif comet_old_mode == "offline":
+ online = False
+ elif comet_old_mode in ("get", "get_or_create", "create"):
+ mode = comet_old_mode
+ elif comet_old_mode:
+ logger.warning("Invalid COMET_MODE env value %r, Comet logging is disabled", comet_old_mode)
+ return
+
+ # For HPO, we always create a new experiment for each trial
+ if state.is_hyper_param_search:
+ if mode is not None:
+ logger.warning(
+ "Hyperparameter Search is enabled, forcing the creation of new experimetns, COMET_MODE value %r is ignored",
+ comet_old_mode,
+ )
+ mode = "create"
+
+ import comet_ml
+
+ # Do not use the default run_name as the experiment name
+ if args.run_name is not None and args.run_name != args.output_dir:
+ experiment_config = comet_ml.ExperimentConfig(name=args.run_name)
+ else:
+ experiment_config = comet_ml.ExperimentConfig()
+
+ self._experiment = comet_ml.start(online=online, mode=mode, experiment_config=experiment_config)
+ self._experiment.__internal_api__set_model_graph__(model, framework="transformers")
+
+ params = {"args": args.to_dict()}
+
+ if hasattr(model, "config") and model.config is not None:
+ model_config = model.config.to_dict()
+ params["config"] = model_config
+ if hasattr(model, "peft_config") and model.peft_config is not None:
+ peft_config = model.peft_config
+ params["peft_config"] = peft_config
+
+ self._experiment.__internal_api__log_parameters__(
+ params, framework="transformers", source="manual", flatten_nested=True
+ )
+
+ if state.is_hyper_param_search:
+ optimization_id = getattr(state, "trial_name", None)
+ optimization_params = getattr(state, "trial_params", None)
+
+ self._experiment.log_optimization(optimization_id=optimization_id, parameters=optimization_params)
+
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
+ if not self._initialized:
+ self.setup(args, state, model)
+
+ def on_log(self, args, state, control, model=None, logs=None, **kwargs):
+ if not self._initialized:
+ self.setup(args, state, model)
+ if state.is_world_process_zero:
+ if self._experiment is not None:
+ rewritten_logs = rewrite_logs(logs)
+ self._experiment.__internal_api__log_metrics__(
+ rewritten_logs, step=state.global_step, epoch=state.epoch, framework="transformers"
+ )
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if self._initialized and state.is_world_process_zero:
+ if self._experiment is not None:
+ if self._log_assets is True:
+ logger.info("Logging checkpoints. This may take time.")
+ self._experiment.log_asset_folder(
+ args.output_dir, recursive=True, log_file_name=True, step=state.global_step
+ )
+
+ # We create one experiment per trial in HPO mode
+ if state.is_hyper_param_search:
+ self._experiment.clean()
+ self._initialized = False
+
+ def on_predict(self, args, state, control, metrics, **kwargs):
+ if not self._initialized:
+ self.setup(args, state, model=None)
+ if state.is_world_process_zero and self._experiment is not None:
+ rewritten_metrics = rewrite_logs(metrics)
+ self._experiment.__internal_api__log_metrics__(
+ rewritten_metrics, step=state.global_step, epoch=state.epoch, framework="transformers"
+ )
+
+
+class AzureMLCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that sends the logs to [AzureML](https://pypi.org/project/azureml-sdk/).
+ """
+
+ def __init__(self, azureml_run=None):
+ if not is_azureml_available():
+ raise RuntimeError("AzureMLCallback requires azureml to be installed. Run `pip install azureml-sdk`.")
+ self.azureml_run = azureml_run
+
+ def on_init_end(self, args, state, control, **kwargs):
+ from azureml.core.run import Run
+
+ if self.azureml_run is None and state.is_world_process_zero:
+ self.azureml_run = Run.get_context()
+
+ def on_log(self, args, state, control, logs=None, **kwargs):
+ if self.azureml_run and state.is_world_process_zero:
+ for k, v in logs.items():
+ if isinstance(v, (int, float)):
+ self.azureml_run.log(k, v, description=k)
+
+
+class MLflowCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that sends the logs to [MLflow](https://www.mlflow.org/). Can be disabled by setting
+ environment variable `DISABLE_MLFLOW_INTEGRATION = TRUE`.
+ """
+
+ def __init__(self):
+ if not is_mlflow_available():
+ raise RuntimeError("MLflowCallback requires mlflow to be installed. Run `pip install mlflow`.")
+ import mlflow
+
+ self._MAX_PARAM_VAL_LENGTH = mlflow.utils.validation.MAX_PARAM_VAL_LENGTH
+ self._MAX_PARAMS_TAGS_PER_BATCH = mlflow.utils.validation.MAX_PARAMS_TAGS_PER_BATCH
+
+ self._initialized = False
+ self._auto_end_run = False
+ self._log_artifacts = False
+ self._ml_flow = mlflow
+
+ def setup(self, args, state, model):
+ """
+ Setup the optional MLflow integration.
+
+ Environment:
+ - **HF_MLFLOW_LOG_ARTIFACTS** (`str`, *optional*):
+ Whether to use MLflow `.log_artifact()` facility to log artifacts. This only makes sense if logging to a
+ remote server, e.g. s3 or GCS. If set to `True` or *1*, will copy each saved checkpoint on each save in
+ [`TrainingArguments`]'s `output_dir` to the local or remote artifact storage. Using it without a remote
+ storage will just copy the files to your artifact location.
+ - **MLFLOW_TRACKING_URI** (`str`, *optional*):
+ Whether to store runs at a specific path or remote server. Unset by default, which skips setting the
+ tracking URI entirely.
+ - **MLFLOW_EXPERIMENT_NAME** (`str`, *optional*, defaults to `None`):
+ Whether to use an MLflow experiment_name under which to launch the run. Default to `None` which will point
+ to the `Default` experiment in MLflow. Otherwise, it is a case sensitive name of the experiment to be
+ activated. If an experiment with this name does not exist, a new experiment with this name is created.
+ - **MLFLOW_TAGS** (`str`, *optional*):
+ A string dump of a dictionary of key/value pair to be added to the MLflow run as tags. Example:
+ `os.environ['MLFLOW_TAGS']='{"release.candidate": "RC1", "release.version": "2.2.0"}'`.
+ - **MLFLOW_NESTED_RUN** (`str`, *optional*):
+ Whether to use MLflow nested runs. If set to `True` or *1*, will create a nested run inside the current
+ run.
+ - **MLFLOW_RUN_ID** (`str`, *optional*):
+ Allow to reattach to an existing run which can be useful when resuming training from a checkpoint. When
+ `MLFLOW_RUN_ID` environment variable is set, `start_run` attempts to resume a run with the specified run ID
+ and other parameters are ignored.
+ - **MLFLOW_FLATTEN_PARAMS** (`str`, *optional*, defaults to `False`):
+ Whether to flatten the parameters dictionary before logging.
+ - **MLFLOW_MAX_LOG_PARAMS** (`int`, *optional*):
+ Set the maximum number of parameters to log in the run.
+ """
+ self._log_artifacts = os.getenv("HF_MLFLOW_LOG_ARTIFACTS", "FALSE").upper() in ENV_VARS_TRUE_VALUES
+ self._nested_run = os.getenv("MLFLOW_NESTED_RUN", "FALSE").upper() in ENV_VARS_TRUE_VALUES
+ self._tracking_uri = os.getenv("MLFLOW_TRACKING_URI", None)
+ self._experiment_name = os.getenv("MLFLOW_EXPERIMENT_NAME", None)
+ self._flatten_params = os.getenv("MLFLOW_FLATTEN_PARAMS", "FALSE").upper() in ENV_VARS_TRUE_VALUES
+ self._run_id = os.getenv("MLFLOW_RUN_ID", None)
+ self._max_log_params = os.getenv("MLFLOW_MAX_LOG_PARAMS", None)
+
+ # "synchronous" flag is only available with mlflow version >= 2.8.0
+ # https://github.com/mlflow/mlflow/pull/9705
+ # https://github.com/mlflow/mlflow/releases/tag/v2.8.0
+ self._async_log = packaging.version.parse(self._ml_flow.__version__) >= packaging.version.parse("2.8.0")
+
+ logger.debug(
+ f"MLflow experiment_name={self._experiment_name}, run_name={args.run_name}, nested={self._nested_run},"
+ f" tracking_uri={self._tracking_uri}"
+ )
+ if state.is_world_process_zero:
+ if not self._ml_flow.is_tracking_uri_set():
+ if self._tracking_uri:
+ self._ml_flow.set_tracking_uri(self._tracking_uri)
+ logger.debug(f"MLflow tracking URI is set to {self._tracking_uri}")
+ else:
+ logger.debug(
+ "Environment variable `MLFLOW_TRACKING_URI` is not provided and therefore will not be"
+ " explicitly set."
+ )
+ else:
+ logger.debug(f"MLflow tracking URI is set to {self._ml_flow.get_tracking_uri()}")
+
+ if self._ml_flow.active_run() is None or self._nested_run or self._run_id:
+ if self._experiment_name:
+ # Use of set_experiment() ensure that Experiment is created if not exists
+ self._ml_flow.set_experiment(self._experiment_name)
+ self._ml_flow.start_run(run_name=args.run_name, nested=self._nested_run)
+ logger.debug(f"MLflow run started with run_id={self._ml_flow.active_run().info.run_id}")
+ self._auto_end_run = True
+ combined_dict = args.to_dict()
+ if hasattr(model, "config") and model.config is not None:
+ model_config = model.config.to_dict()
+ combined_dict = {**model_config, **combined_dict}
+ combined_dict = flatten_dict(combined_dict) if self._flatten_params else combined_dict
+ # remove params that are too long for MLflow
+ for name, value in list(combined_dict.items()):
+ # internally, all values are converted to str in MLflow
+ if len(str(value)) > self._MAX_PARAM_VAL_LENGTH:
+ logger.warning(
+ f'Trainer is attempting to log a value of "{value}" for key "{name}" as a parameter. MLflow\'s'
+ " log_param() only accepts values no longer than 250 characters so we dropped this attribute."
+ " You can use `MLFLOW_FLATTEN_PARAMS` environment variable to flatten the parameters and"
+ " avoid this message."
+ )
+ del combined_dict[name]
+ # MLflow cannot log more than 100 values in one go, so we have to split it
+ combined_dict_items = list(combined_dict.items())
+ if self._max_log_params and self._max_log_params.isdigit():
+ max_log_params = int(self._max_log_params)
+ if max_log_params < len(combined_dict_items):
+ logger.debug(
+ f"Reducing the number of parameters to log from {len(combined_dict_items)} to {max_log_params}."
+ )
+ combined_dict_items = combined_dict_items[:max_log_params]
+ for i in range(0, len(combined_dict_items), self._MAX_PARAMS_TAGS_PER_BATCH):
+ if self._async_log:
+ self._ml_flow.log_params(
+ dict(combined_dict_items[i : i + self._MAX_PARAMS_TAGS_PER_BATCH]), synchronous=False
+ )
+ else:
+ self._ml_flow.log_params(dict(combined_dict_items[i : i + self._MAX_PARAMS_TAGS_PER_BATCH]))
+ mlflow_tags = os.getenv("MLFLOW_TAGS", None)
+ if mlflow_tags:
+ mlflow_tags = json.loads(mlflow_tags)
+ self._ml_flow.set_tags(mlflow_tags)
+ self._initialized = True
+
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
+ if not self._initialized:
+ self.setup(args, state, model)
+
+ def on_log(self, args, state, control, logs, model=None, **kwargs):
+ if not self._initialized:
+ self.setup(args, state, model)
+ if state.is_world_process_zero:
+ metrics = {}
+ for k, v in logs.items():
+ if isinstance(v, (int, float)):
+ metrics[k] = v
+ elif isinstance(v, torch.Tensor) and v.numel() == 1:
+ metrics[k] = v.item()
+ else:
+ logger.warning(
+ f'Trainer is attempting to log a value of "{v}" of type {type(v)} for key "{k}" as a metric. '
+ "MLflow's log_metric() only accepts float and int types so we dropped this attribute."
+ )
+
+ if self._async_log:
+ self._ml_flow.log_metrics(metrics=metrics, step=state.global_step, synchronous=False)
+ else:
+ self._ml_flow.log_metrics(metrics=metrics, step=state.global_step)
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if self._initialized and state.is_world_process_zero:
+ if self._auto_end_run and self._ml_flow.active_run():
+ self._ml_flow.end_run()
+
+ def on_save(self, args, state, control, **kwargs):
+ if self._initialized and state.is_world_process_zero and self._log_artifacts:
+ ckpt_dir = f"checkpoint-{state.global_step}"
+ artifact_path = os.path.join(args.output_dir, ckpt_dir)
+ logger.info(f"Logging checkpoint artifacts in {ckpt_dir}. This may take time.")
+ self._ml_flow.pyfunc.log_model(
+ ckpt_dir,
+ artifacts={"model_path": artifact_path},
+ python_model=self._ml_flow.pyfunc.PythonModel(),
+ )
+
+ def __del__(self):
+ # if the previous run is not terminated correctly, the fluent API will
+ # not let you start a new run before the previous one is killed
+ if (
+ self._auto_end_run
+ and callable(getattr(self._ml_flow, "active_run", None))
+ and self._ml_flow.active_run() is not None
+ ):
+ self._ml_flow.end_run()
+
+
+class DagsHubCallback(MLflowCallback):
+ """
+ A [`TrainerCallback`] that logs to [DagsHub](https://dagshub.com/). Extends [`MLflowCallback`]
+ """
+
+ def __init__(self):
+ super().__init__()
+ if not is_dagshub_available():
+ raise ImportError("DagsHubCallback requires dagshub to be installed. Run `pip install dagshub`.")
+
+ from dagshub.upload import Repo
+
+ self.Repo = Repo
+
+ def setup(self, *args, **kwargs):
+ """
+ Setup the DagsHub's Logging integration.
+
+ Environment:
+ - **HF_DAGSHUB_LOG_ARTIFACTS** (`str`, *optional*):
+ Whether to save the data and model artifacts for the experiment. Default to `False`.
+ """
+
+ self.log_artifacts = os.getenv("HF_DAGSHUB_LOG_ARTIFACTS", "FALSE").upper() in ENV_VARS_TRUE_VALUES
+ self.name = os.getenv("HF_DAGSHUB_MODEL_NAME") or "main"
+ self.remote = os.getenv("MLFLOW_TRACKING_URI")
+ self.repo = self.Repo(
+ owner=self.remote.split(os.sep)[-2],
+ name=self.remote.split(os.sep)[-1].split(".")[0],
+ branch=os.getenv("BRANCH") or "main",
+ )
+ self.path = Path("artifacts")
+
+ if self.remote is None:
+ raise RuntimeError(
+ "DagsHubCallback requires the `MLFLOW_TRACKING_URI` environment variable to be set. Did you run"
+ " `dagshub.init()`?"
+ )
+
+ super().setup(*args, **kwargs)
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if self.log_artifacts:
+ if getattr(self, "train_dataloader", None):
+ torch.save(self.train_dataloader.dataset, os.path.join(args.output_dir, "dataset.pt"))
+
+ self.repo.directory(str(self.path)).add_dir(args.output_dir)
+
+
+class NeptuneMissingConfiguration(Exception):
+ def __init__(self):
+ super().__init__(
+ """
+ ------ Unsupported ---- We were not able to create new runs. You provided a custom Neptune run to
+ `NeptuneCallback` with the `run` argument. For the integration to work fully, provide your `api_token` and
+ `project` by saving them as environment variables or passing them to the callback.
+ """
+ )
+
+
+class NeptuneCallback(TrainerCallback):
+ """TrainerCallback that sends the logs to [Neptune](https://app.neptune.ai).
+
+ Args:
+ api_token (`str`, *optional*): Neptune API token obtained upon registration.
+ You can leave this argument out if you have saved your token to the `NEPTUNE_API_TOKEN` environment
+ variable (strongly recommended). See full setup instructions in the
+ [docs](https://docs.neptune.ai/setup/installation).
+ project (`str`, *optional*): Name of an existing Neptune project, in the form "workspace-name/project-name".
+ You can find and copy the name in Neptune from the project settings -> Properties. If None (default), the
+ value of the `NEPTUNE_PROJECT` environment variable is used.
+ name (`str`, *optional*): Custom name for the run.
+ base_namespace (`str`, *optional*, defaults to "finetuning"): In the Neptune run, the root namespace
+ that will contain all of the metadata logged by the callback.
+ log_parameters (`bool`, *optional*, defaults to `True`):
+ If True, logs all Trainer arguments and model parameters provided by the Trainer.
+ log_checkpoints (`str`, *optional*): If "same", uploads checkpoints whenever they are saved by the Trainer.
+ If "last", uploads only the most recently saved checkpoint. If "best", uploads the best checkpoint (among
+ the ones saved by the Trainer). If `None`, does not upload checkpoints.
+ run (`Run`, *optional*): Pass a Neptune run object if you want to continue logging to an existing run.
+ Read more about resuming runs in the [docs](https://docs.neptune.ai/logging/to_existing_object).
+ **neptune_run_kwargs (*optional*):
+ Additional keyword arguments to be passed directly to the
+ [`neptune.init_run()`](https://docs.neptune.ai/api/neptune#init_run) function when a new run is created.
+
+ For instructions and examples, see the [Transformers integration
+ guide](https://docs.neptune.ai/integrations/transformers) in the Neptune documentation.
+ """
+
+ integration_version_key = "source_code/integrations/transformers"
+ model_parameters_key = "model_parameters"
+ trial_name_key = "trial"
+ trial_params_key = "trial_params"
+ trainer_parameters_key = "trainer_parameters"
+ flat_metrics = {"train/epoch"}
+
+ def __init__(
+ self,
+ *,
+ api_token: Optional[str] = None,
+ project: Optional[str] = None,
+ name: Optional[str] = None,
+ base_namespace: str = "finetuning",
+ run=None,
+ log_parameters: bool = True,
+ log_checkpoints: Optional[str] = None,
+ **neptune_run_kwargs,
+ ):
+ if not is_neptune_available():
+ raise ValueError(
+ "NeptuneCallback requires the Neptune client library to be installed. "
+ "To install the library, run `pip install neptune`."
+ )
+
+ try:
+ from neptune import Run
+ from neptune.internal.utils import verify_type
+ except ImportError:
+ from neptune.new.internal.utils import verify_type
+ from neptune.new.metadata_containers.run import Run
+
+ verify_type("api_token", api_token, (str, type(None)))
+ verify_type("project", project, (str, type(None)))
+ verify_type("name", name, (str, type(None)))
+ verify_type("base_namespace", base_namespace, str)
+ verify_type("run", run, (Run, type(None)))
+ verify_type("log_parameters", log_parameters, bool)
+ verify_type("log_checkpoints", log_checkpoints, (str, type(None)))
+
+ self._base_namespace_path = base_namespace
+ self._log_parameters = log_parameters
+ self._log_checkpoints = log_checkpoints
+ self._initial_run: Optional[Run] = run
+
+ self._run = None
+ self._is_monitoring_run = False
+ self._run_id = None
+ self._force_reset_monitoring_run = False
+ self._init_run_kwargs = {"api_token": api_token, "project": project, "name": name, **neptune_run_kwargs}
+
+ self._volatile_checkpoints_dir = None
+ self._should_upload_checkpoint = self._log_checkpoints is not None
+ self._recent_checkpoint_path = None
+
+ if self._log_checkpoints in {"last", "best"}:
+ self._target_checkpoints_namespace = f"checkpoints/{self._log_checkpoints}"
+ self._should_clean_recently_uploaded_checkpoint = True
+ else:
+ self._target_checkpoints_namespace = "checkpoints"
+ self._should_clean_recently_uploaded_checkpoint = False
+
+ def _stop_run_if_exists(self):
+ if self._run:
+ self._run.stop()
+ del self._run
+ self._run = None
+
+ def _initialize_run(self, **additional_neptune_kwargs):
+ try:
+ from neptune import init_run
+ from neptune.exceptions import NeptuneMissingApiTokenException, NeptuneMissingProjectNameException
+ except ImportError:
+ from neptune.new import init_run
+ from neptune.new.exceptions import NeptuneMissingApiTokenException, NeptuneMissingProjectNameException
+
+ self._stop_run_if_exists()
+
+ try:
+ run_params = additional_neptune_kwargs.copy()
+ run_params.update(self._init_run_kwargs)
+ self._run = init_run(**run_params)
+ self._run_id = self._run["sys/id"].fetch()
+ except (NeptuneMissingProjectNameException, NeptuneMissingApiTokenException) as e:
+ raise NeptuneMissingConfiguration() from e
+
+ def _use_initial_run(self):
+ self._run = self._initial_run
+ self._is_monitoring_run = True
+ self._run_id = self._run["sys/id"].fetch()
+ self._initial_run = None
+
+ def _ensure_run_with_monitoring(self):
+ if self._initial_run is not None:
+ self._use_initial_run()
+ else:
+ if not self._force_reset_monitoring_run and self._is_monitoring_run:
+ return
+
+ if self._run and not self._is_monitoring_run and not self._force_reset_monitoring_run:
+ self._initialize_run(with_id=self._run_id)
+ self._is_monitoring_run = True
+ else:
+ self._initialize_run()
+ self._force_reset_monitoring_run = False
+
+ def _ensure_at_least_run_without_monitoring(self):
+ if self._initial_run is not None:
+ self._use_initial_run()
+ else:
+ if not self._run:
+ self._initialize_run(
+ with_id=self._run_id,
+ capture_stdout=False,
+ capture_stderr=False,
+ capture_hardware_metrics=False,
+ capture_traceback=False,
+ )
+ self._is_monitoring_run = False
+
+ @property
+ def run(self):
+ if self._run is None:
+ self._ensure_at_least_run_without_monitoring()
+ return self._run
+
+ @property
+ def _metadata_namespace(self):
+ return self.run[self._base_namespace_path]
+
+ def _log_integration_version(self):
+ self.run[NeptuneCallback.integration_version_key] = version
+
+ def _log_trainer_parameters(self, args):
+ self._metadata_namespace[NeptuneCallback.trainer_parameters_key] = args.to_sanitized_dict()
+
+ def _log_model_parameters(self, model):
+ from neptune.utils import stringify_unsupported
+
+ if model and hasattr(model, "config") and model.config is not None:
+ self._metadata_namespace[NeptuneCallback.model_parameters_key] = stringify_unsupported(
+ model.config.to_dict()
+ )
+
+ def _log_hyper_param_search_parameters(self, state):
+ if state and hasattr(state, "trial_name"):
+ self._metadata_namespace[NeptuneCallback.trial_name_key] = state.trial_name
+
+ if state and hasattr(state, "trial_params") and state.trial_params is not None:
+ self._metadata_namespace[NeptuneCallback.trial_params_key] = state.trial_params
+
+ def _log_model_checkpoint(self, source_directory: str, checkpoint: str):
+ target_path = relative_path = os.path.join(source_directory, checkpoint)
+
+ if self._volatile_checkpoints_dir is not None:
+ consistent_checkpoint_path = os.path.join(self._volatile_checkpoints_dir, checkpoint)
+ try:
+ # Remove leading ../ from a relative path.
+ cpkt_path = relative_path.replace("..", "").lstrip(os.path.sep)
+ copy_path = os.path.join(consistent_checkpoint_path, cpkt_path)
+ shutil.copytree(relative_path, copy_path)
+ target_path = consistent_checkpoint_path
+ except IOError as e:
+ logger.warning(
+ "NeptuneCallback was unable to made a copy of checkpoint due to I/O exception: '{}'. "
+ "Could fail trying to upload.".format(e)
+ )
+
+ self._metadata_namespace[self._target_checkpoints_namespace].upload_files(target_path)
+
+ if self._should_clean_recently_uploaded_checkpoint and self._recent_checkpoint_path is not None:
+ self._metadata_namespace[self._target_checkpoints_namespace].delete_files(self._recent_checkpoint_path)
+
+ self._recent_checkpoint_path = relative_path
+
+ def on_init_end(self, args, state, control, **kwargs):
+ self._volatile_checkpoints_dir = None
+ if self._log_checkpoints and (args.overwrite_output_dir or args.save_total_limit is not None):
+ self._volatile_checkpoints_dir = tempfile.TemporaryDirectory().name
+
+ if self._log_checkpoints == "best" and not args.load_best_model_at_end:
+ raise ValueError("To save the best model checkpoint, the load_best_model_at_end argument must be enabled.")
+
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
+ if not state.is_world_process_zero:
+ return
+
+ self._ensure_run_with_monitoring()
+ self._force_reset_monitoring_run = True
+
+ self._log_integration_version()
+ if self._log_parameters:
+ self._log_trainer_parameters(args)
+ self._log_model_parameters(model)
+
+ if state.is_hyper_param_search:
+ self._log_hyper_param_search_parameters(state)
+
+ def on_train_end(self, args, state, control, **kwargs):
+ self._stop_run_if_exists()
+
+ def __del__(self):
+ if self._volatile_checkpoints_dir is not None:
+ shutil.rmtree(self._volatile_checkpoints_dir, ignore_errors=True)
+
+ self._stop_run_if_exists()
+
+ def on_save(self, args, state, control, **kwargs):
+ if self._should_upload_checkpoint:
+ self._log_model_checkpoint(args.output_dir, f"checkpoint-{state.global_step}")
+
+ def on_evaluate(self, args, state, control, metrics=None, **kwargs):
+ if self._log_checkpoints == "best":
+ best_metric_name = args.metric_for_best_model
+ if not best_metric_name.startswith("eval_"):
+ best_metric_name = f"eval_{best_metric_name}"
+
+ metric_value = metrics.get(best_metric_name)
+
+ operator = np.greater if args.greater_is_better else np.less
+
+ self._should_upload_checkpoint = state.best_metric is None or operator(metric_value, state.best_metric)
+
+ @classmethod
+ def get_run(cls, trainer):
+ for callback in trainer.callback_handler.callbacks:
+ if isinstance(callback, cls):
+ return callback.run
+
+ raise Exception("The trainer doesn't have a NeptuneCallback configured.")
+
+ def on_log(self, args, state, control, logs: Optional[Dict[str, float]] = None, **kwargs):
+ if not state.is_world_process_zero:
+ return
+
+ if logs is not None:
+ for name, value in rewrite_logs(logs).items():
+ if isinstance(value, (int, float)):
+ if name in NeptuneCallback.flat_metrics:
+ self._metadata_namespace[name] = value
+ else:
+ self._metadata_namespace[name].log(value, step=state.global_step)
+
+
+class CodeCarbonCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that tracks the CO2 emission of training.
+ """
+
+ def __init__(self):
+ if not is_codecarbon_available():
+ raise RuntimeError(
+ "CodeCarbonCallback requires `codecarbon` to be installed. Run `pip install codecarbon`."
+ )
+ elif torch.version.hip:
+ raise RuntimeError(
+ "CodeCarbonCallback requires `codecarbon` package, which is not compatible with AMD ROCm (https://github.com/mlco2/codecarbon/pull/490). When using the Trainer, please specify the `report_to` argument (https://huggingface.co/docs/transformers/v4.39.3/en/main_classes/trainer#transformers.TrainingArguments.report_to) to disable CodeCarbonCallback."
+ )
+
+ import codecarbon
+
+ self._codecarbon = codecarbon
+ self.tracker = None
+
+ def on_init_end(self, args, state, control, **kwargs):
+ if self.tracker is None and state.is_local_process_zero:
+ # CodeCarbon will automatically handle environment variables for configuration
+ self.tracker = self._codecarbon.EmissionsTracker(output_dir=args.output_dir)
+
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
+ if self.tracker and state.is_local_process_zero:
+ self.tracker.start()
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if self.tracker and state.is_local_process_zero:
+ self.tracker.stop()
+
+
+class ClearMLCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that sends the logs to [ClearML](https://clear.ml/).
+
+ Environment:
+ - **CLEARML_PROJECT** (`str`, *optional*, defaults to `HuggingFace Transformers`):
+ ClearML project name.
+ - **CLEARML_TASK** (`str`, *optional*, defaults to `Trainer`):
+ ClearML task name.
+ - **CLEARML_LOG_MODEL** (`bool`, *optional*, defaults to `False`):
+ Whether to log models as artifacts during training.
+ """
+
+ log_suffix = ""
+
+ _hparams_section = "Transformers"
+ _model_config_section = "Model Configuration"
+ _ignore_hparams_overrides = "_ignore_hparams_ui_overrides_"
+ _ignoge_model_config_overrides = "_ignore_model_config_ui_overrides_"
+ _model_config_description = "The configuration of model number {}."
+ _model_config_description_note = (
+ "Note that, when cloning this task and running it remotely,"
+ " the configuration might be applied to another model instead of this one."
+ " To avoid this, initialize the task externally by calling `Task.init`"
+ " before the `ClearMLCallback` is instantiated."
+ )
+ _train_run_counter = 0
+ _model_connect_counter = 0
+ _task_created_in_callback = False
+ _should_close_on_train_end = None
+
+ def __init__(self):
+ if is_clearml_available():
+ import clearml
+
+ self._clearml = clearml
+ else:
+ raise RuntimeError("ClearMLCallback requires 'clearml' to be installed. Run `pip install clearml`.")
+
+ self._initialized = False
+ self._clearml_task = None
+
+ self._log_model = False
+ self._checkpoints_saved = []
+
+ def setup(self, args, state, model, processing_class, **kwargs):
+ if self._clearml is None:
+ return
+ if self._initialized:
+ return
+ ClearMLCallback._train_run_counter += 1
+ ClearMLCallback._model_connect_counter += 1
+ ClearMLCallback.log_suffix = (
+ "" if ClearMLCallback._train_run_counter == 1 else "_" + str(ClearMLCallback._train_run_counter)
+ )
+ if state.is_world_process_zero:
+ logger.info("Automatic ClearML logging enabled.")
+ if self._clearml_task is None:
+ if ClearMLCallback._should_close_on_train_end is None:
+ if not self._clearml.Task.running_locally() or self._clearml.Task.current_task():
+ ClearMLCallback._should_close_on_train_end = False
+ else:
+ ClearMLCallback._should_close_on_train_end = True
+
+ # This might happen when running inside of a pipeline, where the task is already initialized
+ # from outside of Hugging Face
+ if self._clearml.Task.running_locally() and self._clearml.Task.current_task():
+ self._clearml_task = self._clearml.Task.current_task()
+ self._log_model = os.getenv(
+ "CLEARML_LOG_MODEL",
+ "FALSE" if not ClearMLCallback._task_created_in_callback else "TRUE",
+ ).upper() in ENV_VARS_TRUE_VALUES.union({"TRUE"})
+ logger.info("External ClearML Task has been connected.")
+ else:
+ self._clearml_task = self._clearml.Task.init(
+ project_name=os.getenv("CLEARML_PROJECT", "HuggingFace Transformers"),
+ task_name=os.getenv("CLEARML_TASK", "Trainer"),
+ auto_connect_frameworks={"tensorboard": False, "pytorch": False},
+ output_uri=True,
+ )
+ self._log_model = os.getenv("CLEARML_LOG_MODEL", "TRUE").upper() in ENV_VARS_TRUE_VALUES.union(
+ {"TRUE"}
+ )
+ ClearMLCallback._task_created_in_callback = True
+ logger.info("ClearML Task has been initialized.")
+ self._initialized = True
+
+ suffixed_hparams_section = ClearMLCallback._hparams_section + ClearMLCallback.log_suffix
+ ignore_hparams_config_section = suffixed_hparams_section + "/" + ClearMLCallback._ignore_hparams_overrides
+ if self._clearml.Task.running_locally():
+ self._copy_training_args_as_hparams(args, suffixed_hparams_section)
+ self._clearml_task.set_parameter(
+ name=ignore_hparams_config_section,
+ value=True,
+ value_type=bool,
+ description=(
+ "If True, ignore Transformers hyperparameters overrides done in the UI/backend "
+ + "when running remotely. Otherwise, the overrides will be applied when running remotely"
+ ),
+ )
+ elif not self._clearml_task.get_parameter(ignore_hparams_config_section, default=True, cast=True):
+ self._clearml_task.connect(args, suffixed_hparams_section)
+ else:
+ self._copy_training_args_as_hparams(
+ args, ClearMLCallback._hparams_section + ClearMLCallback.log_suffix
+ )
+
+ if getattr(model, "config", None) is not None:
+ ignore_model_config_section = (
+ suffixed_hparams_section + "/" + ClearMLCallback._ignoge_model_config_overrides
+ )
+ configuration_object_description = ClearMLCallback._model_config_description.format(
+ ClearMLCallback._model_connect_counter
+ )
+ if ClearMLCallback._model_connect_counter != ClearMLCallback._train_run_counter:
+ configuration_object_description += " " + ClearMLCallback._model_config_description_note
+ if self._clearml.Task.running_locally():
+ self._clearml_task.set_parameter(
+ name=ignore_model_config_section,
+ value=True,
+ value_type=bool,
+ description=(
+ "If True, ignore Transformers model configuration overrides done in the UI/backend "
+ + "when running remotely. Otherwise, the overrides will be applied when running remotely"
+ ),
+ )
+ self._clearml_task.set_configuration_object(
+ name=ClearMLCallback._model_config_section + ClearMLCallback.log_suffix,
+ config_dict=model.config.to_dict(),
+ description=configuration_object_description,
+ )
+ elif not self._clearml_task.get_parameter(ignore_model_config_section, default=True, cast=True):
+ model.config = model.config.from_dict(
+ self._clearml_task.get_configuration_object_as_dict(
+ ClearMLCallback._model_config_section + ClearMLCallback.log_suffix
+ )
+ )
+ else:
+ self._clearml_task.set_configuration_object(
+ name=ClearMLCallback._model_config_section + ClearMLCallback.log_suffix,
+ config_dict=model.config.to_dict(),
+ description=configuration_object_description,
+ )
+
+ def on_train_begin(self, args, state, control, model=None, processing_class=None, **kwargs):
+ if self._clearml is None:
+ return
+ self._checkpoints_saved = []
+ if state.is_hyper_param_search:
+ self._initialized = False
+ if not self._initialized:
+ self.setup(args, state, model, processing_class, **kwargs)
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if ClearMLCallback._should_close_on_train_end:
+ self._clearml_task.close()
+ ClearMLCallback._train_run_counter = 0
+
+ def on_log(self, args, state, control, model=None, processing_class=None, logs=None, **kwargs):
+ if self._clearml is None:
+ return
+ if not self._initialized:
+ self.setup(args, state, model, processing_class, **kwargs)
+ if state.is_world_process_zero:
+ eval_prefix = "eval_"
+ eval_prefix_len = len(eval_prefix)
+ test_prefix = "test_"
+ test_prefix_len = len(test_prefix)
+ single_value_scalars = [
+ "train_runtime",
+ "train_samples_per_second",
+ "train_steps_per_second",
+ "train_loss",
+ "total_flos",
+ "epoch",
+ ]
+ for k, v in logs.items():
+ if isinstance(v, (int, float)):
+ if k in single_value_scalars:
+ self._clearml_task.get_logger().report_single_value(
+ name=k + ClearMLCallback.log_suffix, value=v
+ )
+ elif k.startswith(eval_prefix):
+ self._clearml_task.get_logger().report_scalar(
+ title="eval" + ClearMLCallback.log_suffix,
+ series=k[eval_prefix_len:],
+ value=v,
+ iteration=state.global_step,
+ )
+ elif k.startswith(test_prefix):
+ self._clearml_task.get_logger().report_scalar(
+ title="test" + ClearMLCallback.log_suffix,
+ series=k[test_prefix_len:],
+ value=v,
+ iteration=state.global_step,
+ )
+ else:
+ self._clearml_task.get_logger().report_scalar(
+ title="train" + ClearMLCallback.log_suffix,
+ series=k,
+ value=v,
+ iteration=state.global_step,
+ )
+ else:
+ logger.warning(
+ "Trainer is attempting to log a value of "
+ f'"{v}" of type {type(v)} for key "{k}" as a scalar. '
+ "This invocation of ClearML logger's report_scalar() "
+ "is incorrect so we dropped this attribute."
+ )
+
+ def on_save(self, args, state, control, **kwargs):
+ if self._log_model and self._clearml_task and state.is_world_process_zero:
+ ckpt_dir = f"checkpoint-{state.global_step}"
+ artifact_path = os.path.join(args.output_dir, ckpt_dir)
+ name = ckpt_dir + ClearMLCallback.log_suffix
+ logger.info(f"Logging checkpoint artifact `{name}`. This may take some time.")
+ output_model = self._clearml.OutputModel(task=self._clearml_task, name=name)
+ output_model.connect(task=self._clearml_task, name=name)
+ output_model.update_weights_package(
+ weights_path=artifact_path,
+ target_filename=ckpt_dir,
+ iteration=state.global_step,
+ auto_delete_file=False,
+ )
+ self._checkpoints_saved.append(output_model)
+ while args.save_total_limit and args.save_total_limit < len(self._checkpoints_saved):
+ try:
+ self._clearml.model.Model.remove(
+ self._checkpoints_saved[0],
+ delete_weights_file=True,
+ force=True,
+ raise_on_errors=True,
+ )
+ except Exception as e:
+ logger.warning(
+ "Could not remove checkpoint `{}` after going over the `save_total_limit`. Error is: {}".format(
+ self._checkpoints_saved[0].name, e
+ )
+ )
+ break
+ self._checkpoints_saved = self._checkpoints_saved[1:]
+
+ def _copy_training_args_as_hparams(self, training_args, prefix):
+ as_dict = {
+ field.name: getattr(training_args, field.name)
+ for field in fields(training_args)
+ if field.init and not field.name.endswith("_token")
+ }
+ flat_dict = {str(k): v for k, v in self._clearml.utilities.proxy_object.flatten_dictionary(as_dict).items()}
+ self._clearml_task._arguments.copy_from_dict(flat_dict, prefix=prefix)
+
+
+class FlyteCallback(TrainerCallback):
+ """A [`TrainerCallback`] that sends the logs to [Flyte](https://flyte.org/).
+ NOTE: This callback only works within a Flyte task.
+
+ Args:
+ save_log_history (`bool`, *optional*, defaults to `True`):
+ When set to True, the training logs are saved as a Flyte Deck.
+
+ sync_checkpoints (`bool`, *optional*, defaults to `True`):
+ When set to True, checkpoints are synced with Flyte and can be used to resume training in the case of an
+ interruption.
+
+ Example:
+
+ ```python
+ # Note: This example skips over some setup steps for brevity.
+ from flytekit import current_context, task
+
+
+ @task
+ def train_hf_transformer():
+ cp = current_context().checkpoint
+ trainer = Trainer(..., callbacks=[FlyteCallback()])
+ output = trainer.train(resume_from_checkpoint=cp.restore())
+ ```
+ """
+
+ def __init__(self, save_log_history: bool = True, sync_checkpoints: bool = True):
+ super().__init__()
+ if not is_flytekit_available():
+ raise ImportError("FlyteCallback requires flytekit to be installed. Run `pip install flytekit`.")
+
+ if not is_flyte_deck_standard_available() or not is_pandas_available():
+ logger.warning(
+ "Syncing log history requires both flytekitplugins-deck-standard and pandas to be installed. "
+ "Run `pip install flytekitplugins-deck-standard pandas` to enable this feature."
+ )
+ save_log_history = False
+
+ from flytekit import current_context
+
+ self.cp = current_context().checkpoint
+ self.save_log_history = save_log_history
+ self.sync_checkpoints = sync_checkpoints
+
+ def on_save(self, args, state, control, **kwargs):
+ if self.sync_checkpoints and state.is_world_process_zero:
+ ckpt_dir = f"checkpoint-{state.global_step}"
+ artifact_path = os.path.join(args.output_dir, ckpt_dir)
+
+ logger.info(f"Syncing checkpoint in {ckpt_dir} to Flyte. This may take time.")
+ self.cp.save(artifact_path)
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if self.save_log_history:
+ import pandas as pd
+ from flytekit import Deck
+ from flytekitplugins.deck.renderer import TableRenderer
+
+ log_history_df = pd.DataFrame(state.log_history)
+ Deck("Log History", TableRenderer().to_html(log_history_df))
+
+
+class DVCLiveCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that sends the logs to [DVCLive](https://www.dvc.org/doc/dvclive).
+
+ Use the environment variables below in `setup` to configure the integration. To customize this callback beyond
+ those environment variables, see [here](https://dvc.org/doc/dvclive/ml-frameworks/huggingface).
+
+ Args:
+ live (`dvclive.Live`, *optional*, defaults to `None`):
+ Optional Live instance. If None, a new instance will be created using **kwargs.
+ log_model (Union[Literal["all"], bool], *optional*, defaults to `None`):
+ Whether to use `dvclive.Live.log_artifact()` to log checkpoints created by [`Trainer`]. If set to `True`,
+ the final checkpoint is logged at the end of training. If set to `"all"`, the entire
+ [`TrainingArguments`]'s `output_dir` is logged at each checkpoint.
+ """
+
+ def __init__(
+ self,
+ live: Optional[Any] = None,
+ log_model: Optional[Union[Literal["all"], bool]] = None,
+ **kwargs,
+ ):
+ if not is_dvclive_available():
+ raise RuntimeError("DVCLiveCallback requires dvclive to be installed. Run `pip install dvclive`.")
+ from dvclive import Live
+
+ self._initialized = False
+ self.live = None
+ if isinstance(live, Live):
+ self.live = live
+ elif live is not None:
+ raise RuntimeError(f"Found class {live.__class__} for live, expected dvclive.Live")
+
+ self._log_model = log_model
+ if self._log_model is None:
+ log_model_env = os.getenv("HF_DVCLIVE_LOG_MODEL", "FALSE")
+ if log_model_env.upper() in ENV_VARS_TRUE_VALUES:
+ self._log_model = True
+ elif log_model_env.lower() == "all":
+ self._log_model = "all"
+
+ def setup(self, args, state, model):
+ """
+ Setup the optional DVCLive integration. To customize this callback beyond the environment variables below, see
+ [here](https://dvc.org/doc/dvclive/ml-frameworks/huggingface).
+
+ Environment:
+ - **HF_DVCLIVE_LOG_MODEL** (`str`, *optional*):
+ Whether to use `dvclive.Live.log_artifact()` to log checkpoints created by [`Trainer`]. If set to `True` or
+ *1*, the final checkpoint is logged at the end of training. If set to `all`, the entire
+ [`TrainingArguments`]'s `output_dir` is logged at each checkpoint.
+ """
+ from dvclive import Live
+
+ self._initialized = True
+ if state.is_world_process_zero:
+ if not self.live:
+ self.live = Live()
+ self.live.log_params(args.to_dict())
+
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
+ if not self._initialized:
+ self.setup(args, state, model)
+
+ def on_log(self, args, state, control, model=None, logs=None, **kwargs):
+ if not self._initialized:
+ self.setup(args, state, model)
+ if state.is_world_process_zero:
+ from dvclive.plots import Metric
+ from dvclive.utils import standardize_metric_name
+
+ for key, value in logs.items():
+ if Metric.could_log(value):
+ self.live.log_metric(standardize_metric_name(key, "dvclive.huggingface"), value)
+ else:
+ logger.warning(
+ "Trainer is attempting to log a value of "
+ f'"{value}" of type {type(value)} for key "{key}" as a scalar. '
+ "This invocation of DVCLive's Live.log_metric() "
+ "is incorrect so we dropped this attribute."
+ )
+ self.live.next_step()
+
+ def on_save(self, args, state, control, **kwargs):
+ if self._log_model == "all" and self._initialized and state.is_world_process_zero:
+ self.live.log_artifact(args.output_dir)
+
+ def on_train_end(self, args, state, control, **kwargs):
+ if self._initialized and state.is_world_process_zero:
+ from transformers.trainer import Trainer
+
+ if self._log_model is True:
+ fake_trainer = Trainer(
+ args=args,
+ model=kwargs.get("model"),
+ processing_class=kwargs.get("processing_class"),
+ eval_dataset=["fake"],
+ )
+ name = "best" if args.load_best_model_at_end else "last"
+ output_dir = os.path.join(args.output_dir, name)
+ fake_trainer.save_model(output_dir)
+ self.live.log_artifact(output_dir, name=name, type="model", copy=True)
+ self.live.end()
+
+
+class SwanLabCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that logs metrics, media, model checkpoints to [SwanLab](https://swanlab.cn/).
+ """
+
+ def __init__(self):
+ if not is_swanlab_available():
+ raise RuntimeError("SwanLabCallback requires swanlab to be installed. Run `pip install swanlab`.")
+ import swanlab
+
+ self._swanlab = swanlab
+ self._initialized = False
+ self._log_model = os.getenv("SWANLAB_LOG_MODEL", None)
+
+ def setup(self, args, state, model, **kwargs):
+ """
+ Setup the optional SwanLab (*swanlab*) integration.
+
+ One can subclass and override this method to customize the setup if needed. Find more information
+ [here](https://docs.swanlab.cn/guide_cloud/integration/integration-huggingface-transformers.html).
+
+ You can also override the following environment variables. Find more information about environment
+ variables [here](https://docs.swanlab.cn/en/api/environment-variable.html#environment-variables)
+
+ Environment:
+ - **SWANLAB_API_KEY** (`str`, *optional*, defaults to `None`):
+ Cloud API Key. During login, this environment variable is checked first. If it doesn't exist, the system
+ checks if the user is already logged in. If not, the login process is initiated.
+
+ - If a string is passed to the login interface, this environment variable is ignored.
+ - If the user is already logged in, this environment variable takes precedence over locally stored
+ login information.
+
+ - **SWANLAB_PROJECT** (`str`, *optional*, defaults to `None`):
+ Set this to a custom string to store results in a different project. If not specified, the name of the current
+ running directory is used.
+
+ - **SWANLAB_LOG_DIR** (`str`, *optional*, defaults to `swanlog`):
+ This environment variable specifies the storage path for log files when running in local mode.
+ By default, logs are saved in a folder named swanlog under the working directory.
+
+ - **SWANLAB_MODE** (`Literal["local", "cloud", "disabled"]`, *optional*, defaults to `cloud`):
+ SwanLab's parsing mode, which involves callbacks registered by the operator. Currently, there are three modes:
+ local, cloud, and disabled. Note: Case-sensitive. Find more information
+ [here](https://docs.swanlab.cn/en/api/py-init.html#swanlab-init)
+
+ - **SWANLAB_LOG_MODEL** (`str`, *optional*, defaults to `None`):
+ SwanLab does not currently support the save mode functionality.This feature will be available in a future
+ release
+
+ - **SWANLAB_WEB_HOST** (`str`, *optional*, defaults to `None`):
+ Web address for the SwanLab cloud environment for private version (its free)
+
+ - **SWANLAB_API_HOST** (`str`, *optional*, defaults to `None`):
+ API address for the SwanLab cloud environment for private version (its free)
+
+ """
+ self._initialized = True
+
+ if state.is_world_process_zero:
+ logger.info('Automatic SwanLab logging enabled, to disable set os.environ["SWANLAB_MODE"] = "disabled"')
+ combined_dict = {**args.to_dict()}
+
+ if hasattr(model, "config") and model.config is not None:
+ model_config = model.config if isinstance(model.config, dict) else model.config.to_dict()
+ combined_dict = {**model_config, **combined_dict}
+ if hasattr(model, "peft_config") and model.peft_config is not None:
+ peft_config = model.peft_config
+ combined_dict = {**{"peft_config": peft_config}, **combined_dict}
+ trial_name = state.trial_name
+ init_args = {}
+ if trial_name is not None:
+ init_args["experiment_name"] = f"{args.run_name}-{trial_name}"
+ elif args.run_name is not None:
+ init_args["experiment_name"] = args.run_name
+ init_args["project"] = os.getenv("SWANLAB_PROJECT", None)
+
+ if self._swanlab.get_run() is None:
+ self._swanlab.init(
+ **init_args,
+ )
+ # show transformers logo!
+ self._swanlab.config["FRAMEWORK"] = "🤗transformers"
+ # add config parameters (run may have been created manually)
+ self._swanlab.config.update(combined_dict)
+
+ # add number of model parameters to swanlab config
+ try:
+ self._swanlab.config.update({"model_num_parameters": model.num_parameters()})
+ # get peft model parameters
+ if type(model).__name__ == "PeftModel" or type(model).__name__ == "PeftMixedModel":
+ trainable_params, all_param = model.get_nb_trainable_parameters()
+ self._swanlab.config.update({"peft_model_trainable_params": trainable_params})
+ self._swanlab.config.update({"peft_model_all_param": all_param})
+ except AttributeError:
+ logger.info("Could not log the number of model parameters in SwanLab due to an AttributeError.")
+
+ # log the initial model architecture to an artifact
+ if self._log_model is not None:
+ logger.warning(
+ "SwanLab does not currently support the save mode functionality. "
+ "This feature will be available in a future release."
+ )
+ badge_markdown = (
+ f'[
]({self._swanlab.get_run().public.cloud.exp_url})'
+ )
+
+ modelcard.AUTOGENERATED_TRAINER_COMMENT += f"\n{badge_markdown}"
+
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
+ if not self._initialized:
+ self.setup(args, state, model, **kwargs)
+
+ def on_train_end(self, args, state, control, model=None, processing_class=None, **kwargs):
+ if self._log_model is not None and self._initialized and state.is_world_process_zero:
+ logger.warning(
+ "SwanLab does not currently support the save mode functionality. "
+ "This feature will be available in a future release."
+ )
+
+ def on_log(self, args, state, control, model=None, logs=None, **kwargs):
+ single_value_scalars = [
+ "train_runtime",
+ "train_samples_per_second",
+ "train_steps_per_second",
+ "train_loss",
+ "total_flos",
+ ]
+
+ if not self._initialized:
+ self.setup(args, state, model)
+ if state.is_world_process_zero:
+ for k, v in logs.items():
+ if k in single_value_scalars:
+ self._swanlab.log({f"single_value/{k}": v})
+ non_scalar_logs = {k: v for k, v in logs.items() if k not in single_value_scalars}
+ non_scalar_logs = rewrite_logs(non_scalar_logs)
+ self._swanlab.log({**non_scalar_logs, "train/global_step": state.global_step})
+
+ def on_save(self, args, state, control, **kwargs):
+ if self._log_model is not None and self._initialized and state.is_world_process_zero:
+ logger.warning(
+ "SwanLab does not currently support the save mode functionality. "
+ "This feature will be available in a future release."
+ )
+
+ def on_predict(self, args, state, control, metrics, **kwargs):
+ if not self._initialized:
+ self.setup(args, state, **kwargs)
+ if state.is_world_process_zero:
+ metrics = rewrite_logs(metrics)
+ self._swanlab.log(metrics)
+
+
+INTEGRATION_TO_CALLBACK = {
+ "azure_ml": AzureMLCallback,
+ "comet_ml": CometCallback,
+ "mlflow": MLflowCallback,
+ "neptune": NeptuneCallback,
+ "tensorboard": TensorBoardCallback,
+ "wandb": WandbCallback,
+ "codecarbon": CodeCarbonCallback,
+ "clearml": ClearMLCallback,
+ "dagshub": DagsHubCallback,
+ "flyte": FlyteCallback,
+ "dvclive": DVCLiveCallback,
+ "swanlab": SwanLabCallback,
+}
+
+
+def get_reporting_integration_callbacks(report_to):
+ if report_to is None:
+ return []
+
+ if isinstance(report_to, str):
+ if "none" == report_to:
+ return []
+ elif "all" == report_to:
+ report_to = get_available_reporting_integrations()
+ else:
+ report_to = [report_to]
+
+ for integration in report_to:
+ if integration not in INTEGRATION_TO_CALLBACK:
+ raise ValueError(
+ f"{integration} is not supported, only {', '.join(INTEGRATION_TO_CALLBACK.keys())} are supported."
+ )
+
+ return [INTEGRATION_TO_CALLBACK[integration] for integration in report_to]
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/mistral.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/mistral.py
new file mode 100644
index 0000000000000000000000000000000000000000..78172329277e4f5ac0b01795a123bdebe7bd8f51
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/mistral.py
@@ -0,0 +1,105 @@
+from tokenizers import Regex, Tokenizer, decoders, pre_tokenizers, processors
+from tokenizers.models import BPE
+
+from transformers import LlamaTokenizerFast
+from transformers.convert_slow_tokenizer import bytes_to_unicode
+
+
+class MistralConverter:
+ """
+ A general tiktoken converter.
+ """
+
+ def __init__(
+ self,
+ vocab=None,
+ pattern=r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+""",
+ add_prefix_space=False,
+ additional_special_tokens=None,
+ *args,
+ **kwargs,
+ ):
+ super().__init__(*args)
+ self.vocab = vocab
+ self.pattern = pattern
+ self.add_prefix_space = add_prefix_space
+ self.additional_special_tokens = additional_special_tokens
+
+ def extract_vocab_merges_from_model(self, vocab: str):
+ bpe_ranks = vocab
+ byte_encoder = bytes_to_unicode()
+
+ def token_bytes_to_string(b):
+ return "".join([byte_encoder[ord(char)] for char in b.decode("latin-1")])
+
+ merges = []
+ vocab = {}
+ for idx, (token, rank) in enumerate(bpe_ranks.items()):
+ if token not in self.additional_special_tokens:
+ vocab[token_bytes_to_string(token)] = idx
+ if len(token) == 1:
+ continue
+ local = []
+ for index in range(1, len(token)):
+ piece_l, piece_r = token[:index], token[index:]
+ if piece_l in bpe_ranks and piece_r in bpe_ranks and (piece_l + piece_r) in bpe_ranks:
+ local.append((piece_l, piece_r, rank))
+ local = sorted(local, key=lambda x: (bpe_ranks[x[0]], bpe_ranks[x[1]]), reverse=False)
+ merges.extend(local)
+ else:
+ vocab[token] = idx
+ merges = sorted(merges, key=lambda val: val[2], reverse=False)
+ merges = [(token_bytes_to_string(val[0]), token_bytes_to_string(val[1])) for val in merges]
+ return vocab, merges
+
+ def tokenizer(self):
+ vocab_scores, merges = self.extract_vocab_merges_from_model(self.vocab)
+ tokenizer = Tokenizer(BPE(vocab_scores, merges, fuse_unk=False))
+ if hasattr(tokenizer.model, "ignore_merges"):
+ tokenizer.model.ignore_merges = True
+ return tokenizer
+
+ def converted(self) -> Tokenizer:
+ tokenizer = self.tokenizer()
+ tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
+ [
+ pre_tokenizers.Split(Regex(self.pattern), behavior="isolated", invert=False),
+ pre_tokenizers.ByteLevel(add_prefix_space=self.add_prefix_space, use_regex=False),
+ ]
+ )
+ tokenizer.decoder = decoders.ByteLevel()
+ tokenizer.add_special_tokens(self.additional_special_tokens)
+
+ tokenizer.post_processor = processors.ByteLevel(trim_offsets=False)
+
+ return tokenizer
+
+
+def convert_tekken_tokenizer(tokenizer_file: str):
+ """Convert a "tekken" tokenizer to a fast Tokenizer."""
+ # Tekken format -- need to use the Converter
+
+ from mistral_common.tokens.tokenizers.mistral import MistralTokenizer
+
+ # Load directly using their lib
+ mistral_tokenizer = MistralTokenizer.from_file(tokenizer_file)
+
+ # Extract vocab and special tokens
+ vocab = mistral_tokenizer.instruct_tokenizer.tokenizer._tekken_token2id_nospecial
+ all_special = [
+ token.value if hasattr(token, "value") else token
+ for token in mistral_tokenizer.instruct_tokenizer.tokenizer._all_special_tokens
+ ]
+ specials_tokens = {token: all_special.index(token) for token in all_special}
+ specials_tokens.update(vocab)
+ vocab = specials_tokens
+
+ # Convert
+ tokenizer = LlamaTokenizerFast(
+ tokenizer_object=MistralConverter(vocab=vocab, additional_special_tokens=all_special).converted(),
+ )
+
+ # Post-process
+ tokenizer.add_special_tokens({"additional_special_tokens": all_special})
+
+ return tokenizer
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/peft.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/peft.py
new file mode 100644
index 0000000000000000000000000000000000000000..791528a629acf431264634cfc7ae351604377388
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/peft.py
@@ -0,0 +1,589 @@
+# 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 inspect
+import warnings
+from typing import Any, Dict, List, Optional, Union
+
+from packaging import version
+
+from ..utils import (
+ check_peft_version,
+ find_adapter_config_file,
+ is_accelerate_available,
+ is_peft_available,
+ is_torch_available,
+ logging,
+)
+
+
+if is_torch_available():
+ import torch
+
+if is_accelerate_available():
+ from accelerate import dispatch_model
+ from accelerate.utils import get_balanced_memory, infer_auto_device_map
+
+# Minimum PEFT version supported for the integration
+MIN_PEFT_VERSION = "0.5.0"
+
+
+logger = logging.get_logger(__name__)
+
+
+class PeftAdapterMixin:
+ """
+ A class containing all functions for loading and using adapters weights that are supported in PEFT library. For
+ more details about adapters and injecting them on a transformer-based model, check out the documentation of PEFT
+ library: https://huggingface.co/docs/peft/index
+
+ Currently supported PEFT methods are all non-prefix tuning methods. Below is the list of supported PEFT methods
+ that anyone can load, train and run with this mixin class:
+ - Low Rank Adapters (LoRA): https://huggingface.co/docs/peft/conceptual_guides/lora
+ - IA3: https://huggingface.co/docs/peft/conceptual_guides/ia3
+ - AdaLora: https://arxiv.org/abs/2303.10512
+
+ Other PEFT models such as prompt tuning, prompt learning are out of scope as these adapters are not "injectable"
+ into a torch module. For using these methods, please refer to the usage guide of PEFT library.
+
+ With this mixin, if the correct PEFT version is installed, it is possible to:
+
+ - Load an adapter stored on a local path or in a remote Hub repository, and inject it in the model
+ - Attach new adapters in the model and train them with Trainer or by your own.
+ - Attach multiple adapters and iteratively activate / deactivate them
+ - Activate / deactivate all adapters from the model.
+ - Get the `state_dict` of the active adapter.
+ """
+
+ _hf_peft_config_loaded = False
+
+ def load_adapter(
+ self,
+ peft_model_id: Optional[str] = None,
+ adapter_name: Optional[str] = None,
+ revision: Optional[str] = None,
+ token: Optional[str] = None,
+ device_map: Optional[str] = "auto",
+ max_memory: Optional[str] = None,
+ offload_folder: Optional[str] = None,
+ offload_index: Optional[int] = None,
+ peft_config: Dict[str, Any] = None,
+ adapter_state_dict: Optional[Dict[str, "torch.Tensor"]] = None,
+ low_cpu_mem_usage: bool = False,
+ is_trainable: bool = False,
+ adapter_kwargs: Optional[Dict[str, Any]] = None,
+ ) -> None:
+ """
+ Load adapter weights from file or remote Hub folder. If you are not familiar with adapters and PEFT methods, we
+ invite you to read more about them on PEFT official documentation: https://huggingface.co/docs/peft
+
+ Requires peft as a backend to load the adapter weights.
+
+ Args:
+ peft_model_id (`str`, *optional*):
+ The identifier of the model to look for on the Hub, or a local path to the saved adapter config file
+ and adapter weights.
+ adapter_name (`str`, *optional*):
+ The adapter name to use. If not set, will use the default adapter.
+ 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/"`.
+
+
+
+ token (`str`, `optional`):
+ Whether to use authentication token to load the remote folder. Useful to load private repositories
+ that are on HuggingFace Hub. You might need to call `huggingface-cli login` and paste your tokens to
+ cache it.
+ device_map (`str` or `Dict[str, Union[int, str, torch.device]]` or `int` or `torch.device`, *optional*):
+ A map that specifies where each submodule should go. It doesn't need to be refined to each
+ parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
+ same device. If we only pass the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank
+ like `1`) on which the model will be allocated, the device map will map the entire model to this
+ device. Passing `device_map = 0` means put the whole model on GPU 0.
+
+ To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
+ more information about each option see [designing a device
+ map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
+ max_memory (`Dict`, *optional*):
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available for each
+ GPU and the available CPU RAM if unset.
+ offload_folder (`str` or `os.PathLike`, `optional`):
+ If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
+ offload_index (`int`, `optional`):
+ `offload_index` argument to be passed to `accelerate.dispatch_model` method.
+ peft_config (`Dict[str, Any]`, *optional*):
+ The configuration of the adapter to add, supported adapters are non-prefix tuning and adaption prompts
+ methods. This argument is used in case users directly pass PEFT state dicts
+ adapter_state_dict (`Dict[str, torch.Tensor]`, *optional*):
+ The state dict of the adapter to load. This argument is used in case users directly pass PEFT state
+ dicts
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `False`):
+ Reduce memory usage while loading the PEFT adapter. This should also speed up the loading process.
+ Requires PEFT version 0.13.0 or higher.
+ is_trainable (`bool`, *optional*, defaults to `False`):
+ Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and can only be
+ used for inference.
+ adapter_kwargs (`Dict[str, Any]`, *optional*):
+ Additional keyword arguments passed along to the `from_pretrained` method of the adapter config and
+ `find_adapter_config_file` method.
+ """
+ check_peft_version(min_version=MIN_PEFT_VERSION)
+
+ # peft only supports low_cpu_mem_usage starting from v0.13.0
+ peft_load_kwargs = {}
+ if low_cpu_mem_usage:
+ min_version_lcmu = "0.13.0"
+ if version.parse(importlib.metadata.version("peft")) >= version.parse(min_version_lcmu):
+ peft_load_kwargs["low_cpu_mem_usage"] = low_cpu_mem_usage
+ else:
+ raise ValueError(
+ "The version of PEFT you are using does not support `low_cpu_mem_usage` yet, "
+ f"please install PEFT >= {min_version_lcmu}."
+ )
+
+ adapter_name = adapter_name if adapter_name is not None else "default"
+ if adapter_kwargs is None:
+ adapter_kwargs = {}
+
+ from peft import PeftConfig, inject_adapter_in_model, load_peft_weights
+ from peft.utils import set_peft_model_state_dict
+
+ if self._hf_peft_config_loaded and adapter_name in self.peft_config:
+ raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")
+
+ if peft_model_id is None and (adapter_state_dict is None and peft_config is None):
+ raise ValueError(
+ "You should either pass a `peft_model_id` or a `peft_config` and `adapter_state_dict` to load an adapter."
+ )
+
+ if "device" not in adapter_kwargs:
+ device = self.device if not hasattr(self, "hf_device_map") else list(self.hf_device_map.values())[0]
+ else:
+ device = adapter_kwargs.pop("device")
+
+ # To avoid PEFT errors later on with safetensors.
+ if isinstance(device, torch.device):
+ device = str(device)
+
+ # We keep `revision` in the signature for backward compatibility
+ if revision is not None and "revision" not in adapter_kwargs:
+ adapter_kwargs["revision"] = revision
+ elif revision is not None and "revision" in adapter_kwargs and revision != adapter_kwargs["revision"]:
+ logger.error(
+ "You passed a `revision` argument both in `adapter_kwargs` and as a standalone argument. "
+ "The one in `adapter_kwargs` will be used."
+ )
+
+ # Override token with adapter_kwargs' token
+ if "token" in adapter_kwargs:
+ token = adapter_kwargs.pop("token")
+
+ if peft_config is None:
+ adapter_config_file = find_adapter_config_file(
+ peft_model_id,
+ token=token,
+ **adapter_kwargs,
+ )
+
+ if adapter_config_file is None:
+ raise ValueError(
+ f"adapter model file not found in {peft_model_id}. Make sure you are passing the correct path to the "
+ "adapter model."
+ )
+
+ peft_config = PeftConfig.from_pretrained(
+ peft_model_id,
+ token=token,
+ **adapter_kwargs,
+ )
+ peft_config.inference_mode = not is_trainable
+
+ # Create and add fresh new adapters into the model.
+ inject_adapter_in_model(peft_config, self, adapter_name, **peft_load_kwargs)
+
+ if not self._hf_peft_config_loaded:
+ self._hf_peft_config_loaded = True
+
+ if peft_model_id is not None:
+ adapter_state_dict = load_peft_weights(peft_model_id, token=token, device=device, **adapter_kwargs)
+
+ # We need to pre-process the state dict to remove unneeded prefixes - for backward compatibility
+ processed_adapter_state_dict = {}
+ prefix = "base_model.model."
+ for key, value in adapter_state_dict.items():
+ if key.startswith(prefix):
+ new_key = key[len(prefix) :]
+ else:
+ new_key = key
+ processed_adapter_state_dict[new_key] = value
+
+ # Load state dict
+ incompatible_keys = set_peft_model_state_dict(
+ self, processed_adapter_state_dict, adapter_name, **peft_load_kwargs
+ )
+
+ if incompatible_keys is not None:
+ err_msg = ""
+ origin_name = peft_model_id if peft_model_id is not None else "state_dict"
+ # Check for unexpected keys.
+ if hasattr(incompatible_keys, "unexpected_keys") and len(incompatible_keys.unexpected_keys) > 0:
+ err_msg = (
+ f"Loading adapter weights from {origin_name} led to unexpected keys not found in the model: "
+ f"{', '.join(incompatible_keys.unexpected_keys)}. "
+ )
+
+ # Check for missing keys.
+ missing_keys = getattr(incompatible_keys, "missing_keys", None)
+ if missing_keys:
+ # Filter missing keys specific to the current adapter, as missing base model keys are expected.
+ lora_missing_keys = [k for k in missing_keys if "lora_" in k and adapter_name in k]
+ if lora_missing_keys:
+ err_msg += (
+ f"Loading adapter weights from {origin_name} led to missing keys in the model: "
+ f"{', '.join(lora_missing_keys)}"
+ )
+
+ if err_msg:
+ logger.warning(err_msg)
+
+ if peft_config.inference_mode:
+ self.eval()
+
+ # Re-dispatch model and hooks in case the model is offloaded to CPU / Disk.
+ if (
+ (getattr(self, "hf_device_map", None) is not None)
+ and (len(set(self.hf_device_map.values()).intersection({"cpu", "disk"})) > 0)
+ and len(self.peft_config) == 1
+ ):
+ self._dispatch_accelerate_model(
+ device_map=device_map,
+ max_memory=max_memory,
+ offload_folder=offload_folder,
+ offload_index=offload_index,
+ )
+
+ def add_adapter(self, adapter_config, adapter_name: Optional[str] = None) -> None:
+ r"""
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
+ official documentation: https://huggingface.co/docs/peft
+
+ Adds a fresh new adapter to the current model for training purpose. If no adapter name is passed, a default
+ name is assigned to the adapter to follow the convention of PEFT library (in PEFT we use "default" as the
+ default adapter name).
+
+ Args:
+ adapter_config (`~peft.PeftConfig`):
+ The configuration of the adapter to add, supported adapters are non-prefix tuning and adaption prompts
+ methods
+ adapter_name (`str`, *optional*, defaults to `"default"`):
+ The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.
+ """
+ check_peft_version(min_version=MIN_PEFT_VERSION)
+
+ from peft import PeftConfig, inject_adapter_in_model
+
+ adapter_name = adapter_name or "default"
+
+ if not self._hf_peft_config_loaded:
+ self._hf_peft_config_loaded = True
+ elif adapter_name in self.peft_config:
+ raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")
+
+ if not isinstance(adapter_config, PeftConfig):
+ raise TypeError(f"adapter_config should be an instance of PeftConfig. Got {type(adapter_config)} instead.")
+
+ # Retrieve the name or path of the model, one could also use self.config._name_or_path
+ # but to be consistent with what we do in PEFT: https://github.com/huggingface/peft/blob/6e783780ca9df3a623992cc4d1d665001232eae0/src/peft/mapping.py#L100
+ adapter_config.base_model_name_or_path = self.__dict__.get("name_or_path", None)
+ inject_adapter_in_model(adapter_config, self, adapter_name)
+
+ self.set_adapter(adapter_name)
+
+ def set_adapter(self, adapter_name: Union[List[str], str]) -> None:
+ """
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
+ official documentation: https://huggingface.co/docs/peft
+
+ Sets a specific adapter by forcing the model to use a that adapter and disable the other adapters.
+
+ Args:
+ adapter_name (`Union[List[str], str]`):
+ The name of the adapter to set. Can be also a list of strings to set multiple adapters.
+ """
+ check_peft_version(min_version=MIN_PEFT_VERSION)
+ if not self._hf_peft_config_loaded:
+ raise ValueError("No adapter loaded. Please load an adapter first.")
+ elif isinstance(adapter_name, list):
+ missing = set(adapter_name) - set(self.peft_config)
+ if len(missing) > 0:
+ raise ValueError(
+ f"Following adapter(s) could not be found: {', '.join(missing)}. Make sure you are passing the correct adapter name(s)."
+ f" current loaded adapters are: {list(self.peft_config.keys())}"
+ )
+ elif adapter_name not in self.peft_config:
+ raise ValueError(
+ f"Adapter with name {adapter_name} not found. Please pass the correct adapter name among {list(self.peft_config.keys())}"
+ )
+
+ from peft.tuners.tuners_utils import BaseTunerLayer
+ from peft.utils import ModulesToSaveWrapper
+
+ _adapters_has_been_set = False
+
+ for _, module in self.named_modules():
+ if isinstance(module, (BaseTunerLayer, ModulesToSaveWrapper)):
+ # For backward compatbility with previous PEFT versions
+ if hasattr(module, "set_adapter"):
+ module.set_adapter(adapter_name)
+ else:
+ module.active_adapter = adapter_name
+ _adapters_has_been_set = True
+
+ if not _adapters_has_been_set:
+ raise ValueError(
+ "Did not succeeded in setting the adapter. Please make sure you are using a model that supports adapters."
+ )
+
+ def disable_adapters(self) -> None:
+ r"""
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
+ official documentation: https://huggingface.co/docs/peft
+
+ Disable all adapters that are attached to the model. This leads to inferring with the base model only.
+ """
+ check_peft_version(min_version=MIN_PEFT_VERSION)
+
+ if not self._hf_peft_config_loaded:
+ raise ValueError("No adapter loaded. Please load an adapter first.")
+
+ from peft.tuners.tuners_utils import BaseTunerLayer
+ from peft.utils import ModulesToSaveWrapper
+
+ for _, module in self.named_modules():
+ if isinstance(module, (BaseTunerLayer, ModulesToSaveWrapper)):
+ # The recent version of PEFT need to call `enable_adapters` instead
+ if hasattr(module, "enable_adapters"):
+ module.enable_adapters(enabled=False)
+ else:
+ module.disable_adapters = True
+
+ def enable_adapters(self) -> None:
+ """
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
+ official documentation: https://huggingface.co/docs/peft
+
+ Enable adapters that are attached to the model.
+ """
+ check_peft_version(min_version=MIN_PEFT_VERSION)
+
+ if not self._hf_peft_config_loaded:
+ raise ValueError("No adapter loaded. Please load an adapter first.")
+
+ from peft.tuners.tuners_utils import BaseTunerLayer
+
+ for _, module in self.named_modules():
+ if isinstance(module, BaseTunerLayer):
+ # The recent version of PEFT need to call `enable_adapters` instead
+ if hasattr(module, "enable_adapters"):
+ module.enable_adapters(enabled=True)
+ else:
+ module.disable_adapters = False
+
+ def active_adapters(self) -> List[str]:
+ """
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
+ official documentation: https://huggingface.co/docs/peft
+
+ Gets the current active adapters of the model. In case of multi-adapter inference (combining multiple adapters
+ for inference) returns the list of all active adapters so that users can deal with them accordingly.
+
+ For previous PEFT versions (that does not support multi-adapter inference), `module.active_adapter` will return
+ a single string.
+ """
+ check_peft_version(min_version=MIN_PEFT_VERSION)
+
+ if not is_peft_available():
+ raise ImportError("PEFT is not available. Please install PEFT to use this function: `pip install peft`.")
+
+ if not self._hf_peft_config_loaded:
+ raise ValueError("No adapter loaded. Please load an adapter first.")
+
+ from peft.tuners.tuners_utils import BaseTunerLayer
+
+ for _, module in self.named_modules():
+ if isinstance(module, BaseTunerLayer):
+ active_adapters = module.active_adapter
+ break
+
+ # For previous PEFT versions
+ if isinstance(active_adapters, str):
+ active_adapters = [active_adapters]
+
+ return active_adapters
+
+ def active_adapter(self) -> str:
+ warnings.warn(
+ "The `active_adapter` method is deprecated and will be removed in a future version.", FutureWarning
+ )
+
+ return self.active_adapters()[0]
+
+ def get_adapter_state_dict(self, adapter_name: Optional[str] = None) -> dict:
+ """
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
+ official documentation: https://huggingface.co/docs/peft
+
+ Gets the adapter state dict that should only contain the weights tensors of the specified adapter_name adapter.
+ If no adapter_name is passed, the active adapter is used.
+
+ Args:
+ adapter_name (`str`, *optional*):
+ The name of the adapter to get the state dict from. If no name is passed, the active adapter is used.
+ """
+ check_peft_version(min_version=MIN_PEFT_VERSION)
+
+ if not self._hf_peft_config_loaded:
+ raise ValueError("No adapter loaded. Please load an adapter first.")
+
+ from peft import get_peft_model_state_dict
+
+ if adapter_name is None:
+ adapter_name = self.active_adapters()[0]
+
+ adapter_state_dict = get_peft_model_state_dict(self, adapter_name=adapter_name)
+ return adapter_state_dict
+
+ def _dispatch_accelerate_model(
+ self,
+ device_map: str,
+ max_memory: Optional[int] = None,
+ offload_folder: Optional[str] = None,
+ offload_index: Optional[int] = None,
+ ) -> None:
+ """
+ Optional re-dispatch the model and attach new hooks to the model in case the model has been loaded with
+ accelerate (i.e. with `device_map=xxx`)
+
+ Args:
+ device_map (`str` or `Dict[str, Union[int, str, torch.device]]` or `int` or `torch.device`, *optional*):
+ A map that specifies where each submodule should go. It doesn't need to be refined to each
+ parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
+ same device. If we only pass the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank
+ like `1`) on which the model will be allocated, the device map will map the entire model to this
+ device. Passing `device_map = 0` means put the whole model on GPU 0.
+
+ To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
+ more information about each option see [designing a device
+ map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
+ max_memory (`Dict`, *optional*):
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available for each
+ GPU and the available CPU RAM if unset.
+ offload_folder (`str` or `os.PathLike`, *optional*):
+ If the `device_map` contains any value `"disk"`, the folder where we will offload weights.
+ offload_index (`int`, *optional*):
+ The offload_index argument to be passed to `accelerate.dispatch_model` method.
+ """
+ dispatch_model_kwargs = {}
+ # Safety checker for previous `accelerate` versions
+ # `offload_index` was introduced in https://github.com/huggingface/accelerate/pull/873/
+ if "offload_index" in inspect.signature(dispatch_model).parameters:
+ dispatch_model_kwargs["offload_index"] = offload_index
+
+ no_split_module_classes = self._no_split_modules
+
+ if device_map != "sequential":
+ max_memory = get_balanced_memory(
+ self,
+ max_memory=max_memory,
+ no_split_module_classes=no_split_module_classes,
+ low_zero=(device_map == "balanced_low_0"),
+ )
+ if isinstance(device_map, str):
+ device_map = infer_auto_device_map(
+ self, max_memory=max_memory, no_split_module_classes=no_split_module_classes
+ )
+ dispatch_model(
+ self,
+ device_map=device_map,
+ offload_dir=offload_folder,
+ **dispatch_model_kwargs,
+ )
+
+ def delete_adapter(self, adapter_names: Union[List[str], str]) -> None:
+ """
+ Delete an adapter's LoRA layers from the underlying model.
+
+ Args:
+ adapter_names (`Union[List[str], str]`):
+ The name(s) of the adapter(s) to delete.
+
+ Example:
+
+ ```py
+ from diffusers import AutoPipelineForText2Image
+ import torch
+
+ pipeline = AutoPipelineForText2Image.from_pretrained(
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
+ ).to("cuda")
+ pipeline.load_lora_weights(
+ "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_names="cinematic"
+ )
+ pipeline.delete_adapters("cinematic")
+ ```
+ """
+
+ check_peft_version(min_version=MIN_PEFT_VERSION)
+
+ if not self._hf_peft_config_loaded:
+ raise ValueError("No adapter loaded. Please load an adapter first.")
+
+ from peft.tuners.tuners_utils import BaseTunerLayer
+
+ if isinstance(adapter_names, str):
+ adapter_names = [adapter_names]
+
+ # Check that all adapter names are present in the config
+ missing_adapters = [name for name in adapter_names if name not in self.peft_config]
+ if missing_adapters:
+ raise ValueError(
+ f"The following adapter(s) are not present and cannot be deleted: {', '.join(missing_adapters)}"
+ )
+
+ for adapter_name in adapter_names:
+ for module in self.modules():
+ if isinstance(module, BaseTunerLayer):
+ if hasattr(module, "delete_adapter"):
+ module.delete_adapter(adapter_name)
+ else:
+ raise ValueError(
+ "The version of PEFT you are using is not compatible, please use a version that is greater than 0.6.1"
+ )
+
+ # For transformers integration - we need to pop the adapter from the config
+ if getattr(self, "_hf_peft_config_loaded", False) and hasattr(self, "peft_config"):
+ self.peft_config.pop(adapter_name, None)
+
+ # In case all adapters are deleted, we need to delete the config
+ # and make sure to set the flag to False
+ if len(self.peft_config) == 0:
+ del self.peft_config
+ self._hf_peft_config_loaded = False
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/quanto.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/quanto.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c5702321937da5f1238427156452cbccdbcea4a
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/quanto.py
@@ -0,0 +1,98 @@
+# 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.
+
+from ..utils import is_optimum_quanto_available, is_torch_available, logging
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+def replace_with_quanto_layers(
+ model,
+ quantization_config=None,
+ modules_to_not_convert=None,
+ current_key_name=None,
+ has_been_replaced=False,
+):
+ """
+ Public method that recursively replaces the Linear layers of the given model with Quanto quantized layers.
+ Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to convert, can be any `torch.nn.Module` instance.
+ quantization_config (`AqlmConfig`, defaults to `None`):
+ The quantization config object that contains the quantization parameters.
+ modules_to_not_convert (`list`, *optional*, defaults to `None`):
+ A list of modules to not convert. If a module name is in the list (e.g. `lm_head`), it will not be
+ converted.
+ current_key_name (`list`, *optional*, defaults to `None`):
+ A list that contains the current key name. This is used for recursion and should not be passed by the user.
+ has_been_replaced (`bool`, *optional*, defaults to `None`):
+ A boolean that indicates if the conversion has been successful or not. This is used for recursion and
+ should not be passed by the user.
+ """
+ from accelerate import init_empty_weights
+
+ if is_optimum_quanto_available():
+ from optimum.quanto import QLayerNorm, QLinear, qfloat8, qint2, qint4, qint8
+
+ w_mapping = {"float8": qfloat8, "int8": qint8, "int4": qint4, "int2": qint2}
+ a_mapping = {None: None, "float8": qfloat8, "int8": qint8}
+
+ if modules_to_not_convert is None:
+ modules_to_not_convert = []
+
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if not any(key in ".".join(current_key_name) for key in modules_to_not_convert):
+ with init_empty_weights():
+ if isinstance(module, torch.nn.Linear):
+ model._modules[name] = QLinear(
+ in_features=module.in_features,
+ out_features=module.out_features,
+ bias=module.bias is not None,
+ dtype=module.weight.dtype,
+ weights=w_mapping[quantization_config.weights],
+ activations=a_mapping[quantization_config.activations],
+ )
+ model._modules[name].requires_grad_(False)
+ has_been_replaced = True
+ elif isinstance(module, torch.nn.LayerNorm):
+ if quantization_config.activations is not None:
+ model._modules[name] = QLayerNorm(
+ module.normalized_shape,
+ module.eps,
+ module.elementwise_affine,
+ module.bias is not None,
+ activations=a_mapping[quantization_config.activations],
+ )
+ has_been_replaced = True
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = replace_with_quanto_layers(
+ module,
+ quantization_config=quantization_config,
+ modules_to_not_convert=modules_to_not_convert,
+ current_key_name=current_key_name,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/sdpa_attention.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/sdpa_attention.py
new file mode 100644
index 0000000000000000000000000000000000000000..890832a26e9d8ce6e49696b291d0833c596a7401
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/sdpa_attention.py
@@ -0,0 +1,65 @@
+from typing import Optional, Tuple
+
+import torch
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def sdpa_attention_forward(
+ module: torch.nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: Optional[torch.Tensor],
+ dropout: float = 0.0,
+ scaling: Optional[float] = None,
+ is_causal: Optional[bool] = None,
+ **kwargs,
+) -> Tuple[torch.Tensor, None]:
+ if hasattr(module, "num_key_value_groups"):
+ key = repeat_kv(key, module.num_key_value_groups)
+ value = repeat_kv(value, module.num_key_value_groups)
+
+ causal_mask = attention_mask
+ if attention_mask is not None:
+ causal_mask = causal_mask[:, :, :, : key.shape[-2]]
+
+ # SDPA with memory-efficient backend is bugged with non-contiguous inputs and custom attn_mask for some torch versions
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
+ query = query.contiguous()
+ key = key.contiguous()
+ value = value.contiguous()
+
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
+ # Note that it is important to check first for the shape, otherwise compile will fail with `argument 'is_causal' must be bool, not SymBool`
+ if is_causal is None:
+ is_causal = query.shape[2] > 1 and causal_mask is None
+
+ # Shapes (e.g. query.shape[2]) are tensors during jit tracing, resulting in `is_causal` being a tensor.
+ # We convert it to a bool for the SDPA kernel that only accepts bools.
+ if torch.jit.is_tracing() and isinstance(is_causal, torch.Tensor):
+ is_causal = is_causal.item()
+
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
+ query,
+ key,
+ value,
+ attn_mask=causal_mask,
+ dropout_p=dropout,
+ scale=scaling,
+ is_causal=is_causal,
+ )
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, None
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/spqr.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/spqr.py
new file mode 100644
index 0000000000000000000000000000000000000000..58b71740d37c77f24fe60ff65fe179b2737c4aa7
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/spqr.py
@@ -0,0 +1,122 @@
+# 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.
+"SpQR (Sparse-Quantized Representation) integration file"
+
+from ..utils import is_accelerate_available, is_spqr_available, is_torch_available
+
+
+if is_torch_available():
+ import torch.nn as nn
+
+
+def replace_with_spqr_linear(
+ model,
+ quantization_config=None,
+ modules_to_not_convert=None,
+ current_key_name=None,
+ has_been_replaced=False,
+):
+ """
+ Public method that recursively replaces the Linear layers of the given model with SpQR quantized layers.
+ `accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the
+ conversion has been successful or not.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to convert, can be any `torch.nn.Module` instance.
+ quantization_config (`SpQRConfig`):
+ The quantization config object that contains the quantization parameters.
+ modules_to_not_convert (`list[str]`, *optional*):
+ A list of nn.Linear weights to not convert. If a parameter path is in the list (e.g. `lm_head.weight`), the corresponding module will not be
+ converted.
+ current_key_name (`list`, *optional*):
+ A list that contains the current key name. This is used for recursion and should not be passed by the user.
+ has_been_replaced (`bool`, *optional*):
+ A boolean that indicates if the conversion has been successful or not. This is used for recursion and
+ should not be passed by the user.
+ """
+ if modules_to_not_convert is None:
+ modules_to_not_convert = []
+
+ if is_accelerate_available():
+ from accelerate import init_empty_weights
+ if is_spqr_available():
+ from spqr_quant import QuantizedLinear
+
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+
+ if isinstance(module, nn.Linear):
+ # Check if the current key is not in the `modules_to_not_convert`
+ if ".".join(current_key_name) + ".weight" not in modules_to_not_convert:
+ with init_empty_weights():
+ tensor_name = ".".join(current_key_name)
+
+ shapes = quantization_config.shapes
+ shapes_keys = shapes.keys()
+
+ shapes_valid = (
+ f"{tensor_name}.dense_weights.shape" in shapes_keys
+ and f"{tensor_name}.row_offsets.shape" in shapes_keys
+ and f"{tensor_name}.col_vals.shape" in shapes_keys
+ and f"{tensor_name}.in_perm.shape" in shapes_keys
+ )
+
+ if not shapes_valid:
+ raise ValueError(
+ f"The SpQR quantization config does not contain the shape "
+ f"configuration for {tensor_name}. This indicates that the "
+ f"configuration is either invalid or corrupted."
+ )
+
+ dense_weights_shape = shapes[f"{tensor_name}.dense_weights.shape"]
+ row_offsets_shape = shapes[f"{tensor_name}.row_offsets.shape"]
+ col_vals_shape = shapes[f"{tensor_name}.col_vals.shape"]
+ in_perm_shape = shapes[f"{tensor_name}.in_perm.shape"]
+
+ in_features = module.in_features
+ out_features = module.out_features
+
+ model._modules[name] = QuantizedLinear.create_placehodler(
+ rows=out_features,
+ cols=in_features,
+ bits=quantization_config.bits,
+ beta1=quantization_config.beta1,
+ beta2=quantization_config.beta2,
+ dense_weights_shape=dense_weights_shape,
+ row_offsets_shape=row_offsets_shape,
+ col_vals_shape=col_vals_shape,
+ in_perm_shape=in_perm_shape,
+ )
+ has_been_replaced = True
+
+ # Store the module class in case we need to transpose the weight later
+ model._modules[name].source_cls = type(module)
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+ else:
+ pass
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = replace_with_spqr_linear(
+ module,
+ quantization_config=quantization_config,
+ modules_to_not_convert=modules_to_not_convert,
+ current_key_name=current_key_name,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/tensor_parallel.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/tensor_parallel.py
new file mode 100644
index 0000000000000000000000000000000000000000..18163f230ee6f23e96e099e4e2173ecdfd6b306e
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/tensor_parallel.py
@@ -0,0 +1,544 @@
+# 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.
+from __future__ import annotations
+
+import re
+from functools import lru_cache, partial
+from typing import List, Optional, Tuple, Union
+
+import torch
+from torch import nn
+
+from ..utils import is_torch_greater_or_equal, logging
+
+
+ALL_LAYERNORM_LAYERS = [nn.LayerNorm]
+
+logger = logging.get_logger(__name__)
+
+# Cache this result has it's a C FFI call which can be pretty time-consuming
+_torch_distributed_available = torch.distributed.is_available()
+
+
+if is_torch_greater_or_equal("2.5") and _torch_distributed_available:
+ from torch.distributed.tensor import DTensor, Placement, Replicate, Shard
+
+
+def _blocks_to_block_sizes(total_size: int, blocks: Union[int, List[int]]) -> List[int]:
+ """
+ Convert block count or proportions to block sizes.
+
+ This function accepts
+
+ - The number of blocks (int), in which case the block size is
+ total_size//blocks; or
+ - A list of block sizes (List[int]).
+
+ In the second case, if sum(blocks) < total_size, the ratios between
+ the block sizes will be preserved. For instance, if blocks is
+ [2, 1, 1] and total_size is 1024, the returned block sizes are
+ [512, 256, 256].
+ """
+ if isinstance(blocks, list):
+ total_blocks = sum(blocks)
+ assert total_size % total_blocks == 0, f"Cannot split {total_size} in proportional blocks: {blocks}"
+ part_size = total_size // total_blocks
+ return [part_size * block for block in blocks]
+ else:
+ assert total_size % blocks == 0, f"Prepacked is not divisible by {blocks}"
+ single_size = total_size // blocks
+ return [single_size] * blocks
+
+
+def get_packed_weights(param, empty_param, device_mesh, rank, dim):
+ """
+ When weights are packed (gate_up_proj), we need to make sure each shard gets its correct share.
+ So if you have: gate_proj ( 16, 5120, 8190)
+ and up_proj ( 16, 5120, 8190)
+ packed as gate_up_proj ( 16, 5120, 2 * 8190)
+ And you shard along the last dimension, you need to interleave the gate and up values:
+
+ Now, if we shard along the last dimension across TP_size (Tensor Parallelism size), we must interleave the values from gate and up projections correctly.
+
+ Let's take TP_size = 4 for an example:
+
+ Packed tensor `gate_up_proj`
+ ---------------------------------------------------------------
+ [ G0 G1 G2 G3 | G4 G5 G6 G7 | ... | U0 U1 U2 U3 | U4 U5 U6 U7 | ... ]
+ ↑─────────────↑ ↑─────────────↑ ↑─────────────↑ ↑─────────────↑
+ Gate Slice 0 Gate Slice 1 Up Slice 0 Up Slice 1
+
+ Explanation:
+ - The first half of the tensor (left of the center) holds the gate_proj values.
+ - The second half (right of the center) holds the up_proj values.
+ - For TP=4, we divide each half into 4 slices. In this example, we show two slices for brevity.
+ - Each shard receives one slice from the gate part and the corresponding slice from the up part.
+
+ For instance:
+ • Shard 0 gets: [ Gate Slice 0, Up Slice 0 ] = [ G0, G1, G2, G3, U0, U1, U2, U3 ]
+ • Shard 1 gets: [ Gate Slice 1, Up Slice 1 ] = [ G4, G5, G6, G7, U4, U5, U6, U7 ]
+ • … and so on.
+
+ This ensures that each shard receives an equal portion of both gate and up projections, maintaining consistency across tensor parallelism.
+ """
+ slice_ = param
+ total_size = empty_param.shape[dim]
+ world_size = device_mesh.size()
+ block_sizes = _blocks_to_block_sizes(total_size=total_size, blocks=2)
+
+ tensors_slices = []
+ block_offset = 0
+ for block_size in block_sizes:
+ shard_block_size = block_size // world_size
+ start = rank * shard_block_size
+ stop = (rank + 1) * shard_block_size
+ tensors_slices += range(block_offset + start, block_offset + stop)
+ block_offset += block_size
+
+ if dim == 0:
+ tensor = slice_[tensors_slices, ...]
+ elif dim == 1 or dim == -2:
+ tensor = slice_[:, tensors_slices, ...]
+ elif dim == 2 or dim == -1:
+ tensor = slice_[..., tensors_slices]
+ else:
+ raise ValueError(f"Unsupported dim {dim}, only dim 0, 1 or 2 are supported")
+ return tensor
+
+
+def get_tensor_shard(param, empty_param, device_mesh, rank, dim):
+ if dim == 0:
+ size_ = empty_param.shape[0]
+ param = param[rank * (size_ // device_mesh.size()) : (rank + 1) * (size_ // device_mesh.size()), ...]
+ elif dim == 1 or dim == -2:
+ size_ = empty_param.shape[-2]
+ param = param[..., rank * (size_ // device_mesh.size()) : (rank + 1) * (size_ // device_mesh.size()), :]
+ elif dim == 2 or dim == -1:
+ size_ = empty_param.shape[-1]
+ param = param[..., rank * (size_ // device_mesh.size()) : (rank + 1) * (size_ // device_mesh.size())]
+ else:
+ raise ValueError(f"Unsupported dim {dim}, only dim 0, 1 or 2 are supported")
+ return param
+
+
+def distribute_module(
+ module: nn.Module,
+ device_mesh=None,
+ input_fn=None,
+ output_fn=None,
+) -> nn.Module:
+ """
+ Copy pasted from torch's function but we remove the communications (partitionning)
+ as well as buffer registering that is similarly not efficient.
+ """
+ if len(module._forward_pre_hooks) == 0:
+ if input_fn is not None:
+ module.register_forward_pre_hook(lambda mod, inputs: input_fn(mod, inputs, device_mesh))
+ if output_fn is not None:
+ module.register_forward_hook(lambda mod, inputs, outputs: output_fn(mod, outputs, device_mesh))
+ return module
+
+
+class TensorParallelLayer:
+ """
+ General tensor parallel layer for transformers.
+ """
+
+ use_dtensor = True
+
+ @staticmethod
+ def _prepare_input_fn(input_layouts, desired_input_layouts, mod, inputs, device_mesh): ...
+
+ @staticmethod
+ def _prepare_output_fn(output_layouts, use_local_output, mod, outputs, device_mesh): ...
+
+ def partition_tensor(self, param, empty_param, param_type, param_casting_dtype, to_contiguous, rank, device_mesh):
+ raise NotImplementedError
+
+ def prepare_module_tp(self, module: nn.Module, device_mesh) -> nn.Module:
+ if self.use_dtensor:
+ distribute_module(
+ module,
+ device_mesh,
+ partial(self._prepare_input_fn, self.input_layouts, self.desired_input_layouts),
+ partial(self._prepare_output_fn, self.output_layouts, self.use_local_output),
+ )
+
+
+# use_dtensor needs to be set to false for nn.Parameter when you want to view, chunk, slice
+# you name it. Whatever you want to do that is a bit unconventional, you need local tensors
+class GatherParallel(TensorParallelLayer):
+ """
+ Simple class used to define the hooks to add to a layer when we just want to gather the outputs
+ """
+
+ def __init__(
+ self,
+ *,
+ input_layouts: Optional[Placement] = None,
+ output_layouts: Optional[Placement] = None,
+ use_local_output: bool = True,
+ ):
+ super().__init__()
+ self.input_layouts = (input_layouts or Replicate(),)
+ self.output_layouts = output_layouts
+ self.desired_input_layouts = (Replicate(),)
+ self.use_local_output = use_local_output
+
+ @staticmethod
+ def _prepare_input_fn(input_layouts, desired_input_layouts, mod, inputs, device_mesh):
+ if isinstance(inputs[0], DTensor):
+ inputs[0] = inputs[0].to_local()
+ return inputs
+
+ @staticmethod
+ def _prepare_output_fn(output_layouts, use_local_output, mod, outputs, device_mesh):
+ torch.distributed.all_reduce(outputs[0], op=torch.distributed.ReduceOp.SUM, async_op=False)
+ return outputs
+
+
+class IsolatedParallel(TensorParallelLayer):
+ """
+ This class is used to isolate computation in a TP layer from the rest of the world.
+ Parameters need to be LOCAL, so not dtensors
+ """
+
+ @staticmethod
+ def _prepare_input_fn(input_layouts, desired_input_layouts, mod, inputs, device_mesh=None):
+ # annotate module input placements/sharding with input_layouts
+ input_tensor = inputs[0]
+ if isinstance(input_tensor, DTensor):
+ input_tensor = input_tensor.to_local()
+ return input_tensor
+
+ @staticmethod
+ def _prepare_output_fn(output_layouts, use_local_output, mod, outputs, device_mesh=None):
+ # TODO: figure out dynamo support for instance method and switch this to instance method
+ return outputs
+
+ def prepare_module_tp(self, module: nn.Module, device_mesh) -> nn.Module:
+ distribute_module(
+ module,
+ device_mesh,
+ partial(self._prepare_input_fn),
+ partial(self._prepare_output_fn),
+ )
+
+
+class ColwiseParallel(TensorParallelLayer):
+ """
+ General tensor parallel layer for transformers.
+ """
+
+ def __init__(
+ self,
+ *,
+ input_layouts: Optional[Placement] = None,
+ output_layouts: Optional[Placement] = None,
+ use_local_output: bool = True,
+ use_dtensor=True,
+ ):
+ super().__init__()
+ self.input_layouts = (input_layouts or Replicate(),)
+ self.output_layouts = (output_layouts or Shard(-1),)
+ self.desired_input_layouts = (Replicate(),)
+ self.use_local_output = use_local_output
+ self.use_dtensor = use_dtensor
+
+ @staticmethod
+ def _prepare_input_fn(input_layouts, desired_input_layouts, mod, inputs, device_mesh):
+ # TODO: figure out dynamo support for instance method and switch this to instance method
+ # annotate module input placements/sharding with input_layouts
+ input_tensor = inputs[0]
+ if not isinstance(input_tensor, DTensor):
+ input_tensor = DTensor.from_local(input_tensor, device_mesh, input_layouts, run_check=False)
+
+ # transform the input layouts to the desired layouts of ColwiseParallel
+ if input_layouts != desired_input_layouts:
+ input_tensor = input_tensor.redistribute(placements=desired_input_layouts, async_op=True)
+ return input_tensor
+
+ def partition_tensor(self, param, empty_param, param_type, param_casting_dtype, to_contiguous, rank, device_mesh):
+ # colwise shard weight/bias to Shard(0), weight be Shard(-2) (0 if you have 1 dim only)
+ # means Colwise as Linear is input * weight^T + bias, where
+ # weight would become Shard(1)
+ if param_type == "bias":
+ parameter = get_tensor_shard(param, empty_param, device_mesh, rank, -1)
+ shard = [Shard(-1)]
+ else:
+ shard = [Shard(-2)]
+ parameter = get_tensor_shard(param, empty_param, device_mesh, rank, -2)
+
+ parameter = parameter.to(param_casting_dtype)
+ if to_contiguous:
+ parameter = parameter.contiguous()
+ if self.use_dtensor:
+ parameter = DTensor.from_local(parameter, device_mesh, shard, run_check=False)
+ return nn.Parameter(parameter)
+
+ @staticmethod
+ def _prepare_output_fn(output_layouts, use_local_output, mod, outputs, device_mesh):
+ # outputs is a shard on last dimension DTensor, i.e. Shard(-1)
+ if outputs.placements != output_layouts:
+ outputs = outputs.redistribute(placements=output_layouts, async_op=True)
+ # back to local tensor
+ return outputs.to_local() if use_local_output else outputs
+
+
+class PackedColwiseParallel(ColwiseParallel):
+ def partition_tensor(self, param, empty_param, param_type, param_casting_dtype, to_contiguous, rank, device_mesh):
+ # colwise shard weight/bias to Shard(0), weight be Shard(-2) (0 if you have 1 dim only)
+ # means Colwise as Linear is input * weight^T + bias, where
+ # weight would become Shard(1)
+ parameter = get_packed_weights(param, empty_param, device_mesh, rank, -2)
+ parameter = parameter.to(param_casting_dtype)
+ if to_contiguous:
+ parameter = parameter.contiguous()
+ if self.use_dtensor:
+ parameter = DTensor.from_local(parameter, device_mesh, [Shard(-2)], run_check=False)
+ return nn.Parameter(parameter)
+
+
+class RowwiseParallel(TensorParallelLayer):
+ """
+ Partition a compatible nn.Module in a row-wise fashion. Currently supports nn.Linear and nn.Embedding.
+ Users can compose it with ColwiseParallel to achieve the sharding of more complicated modules.
+ (i.e. MLP, Attention)
+
+ Keyword Args:
+ input_layouts (Placement, optional):
+ The DTensor layout of input tensor for the nn.Module, this is used to annotate the input tensor to
+ become a DTensor. If not specified, we assume the input tensor to be sharded on the last dimension.
+ output_layouts (Placement, optional):
+ The DTensor layout of the output for the nn.Module, this is used to ensure the output of the nn.Module
+ with the user desired layout. If not specified, the output tensor is replicated.
+ use_local_output (bool, optional):
+ Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module output, default: True.
+ Returns:
+ A :class:`ParallelStyle` object that represents Rowwise sharding of the nn.Module.
+ """
+
+ def __init__(
+ self,
+ *,
+ input_layouts: Optional[Placement] = None,
+ output_layouts: Optional[Placement] = None,
+ use_local_output: bool = True,
+ use_dtensor=True,
+ ):
+ super().__init__()
+ self.input_layouts = (input_layouts or Shard(-1),)
+ self.output_layouts = (output_layouts or Replicate(),)
+ self.use_local_output = use_local_output
+ self.use_dtensor = use_dtensor
+
+ @staticmethod
+ def _prepare_input_fn(input_layouts, desired_input_layouts, mod, inputs, device_mesh):
+ input_tensor = inputs[0]
+ if not isinstance(input_tensor, DTensor):
+ input_tensor = DTensor.from_local(input_tensor, device_mesh, input_layouts, run_check=False)
+
+ if input_layouts != desired_input_layouts:
+ input_tensor = input_tensor.redistribute(placements=desired_input_layouts, async_op=True)
+ return input_tensor
+
+ def partition_tensor(self, param, empty_param, param_type, param_casting_dtype, to_contiguous, rank, device_mesh):
+ # Rowwise shard weight to Shard(1), bias to Replicate(), weight be Shard(1)
+ # means Rowwise as nn.Linear is input * weight^T + bias, where
+ # weight would become Shard(0)
+ if param_type != "bias":
+ parameter = get_tensor_shard(param, empty_param, device_mesh, rank, -1)
+ shard = [Shard(-1)]
+ else:
+ shard = [Replicate()]
+ parameter = param[:]
+
+ parameter = parameter.to(param_casting_dtype)
+ if to_contiguous:
+ parameter = parameter.contiguous()
+ if self.use_dtensor:
+ parameter = DTensor.from_local(parameter, device_mesh, shard, run_check=False)
+ return nn.Parameter(parameter)
+
+ @staticmethod
+ def _prepare_output_fn(output_layouts, use_local_output, mod, outputs, device_mesh):
+ # Rowwise sharding produces partial output, depending on output layouts:
+ # 1. to replicate -> allreduce
+ # 2. to shard -> reduce_scatter
+ if outputs.placements != output_layouts:
+ outputs = outputs.redistribute(placements=output_layouts, async_op=True)
+ # back to local tensor if use_local_output is True
+ return outputs.to_local() if use_local_output else outputs
+
+ def prepare_module_tp(self, module: nn.Module, device_mesh) -> nn.Module:
+ module._distribute_module_applied = True
+ if self.use_dtensor:
+ if isinstance(module, nn.Linear):
+ # rowwise linear runtime sharding requires input tensor shard on last dim
+ self.desired_input_layouts: Tuple[Placement, ...] = (Shard(-1),)
+ elif isinstance(module, nn.Embedding):
+ # rowwise embedding runtime sharding requires input tensor replicated
+ self.desired_input_layouts = (Replicate(),)
+ elif isinstance(module, nn.Parameter):
+ # rowwise embedding runtime sharding requires input tensor replicated
+ self.desired_input_layouts = (Shard(-1),)
+ else:
+ raise NotImplementedError("RowwiseParallel currently only support nn.Linear and nn.Embedding!")
+
+ distribute_module(
+ module,
+ device_mesh,
+ partial(self._prepare_input_fn, self.input_layouts, self.desired_input_layouts),
+ partial(self._prepare_output_fn, self.output_layouts, self.use_local_output),
+ )
+
+
+class PackedRowwiseParallel(RowwiseParallel):
+ def partition_tensor(self, param, empty_param, param_type, param_casting_dtype, to_contiguous, rank, device_mesh):
+ # colwise shard weight/bias to Shard(0), weight be Shard(-2) (0 if you have 1 dim only)
+ # means Colwise as Linear is input * weight^T + bias, where
+ # weight would become Shard(1)
+ parameter = get_packed_weights(param, empty_param, device_mesh, rank, -1)
+ parameter = parameter.to(param_casting_dtype)
+ if to_contiguous:
+ parameter = parameter.contiguous()
+ if self.use_dtensor:
+ parameter = DTensor.from_local(parameter, device_mesh, [Shard(-1)], run_check=False)
+ return nn.Parameter(parameter)
+
+
+SUPPORTED_TP_STYLES = {
+ "colwise",
+ "rowwise",
+ "colwise_rep",
+ "rowwise_rep",
+ "local_colwise",
+ "local_rowwise",
+ "local",
+ "gather",
+ "local_packed_rowwise",
+}
+
+
+@lru_cache
+def translate_to_torch_parallel_style(style: str):
+ """
+ In model configurations, we use a neutral type (string) to specify parallel
+ styles, here we translate them into torch.distributed tensor-parallel
+ types.
+ """
+ if not isinstance(style, str):
+ raise ValueError(f"Unsupported parallel style type {type(style)}, expected str")
+
+ if style == "colwise":
+ return ColwiseParallel()
+ elif style == "rowwise":
+ return RowwiseParallel()
+ elif style == "colwise_rep":
+ return ColwiseParallel(output_layouts=Replicate())
+ elif style == "rowwise_rep":
+ return RowwiseParallel(input_layouts=Replicate())
+ elif style == "local_colwise":
+ return ColwiseParallel(use_dtensor=False)
+ elif style == "local_rowwise":
+ return RowwiseParallel(use_dtensor=False)
+ elif style == "local":
+ return IsolatedParallel()
+ elif style == "gather":
+ return GatherParallel()
+ elif style == "local_packed_rowwise":
+ return PackedRowwiseParallel(use_dtensor=False)
+ else:
+ raise ValueError(f"Unsupported parallel style value: {style}")
+
+
+def add_tensor_parallel_hooks_to_module(model, module, tp_plan, layer_name, current_module_plan, device_mesh):
+ """
+ Add hooks to the module holding the layer. Meaning:
+ ```
+ class MyModel(nn.Module):
+ def __init__(self):
+ self.layer = nn.Linear(10, 10)
+ ```
+ has state_dict like:
+ ```
+ {
+ "layer.weight": torch.Tensor,
+ "layer.bias": torch.Tensor
+ }
+ ```
+ we add hooks to `MyModel` as well as `layer` to make sure that the tensors are correctly sharded and gathered.
+ """
+
+ # 1. We add hooks to the layer being loaded:
+ if current_module_plan is not None:
+ tp_layer = translate_to_torch_parallel_style(current_module_plan)
+ tp_layer.prepare_module_tp(module, device_mesh)
+
+ # 2. We add hooks to the parrent module if needed
+ if "." in layer_name:
+ parrent_layer_name = layer_name.rsplit(".", 1)[0]
+ generic_name = re.sub(r"\d+", "*", parrent_layer_name)
+ # The module itself needs hooks
+ if module_plan := tp_plan.get(generic_name, False):
+ tp_layer = translate_to_torch_parallel_style(module_plan)
+ module_to_tp_ = model.get_submodule(parrent_layer_name)
+ tp_layer.prepare_module_tp(module_to_tp_, device_mesh)
+
+
+def shard_and_distribute_module(
+ model, param, empty_param, parameter_name, param_casting_dtype, is_contiguous, rank, device_mesh
+):
+ r"""
+ Main uses cases:
+ - column / rowise parallelism, you just shard all the weights of the layer (weight and bias)
+ - packed layers: you slice the weights, then shard like above
+ - custom operation:
+ - you want to add an all-gather at the end of a local layer.
+ - you want to have a layer that is isolated from the rest of the world (because torch.DTensor does not work well with `.view` for instance)
+
+ """
+ param_name, param_type = parameter_name.rsplit(".", 1) if "." in parameter_name else parameter_name
+ tp_plan = model._tp_plan
+ module_to_tp = model.get_submodule(param_name)
+ current_module_plan = None
+ generic_param_name = re.sub(r"\d+", "*", parameter_name)
+ if generic_param_name in tp_plan:
+ current_module_plan = tp_plan[generic_param_name]
+ elif "." in generic_param_name and generic_param_name.rsplit(".", 1)[0] in tp_plan:
+ current_module_plan = tp_plan[generic_param_name.rsplit(".", 1)[0]]
+
+ # Add hooks to the module if not done yet
+ # add_tensor_parallel_hooks_to_module(model, module_to_tp, tp_plan, param_name, current_module_plan, device_mesh)
+ if not getattr(module_to_tp, "_is_hooked", False):
+ add_tensor_parallel_hooks_to_module(model, module_to_tp, tp_plan, param_name, current_module_plan, device_mesh)
+ module_to_tp._is_hooked = True
+
+ if current_module_plan is not None:
+ tp_layer = translate_to_torch_parallel_style(current_module_plan)
+ param = tp_layer.partition_tensor(
+ param, empty_param, param_type, param_casting_dtype, is_contiguous, rank, device_mesh
+ )
+ else:
+ param = param[...]
+ if is_contiguous:
+ param = param.contiguous()
+
+ # SUPER IMPORTANT we have to use setattr
+ # otherwise loading is crazy slow
+ if not isinstance(param, torch.nn.Parameter):
+ param = torch.nn.Parameter(param)
+ setattr(module_to_tp, param_type, param)
+ # module_to_tp.load_state_dict({param_type: param}, strict=False, assign=True)
+ return param
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/tiktoken.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/tiktoken.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f200bc355933bcb9ec119e08b560241fc1433c5
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/tiktoken.py
@@ -0,0 +1,43 @@
+from pathlib import Path
+from typing import Any
+
+from transformers.convert_slow_tokenizer import TikTokenConverter
+from transformers.tokenization_utils_fast import TIKTOKEN_VOCAB_FILE, TOKENIZER_FILE
+
+
+def convert_tiktoken_to_fast(encoding: Any, output_dir: str):
+ """
+ Converts given `tiktoken` encoding to `PretrainedTokenizerFast` and saves the configuration of converted tokenizer
+ on disk.
+
+ Args:
+ encoding (`str` or `tiktoken.Encoding`):
+ Tokenizer from `tiktoken` library. If `encoding` is `str`, the tokenizer will be loaded with
+ `tiktoken.get_encoding(encoding)`.
+ output_dir (`str`):
+ Save path for converted tokenizer configuration file.
+ """
+ output_dir = Path(output_dir)
+ output_dir.mkdir(exist_ok=True)
+
+ save_file = output_dir / "tiktoken" / TIKTOKEN_VOCAB_FILE
+ tokenizer_file = output_dir / TOKENIZER_FILE
+
+ save_file_absolute = str(save_file.absolute())
+ output_file_absolute = str(tokenizer_file.absolute())
+
+ try:
+ from tiktoken import get_encoding
+ from tiktoken.load import dump_tiktoken_bpe
+
+ if isinstance(encoding, str):
+ encoding = get_encoding(encoding)
+
+ dump_tiktoken_bpe(encoding._mergeable_ranks, save_file_absolute)
+ except ImportError:
+ raise ValueError("`tiktoken` is required to save a `tiktoken` file. Install it with `pip install tiktoken`.")
+
+ tokenizer = TikTokenConverter(
+ vocab_file=save_file_absolute, pattern=encoding._pat_str, additional_special_tokens=encoding._special_tokens
+ ).converted()
+ tokenizer.save(output_file_absolute)
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/tpu.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/tpu.py
new file mode 100644
index 0000000000000000000000000000000000000000..29262789dc98558ecc872b9e84cda4468e4b85ea
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/tpu.py
@@ -0,0 +1,36 @@
+# 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.
+
+from torch.utils.data import DataLoader
+
+from ..utils import is_torch_xla_available
+
+
+def tpu_spmd_dataloader(dataloader: DataLoader):
+ if is_torch_xla_available():
+ import torch_xla.distributed.parallel_loader as pl
+
+ assert isinstance(
+ dataloader, pl.MpDeviceLoader
+ ), "The dataloader must be a `torch_xla.distributed.parallel_loader.MpDeviceLoader`."
+
+ # This is to support PyTorch/XLA FSDP via SPMD.
+ # Here we shard the input data's 0th dim across the fsdp axis.
+ import torch_xla.distributed.spmd as xs
+
+ sharding_spec = xs.ShardingSpec(xs.get_global_mesh(), ("fsdp", None))
+ dataloader._parallel_loader_kwargs["input_sharding"] = sharding_spec
+ return dataloader
+ else:
+ return dataloader
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/vptq.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/vptq.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa435517e81ebe3f9e624b45d34a601e512f5b1b
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/integrations/vptq.py
@@ -0,0 +1,101 @@
+# 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.
+"VPTQ (Vector Post-Training Quantization) integration file"
+
+import torch.nn as nn
+from accelerate import init_empty_weights
+from vptq import VQuantLinear
+
+
+def replace_with_vptq_linear(
+ model,
+ quantization_config=None,
+ modules_to_not_convert=None,
+ current_key_name=None,
+ has_been_replaced=False,
+):
+ """
+ Public method that recursively replaces the Linear layers of the given model with VPTQ quantized layers.
+ `accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the
+ conversion has been successfull or not.
+
+ Args:
+ model (`torch.nn.Module`):
+ The model to convert, can be any `torch.nn.Module` instance.
+ quantization_config (`VptqConfig`):
+ The quantization config object that contains the quantization parameters.
+ modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`):
+ Names of the modules to not convert in `VQuantLinear`. In practice we keep the `lm_head` in full precision
+ for numerical stability reasons.
+ current_key_name (`list`, *optional*):
+ A list that contains the current key name. This is used for recursion and should not be passed by the user.
+ has_been_replaced (`bool`, *optional*):
+ A boolean that indicates if the conversion has been successful or not. This is used for recursion and
+ should not be passed by the user.
+ """
+
+ modules_to_not_convert = ["lm_head"] if not modules_to_not_convert else modules_to_not_convert
+
+ for name, module in model.named_children():
+ if current_key_name is None:
+ current_key_name = []
+ current_key_name.append(name)
+ layer_name = ".".join(current_key_name)
+ shared_layer_config = quantization_config.shared_layer_config
+ config_for_layers = quantization_config.config_for_layers
+
+ if (
+ isinstance(module, nn.Linear)
+ and layer_name not in modules_to_not_convert
+ and ((layer_name in config_for_layers) or (current_key_name[-1] in shared_layer_config))
+ ):
+ layer_params = config_for_layers.get(layer_name, None) or shared_layer_config.get(
+ current_key_name[-1], None
+ )
+
+ with init_empty_weights():
+ in_features = module.in_features
+ out_features = module.out_features
+
+ model._modules[name] = VQuantLinear(
+ in_features,
+ out_features,
+ vector_lens=layer_params["vector_lens"],
+ num_centroids=layer_params["num_centroids"],
+ num_res_centroids=layer_params["num_res_centroids"],
+ group_num=layer_params["group_num"],
+ group_size=layer_params["group_size"],
+ outlier_size=layer_params["outlier_size"],
+ indices_as_float=layer_params["indices_as_float"],
+ enable_norm=layer_params["enable_norm"],
+ enable_perm=layer_params["enable_perm"],
+ is_indice_packed=True,
+ enable_proxy_error=False,
+ bias=module.bias is not None,
+ )
+ has_been_replaced = True
+
+ # Force requires grad to False to avoid unexpected errors
+ model._modules[name].requires_grad_(False)
+ if len(list(module.children())) > 0:
+ _, has_been_replaced = replace_with_vptq_linear(
+ module,
+ quantization_config=quantization_config,
+ modules_to_not_convert=modules_to_not_convert,
+ current_key_name=current_key_name,
+ has_been_replaced=has_been_replaced,
+ )
+ # Remove the last key for recursion
+ current_key_name.pop(-1)
+ return model, has_been_replaced
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/keras_callbacks.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/keras_callbacks.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6e832729a1eeb482d1193753cc2c07ad1f16c2e
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/keras_callbacks.py
@@ -0,0 +1,413 @@
+import logging
+import os
+from pathlib import Path
+from time import sleep
+from typing import Callable, List, Optional, Union
+
+import numpy as np
+import tensorflow as tf
+from huggingface_hub import Repository, create_repo
+from packaging.version import parse
+
+from . import IntervalStrategy, PreTrainedTokenizerBase
+from .modelcard import TrainingSummary
+from .modeling_tf_utils import keras
+
+
+logger = logging.getLogger(__name__)
+
+
+class KerasMetricCallback(keras.callbacks.Callback):
+ """
+ Callback to compute metrics at the end of every epoch. Unlike normal Keras metrics, these do not need to be
+ compilable by TF. It is particularly useful for common NLP metrics like BLEU and ROUGE that require string
+ operations or generation loops that cannot be compiled. Predictions (or generations) will be computed on the
+ `eval_dataset` before being passed to the `metric_fn` in `np.ndarray` format. The `metric_fn` should compute
+ metrics and return a dict mapping metric names to metric values.
+
+ We provide an example of a suitable metric_fn that computes ROUGE scores for a summarization model below. Note that
+ this example skips some post-processing for readability and simplicity, and should probably not be used as-is!
+
+ ```py
+ from datasets import load_metric
+
+ rouge_metric = load_metric("rouge")
+
+
+ def rouge_fn(predictions, labels):
+ decoded_predictions = tokenizer.batch_decode(predictions, skip_special_tokens=True)
+ decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
+ result = rouge_metric.compute(predictions=decoded_predictions, references=decoded_labels)
+ return {key: value.mid.fmeasure * 100 for key, value in result.items()}
+ ```
+
+ The above function will return a dict containing values which will be logged like any other Keras metric:
+
+ ```
+ {'rouge1': 37.4199, 'rouge2': 13.9768, 'rougeL': 34.361, 'rougeLsum': 35.0781
+ ```
+
+ Args:
+ metric_fn (`Callable`):
+ Metric function provided by the user. It will be called with two arguments - `predictions` and `labels`.
+ These contain the model's outputs and matching labels from the dataset. It should return a dict mapping
+ metric names to numerical values.
+ eval_dataset (`tf.data.Dataset` or `dict` or `tuple` or `np.ndarray` or `tf.Tensor`):
+ Validation data to be used to generate predictions for the `metric_fn`.
+ output_cols (`List[str], *optional*):
+ A list of columns to be retained from the model output as the predictions. Defaults to all.
+ label_cols ('`List[str]`, *optional*'):
+ A list of columns to be retained from the input dataset as the labels. Will be autodetected if this is not
+ supplied.
+ batch_size (`int`, *optional*):
+ Batch size. Only used when the data is not a pre-batched `tf.data.Dataset`.
+ predict_with_generate (`bool`, *optional*, defaults to `False`):
+ Whether we should use `model.generate()` to get outputs for the model.
+ use_xla_generation (`bool`, *optional*, defaults to `False`):
+ If we're generating, whether to compile model generation with XLA. This can massively increase the speed of
+ generation (up to 100X speedup) but will require a new XLA compilation for each input shape. When using XLA
+ generation, it's a good idea to pad your inputs to the same size, or to use the `pad_to_multiple_of`
+ argument in your `tokenizer` or `DataCollator`, which will reduce the number of unique input shapes and
+ save a lot of compilation time. This option has no effect is `predict_with_generate` is `False`.
+ generate_kwargs (`dict`, *optional*):
+ Keyword arguments to pass to `model.generate()` when generating. Has no effect if `predict_with_generate`
+ is `False`.
+
+ """
+
+ def __init__(
+ self,
+ metric_fn: Callable,
+ eval_dataset: Union[tf.data.Dataset, np.ndarray, tf.Tensor, tuple, dict],
+ output_cols: Optional[List[str]] = None,
+ label_cols: Optional[List[str]] = None,
+ batch_size: Optional[int] = None,
+ predict_with_generate: bool = False,
+ use_xla_generation: bool = False,
+ generate_kwargs: Optional[dict] = None,
+ ):
+ super().__init__()
+ self.metric_fn = metric_fn
+ self.batch_size = batch_size
+ if not isinstance(eval_dataset, tf.data.Dataset):
+ if batch_size is None:
+ raise ValueError(
+ "When passing data to KerasMetricCallback that is not a pre-batched tf.data.Dataset "
+ "the batch_size argument must be set."
+ )
+ # Wrap a tf.data.Dataset around it
+ eval_dataset = tf.data.Dataset.from_tensor_slices(eval_dataset).batch(batch_size, drop_remainder=False)
+ self.eval_dataset = eval_dataset
+ self.predict_with_generate = predict_with_generate
+ self.output_cols = output_cols
+
+ # This next block attempts to parse out which elements of the dataset should be appended to the labels list
+ # that is passed to the metric_fn
+ if isinstance(eval_dataset.element_spec, tuple) and len(eval_dataset.element_spec) == 2:
+ input_spec, label_spec = eval_dataset.element_spec
+ else:
+ input_spec = eval_dataset.element_spec
+ label_spec = None
+ if label_cols is not None:
+ for label in label_cols:
+ if label not in input_spec:
+ raise ValueError(f"Label {label} is in label_cols but could not be found in the dataset inputs!")
+ self.label_cols = label_cols
+ self.use_keras_label = False
+ elif label_spec is not None:
+ # If the dataset inputs are split into a 2-tuple of inputs and labels,
+ # assume the second element is the labels
+ self.label_cols = None
+ self.use_keras_label = True
+ elif "labels" in input_spec:
+ self.label_cols = ["labels"]
+ self.use_keras_label = False
+ logging.warning("No label_cols specified for KerasMetricCallback, assuming you want the 'labels' key.")
+ elif "start_positions" in input_spec and "end_positions" in input_spec:
+ self.label_cols = ["start_positions", "end_positions"]
+ self.use_keras_label = False
+ logging.warning(
+ "No label_cols specified for KerasMetricCallback, assuming you want the "
+ "start_positions and end_positions keys."
+ )
+ else:
+ raise ValueError("Could not autodetect label_cols for KerasMetricCallback, please specify them!")
+ if parse(tf.__version__) < parse("2.7"):
+ logging.warning("TF versions less than 2.7 may encounter issues with KerasMetricCallback!")
+
+ self.use_xla_generation = use_xla_generation
+ self.generate_kwargs = {} if generate_kwargs is None else generate_kwargs
+
+ self.generation_function = None
+
+ @staticmethod
+ def _concatenate_batches(batches, padding_index=-100):
+ # If all batches are unidimensional or same length, do a simple concatenation
+ if batches[0].ndim == 1 or all(batch.shape[1] == batches[0].shape[1] for batch in batches):
+ return np.concatenate(batches, axis=0)
+
+ # Welp, they're not the same length. Let's do some padding
+ max_len = max([batch.shape[1] for batch in batches])
+ num_samples = sum([batch.shape[0] for batch in batches])
+ output = np.full_like(
+ batches[0], fill_value=padding_index, shape=[num_samples, max_len] + list(batches[0].shape[2:])
+ )
+ # i keeps track of which part of the concatenated array we're writing the next batch to
+ i = 0
+ for batch in batches:
+ output[i : i + len(batch), : batch.shape[1]] = batch
+ i += len(batch)
+ return output
+
+ def _postprocess_predictions_or_labels(self, inputs):
+ if isinstance(inputs[0], dict):
+ outputs = {}
+ for key in inputs[0].keys():
+ outputs[key] = self._concatenate_batches([batch[key] for batch in inputs])
+ # If it's a dict with only one key, just return the array
+ if len(outputs) == 1:
+ outputs = list(outputs.values())[0]
+ elif isinstance(inputs[0], list) or isinstance(inputs[0], tuple):
+ outputs = []
+ for input_list in zip(*inputs):
+ outputs.append(self._concatenate_batches(input_list))
+ if len(outputs) == 1:
+ outputs = outputs[0] # If it's a list with only one element, just return the array
+ elif isinstance(inputs[0], np.ndarray):
+ outputs = self._concatenate_batches(inputs)
+ elif isinstance(inputs[0], tf.Tensor):
+ outputs = self._concatenate_batches([tensor.numpy() for tensor in inputs])
+ else:
+ raise TypeError(f"Couldn't handle batch of type {type(inputs[0])}!")
+ return outputs
+
+ def on_epoch_end(self, epoch, logs=None):
+ if hasattr(self.model, "config"):
+ ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", [])
+ else:
+ ignore_keys = []
+
+ main_input_name = None
+ if self.predict_with_generate:
+ # This dense conditional recognizes the case where we have an encoder-decoder model, but
+ # avoids getting tangled up when we just have a model with a layer called 'encoder'
+ if hasattr(self.model, "encoder") and hasattr(self.model.encoder, "main_input_name"):
+ main_input_name = self.model.encoder.main_input_name
+ else:
+ main_input_name = getattr(self.model, "main_input_name", "input_ids")
+
+ if self.use_xla_generation and self.generation_function is None:
+
+ def generation_function(inputs, attention_mask):
+ return self.model.generate(inputs, attention_mask=attention_mask, **self.generate_kwargs)
+
+ self.generation_function = tf.function(generation_function, jit_compile=True)
+
+ prediction_list = []
+ label_list = []
+
+ # The whole predict/generate loop is handled inside this method
+ for batch in self.eval_dataset:
+ if isinstance(batch, tuple):
+ batch, labels = batch
+ else:
+ labels = None
+ if self.predict_with_generate:
+ if isinstance(batch, dict):
+ generation_inputs = batch[main_input_name]
+ attention_mask = batch.get("attention_mask", None)
+ else:
+ generation_inputs = batch
+ attention_mask = None
+ if self.use_xla_generation:
+ predictions = self.generation_function(generation_inputs, attention_mask=attention_mask)
+ else:
+ predictions = self.model.generate(
+ generation_inputs, attention_mask=attention_mask, **self.generate_kwargs
+ )
+ else:
+ predictions = self.model.predict_on_batch(batch)
+ if isinstance(predictions, dict):
+ # This converts any dict-subclass to a regular dict
+ # Keras REALLY doesn't like it when we pass around a BatchEncoding or other derived class
+ predictions = dict(predictions)
+ if self.output_cols is not None:
+ predictions = {key: predictions[key] for key in self.output_cols}
+ else:
+ predictions = {
+ key: val for key, val in predictions.items() if key not in ignore_keys + ["loss"]
+ }
+ prediction_list.append(predictions)
+ if not self.use_keras_label:
+ labels = {key: batch[key].numpy() for key in self.label_cols}
+ elif isinstance(labels, dict):
+ labels = {key: array.numpy() for key, array in labels.items()}
+ elif isinstance(labels, list) or isinstance(labels, tuple):
+ labels = [array.numpy() for array in labels]
+ elif isinstance(labels, tf.Tensor):
+ labels = labels.numpy()
+ else:
+ raise TypeError(f"Confused by labels of type {type(labels)}")
+ label_list.append(labels)
+
+ all_preds = self._postprocess_predictions_or_labels(prediction_list)
+ all_labels = self._postprocess_predictions_or_labels(label_list)
+
+ metric_output = self.metric_fn((all_preds, all_labels))
+ if not isinstance(metric_output, dict):
+ raise TypeError(
+ f"metric_fn should return a dict mapping metric names to values but instead returned {metric_output}"
+ )
+ # This is the critical bit - Keras passes a dict containing the loss and standard metric values for this epoch
+ # in the logs argument. Ordinarily, this is so the callback can read them, but in this case we write a bunch of
+ # new keys in there, which will then get read by the History callback and treated like any other metric value.
+ # I promise that I have it in writing from Chollet that this is okay.
+ logs.update(metric_output)
+
+
+class PushToHubCallback(keras.callbacks.Callback):
+ """
+ Callback that will save and push the model to the Hub regularly. By default, it pushes once per epoch, but this can
+ be changed with the `save_strategy` argument. Pushed models can be accessed like any other model on the hub, such
+ as with the `from_pretrained` method.
+
+ ```py
+ from transformers.keras_callbacks import PushToHubCallback
+
+ push_to_hub_callback = PushToHubCallback(
+ output_dir="./model_save",
+ tokenizer=tokenizer,
+ hub_model_id="gpt5-7xlarge",
+ )
+
+ model.fit(train_dataset, callbacks=[push_to_hub_callback])
+ ```
+
+ Args:
+ output_dir (`str`):
+ The output directory where the model predictions and checkpoints will be written and synced with the
+ repository on the Hub.
+ save_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"epoch"`):
+ The checkpoint save strategy to adopt during training. Possible values are:
+
+ - `"no"`: Save is done at the end of training.
+ - `"epoch"`: Save is done at the end of each epoch.
+ - `"steps"`: Save is done every `save_steps`
+ save_steps (`int`, *optional*):
+ The number of steps between saves when using the "steps" `save_strategy`.
+ tokenizer (`PreTrainedTokenizerBase`, *optional*):
+ The tokenizer used by the model. If supplied, will be uploaded to the repo alongside the weights.
+ hub_model_id (`str`, *optional*):
+ The name of the repository to keep in sync with the local `output_dir`. It can be a simple model ID in
+ which case the model will be pushed in your namespace. Otherwise it should be the whole repository name,
+ for instance `"user_name/model"`, which allows you to push to an organization you are a member of with
+ `"organization_name/model"`.
+
+ Will default to the name of `output_dir`.
+ hub_token (`str`, *optional*):
+ The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with
+ `huggingface-cli login`.
+ checkpoint (`bool`, *optional*, defaults to `False`):
+ Whether to save full training checkpoints (including epoch and optimizer state) to allow training to be
+ resumed. Only usable when `save_strategy` is `"epoch"`.
+ """
+
+ def __init__(
+ self,
+ output_dir: Union[str, Path],
+ save_strategy: Union[str, IntervalStrategy] = "epoch",
+ save_steps: Optional[int] = None,
+ tokenizer: Optional[PreTrainedTokenizerBase] = None,
+ hub_model_id: Optional[str] = None,
+ hub_token: Optional[str] = None,
+ checkpoint: bool = False,
+ **model_card_args,
+ ):
+ super().__init__()
+ if checkpoint and save_strategy != "epoch":
+ raise ValueError("Cannot save checkpoints when save_strategy is not 'epoch'!")
+ if isinstance(save_strategy, str):
+ save_strategy = IntervalStrategy(save_strategy.lower())
+ self.save_strategy = save_strategy
+ if self.save_strategy == IntervalStrategy.STEPS and (not isinstance(save_steps, int) or save_steps <= 0):
+ raise ValueError("Please supply a positive integer argument for save_steps when save_strategy == 'steps'!")
+ self.save_steps = save_steps
+ output_dir = Path(output_dir)
+
+ # Create repo and retrieve repo_id
+ if hub_model_id is None:
+ hub_model_id = output_dir.absolute().name
+ self.hub_model_id = create_repo(repo_id=hub_model_id, exist_ok=True, token=hub_token).repo_id
+
+ self.output_dir = output_dir
+ self.repo = Repository(str(self.output_dir), clone_from=self.hub_model_id, token=hub_token)
+
+ self.tokenizer = tokenizer
+ self.last_job = None
+ self.checkpoint = checkpoint
+ self.training_history = None
+ self.model_card_args = model_card_args
+
+ def on_train_begin(self, logs=None):
+ # Although we can access model.history, we have no guarantees that the History callback will fire before this
+ # one, so we keep track of it here too
+ self.training_history = []
+
+ def on_train_batch_end(self, batch, logs=None):
+ if self.save_strategy == IntervalStrategy.STEPS and (batch + 1) % self.save_steps == 0:
+ if self.last_job is not None and not self.last_job.is_done:
+ return # The last upload is still running, don't start another
+ self.model.save_pretrained(self.output_dir)
+ if self.tokenizer is not None:
+ self.tokenizer.save_pretrained(self.output_dir)
+ _, self.last_job = self.repo.push_to_hub(
+ commit_message=f"Training in progress steps {batch}", blocking=False
+ )
+
+ def on_epoch_end(self, epoch, logs=None):
+ logs = logs.copy() # Don't accidentally write things that Keras will read later
+ if "epoch" not in logs:
+ logs["epoch"] = epoch
+ self.training_history.append(logs)
+ if self.save_strategy == IntervalStrategy.EPOCH:
+ if self.last_job is not None and not self.last_job.is_done:
+ return # The last upload is still running, don't start another
+ self.model.save_pretrained(self.output_dir)
+ if self.tokenizer is not None:
+ self.tokenizer.save_pretrained(self.output_dir)
+ if self.checkpoint:
+ checkpoint_dir = os.path.join(self.output_dir, "checkpoint")
+ self.model._save_checkpoint(checkpoint_dir, epoch)
+ train_summary = TrainingSummary.from_keras(
+ model=self.model,
+ model_name=self.hub_model_id,
+ keras_history=self.training_history,
+ **self.model_card_args,
+ )
+ model_card = train_summary.to_model_card()
+ with (self.output_dir / "README.md").open("w") as f:
+ f.write(model_card)
+ _, self.last_job = self.repo.push_to_hub(
+ commit_message=f"Training in progress epoch {epoch}", blocking=False
+ )
+
+ def on_train_end(self, logs=None):
+ # Makes sure the latest version of the model is uploaded
+ if self.last_job is not None and not self.last_job.is_done:
+ logging.info("Pushing the last epoch to the Hub, this may take a while...")
+ while not self.last_job.is_done:
+ sleep(1)
+ else:
+ self.model.save_pretrained(self.output_dir)
+ if self.tokenizer is not None:
+ self.tokenizer.save_pretrained(self.output_dir)
+ train_summary = TrainingSummary.from_keras(
+ model=self.model,
+ model_name=self.hub_model_id,
+ keras_history=self.training_history,
+ **self.model_card_args,
+ )
+ model_card = train_summary.to_model_card()
+ with (self.output_dir / "README.md").open("w") as f:
+ f.write(model_card)
+ self.repo.push_to_hub(commit_message="End of training", blocking=True)
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/__init__.py b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.cpp b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..388a73d22d4c9b561e2a887b50a1897b8cf2def9
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.cpp
@@ -0,0 +1,40 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include
+
+#include
+#include
+
+
+at::Tensor
+ms_deform_attn_cpu_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ AT_ERROR("Not implement on cpu");
+}
+
+std::vector
+ms_deform_attn_cpu_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+ AT_ERROR("Not implement on cpu");
+}
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.h b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.h
new file mode 100644
index 0000000000000000000000000000000000000000..7eac8c8bcd1bf529bb9c13d54d2d4215c9e4c89f
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.h
@@ -0,0 +1,32 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#pragma once
+#include
+
+at::Tensor
+ms_deform_attn_cpu_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step);
+
+std::vector
+ms_deform_attn_cpu_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step);
+
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cu b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cu
new file mode 100644
index 0000000000000000000000000000000000000000..c2b3a462a1a06338d4a04c33a6867fcad42248e6
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cu
@@ -0,0 +1,159 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include
+#include "cuda/ms_deform_im2col_cuda.cuh"
+
+#include
+#include
+#include
+#include
+
+#pragma once
+#include
+
+
+at::Tensor ms_deform_attn_cuda_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ at::DeviceGuard guard(value.device());
+
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+
+ AT_ASSERTM(value.is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.is_cuda(), "attn_weight must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto output = at::zeros({batch, num_query, num_heads, channels}, value.options());
+
+ const int batch_n = im2col_step_;
+ auto output_n = output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto columns = output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, value.scalar_type(), "ms_deform_attn_forward_cuda", ([&] {
+ ms_deformable_im2col_cuda(at::cuda::getCurrentCUDAStream(),
+ value.data_ptr() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data_ptr(),
+ level_start_index.data_ptr(),
+ sampling_loc.data_ptr() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data_ptr() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ columns.data_ptr());
+
+ }));
+ }
+
+ output = output.view({batch, num_query, num_heads*channels});
+
+ return output;
+}
+
+
+std::vector ms_deform_attn_cuda_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+ at::DeviceGuard guard(value.device());
+
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+ AT_ASSERTM(grad_output.is_contiguous(), "grad_output tensor has to be contiguous");
+
+ AT_ASSERTM(value.is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.is_cuda(), "attn_weight must be a CUDA tensor");
+ AT_ASSERTM(grad_output.is_cuda(), "grad_output must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto grad_value = at::zeros_like(value);
+ auto grad_sampling_loc = at::zeros_like(sampling_loc);
+ auto grad_attn_weight = at::zeros_like(attn_weight);
+
+ const int batch_n = im2col_step_;
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ auto grad_output_n = grad_output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto grad_output_g = grad_output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, value.scalar_type(), "ms_deform_attn_backward_cuda", ([&] {
+ ms_deformable_col2im_cuda(at::cuda::getCurrentCUDAStream(),
+ grad_output_g.data_ptr(),
+ value.data_ptr() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data_ptr(),
+ level_start_index.data_ptr(),
+ sampling_loc.data_ptr() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data_ptr() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ grad_value.data_ptr() + n * im2col_step_ * per_value_size,
+ grad_sampling_loc.data_ptr() + n * im2col_step_ * per_sample_loc_size,
+ grad_attn_weight.data_ptr() + n * im2col_step_ * per_attn_weight_size);
+
+ }));
+ }
+
+ return {
+ grad_value, grad_sampling_loc, grad_attn_weight
+ };
+}
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cuh b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cuh
new file mode 100644
index 0000000000000000000000000000000000000000..20ae6892e4b9881578a72aae27ddc4ec9f68ae1c
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cuh
@@ -0,0 +1,1467 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include
+
+#include
+#include
+
+#include
+#include
+#include
+
+#include
+#include
+
+#include
+
+#define CUDA_KERNEL_LOOP(i, n) \
+ for (int i = blockIdx.x * blockDim.x + threadIdx.x; \
+ i < (n); \
+ i += blockDim.x * gridDim.x)
+
+
+at::Tensor ms_deform_attn_cuda_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+
+ AT_ASSERTM(value.is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.is_cuda(), "attn_weight must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto output = at::zeros({batch, num_query, num_heads, channels}, value.options());
+
+ const int batch_n = im2col_step_;
+ auto output_n = output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto columns = output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, value.scalar_type(), "ms_deform_attn_forward_cuda", ([&] {
+ ms_deformable_im2col_cuda(at::cuda::getCurrentCUDAStream(),
+ value.data_ptr() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data_ptr(),
+ level_start_index.data_ptr(),
+ sampling_loc.data_ptr() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data_ptr() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ columns.data_ptr());
+
+ }));
+ }
+
+ output = output.view({batch, num_query, num_heads*channels});
+
+ return output;
+}
+
+
+std::vector ms_deform_attn_cuda_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+ AT_ASSERTM(grad_output.is_contiguous(), "grad_output tensor has to be contiguous");
+
+ AT_ASSERTM(value.is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.is_cuda(), "attn_weight must be a CUDA tensor");
+ AT_ASSERTM(grad_output.is_cuda(), "grad_output must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto grad_value = at::zeros_like(value);
+ auto grad_sampling_loc = at::zeros_like(sampling_loc);
+ auto grad_attn_weight = at::zeros_like(attn_weight);
+
+ const int batch_n = im2col_step_;
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ auto grad_output_n = grad_output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto grad_output_g = grad_output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, value.scalar_type(), "ms_deform_attn_backward_cuda", ([&] {
+ ms_deformable_col2im_cuda(at::cuda::getCurrentCUDAStream(),
+ grad_output_g.data_ptr(),
+ value.data_ptr() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data_ptr(),
+ level_start_index.data_ptr(),
+ sampling_loc.data_ptr() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data_ptr() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ grad_value.data_ptr() + n * im2col_step_ * per_value_size,
+ grad_sampling_loc.data_ptr() + n * im2col_step_ * per_sample_loc_size,
+ grad_attn_weight.data_ptr() + n * im2col_step_ * per_attn_weight_size);
+
+ }));
+ }
+
+ return {
+ grad_value, grad_sampling_loc, grad_attn_weight
+ };
+}
+
+const int CUDA_NUM_THREADS = 1024;
+inline int GET_BLOCKS(const int N, const int num_threads)
+{
+ return (N + num_threads - 1) / num_threads;
+}
+
+
+template
+__device__ scalar_t ms_deform_attn_im2col_bilinear(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ }
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ return val;
+}
+
+
+template
+__device__ void ms_deform_attn_col2im_bilinear(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
+ const scalar_t &top_grad,
+ const scalar_t &attn_weight,
+ scalar_t* &grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ *grad_attn_weight = top_grad * val;
+ *grad_sampling_loc = width * grad_w_weight * top_grad_value;
+ *(grad_sampling_loc + 1) = height * grad_h_weight * top_grad_value;
+}
+
+
+template
+__device__ void ms_deform_attn_col2im_bilinear_gm(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
+ const scalar_t &top_grad,
+ const scalar_t &attn_weight,
+ scalar_t* &grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ atomicAdd(grad_attn_weight, top_grad * val);
+ atomicAdd(grad_sampling_loc, width * grad_w_weight * top_grad_value);
+ atomicAdd(grad_sampling_loc + 1, height * grad_h_weight * top_grad_value);
+}
+
+
+template
+__global__ void ms_deformable_im2col_gpu_kernel(const int n,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *data_col)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ scalar_t *data_col_ptr = data_col + index;
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+ scalar_t col = 0;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const scalar_t *data_value_ptr = data_value + (data_value_ptr_init_offset + level_start_id * qid_stride);
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ col += ms_deform_attn_im2col_bilinear(data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col) * weight;
+ }
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ }
+ }
+ *data_col_ptr = col;
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0)
+ {
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
+ int sid=2;
+ for (unsigned int tid = 1; tid < blockSize; ++tid)
+ {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockSize/2; s>0; s>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v1(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0)
+ {
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
+ int sid=2;
+ for (unsigned int tid = 1; tid < blockDim.x; ++tid)
+ {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre)
+ {
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre)
+ {
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ atomicAdd(grad_sampling_loc, cache_grad_sampling_loc[0]);
+ atomicAdd(grad_sampling_loc + 1, cache_grad_sampling_loc[1]);
+ atomicAdd(grad_attn_weight, cache_grad_attn_weight[0]);
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_gm(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear_gm(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ grad_sampling_loc, grad_attn_weight);
+ }
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+void ms_deformable_im2col_cuda(cudaStream_t stream,
+ const scalar_t* data_value,
+ const int64_t* data_spatial_shapes,
+ const int64_t* data_level_start_index,
+ const scalar_t* data_sampling_loc,
+ const scalar_t* data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t* data_col)
+{
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ const int num_threads = CUDA_NUM_THREADS;
+ ms_deformable_im2col_gpu_kernel
+ <<>>(
+ num_kernels, data_value, data_spatial_shapes, data_level_start_index, data_sampling_loc, data_attn_weight,
+ batch_size, spatial_size, num_heads, channels, num_levels, num_query, num_point, data_col);
+
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess)
+ {
+ printf("error in ms_deformable_im2col_cuda: %s\n", cudaGetErrorString(err));
+ }
+
+}
+
+template
+void ms_deformable_col2im_cuda(cudaStream_t stream,
+ const scalar_t* grad_col,
+ const scalar_t* data_value,
+ const int64_t * data_spatial_shapes,
+ const int64_t * data_level_start_index,
+ const scalar_t * data_sampling_loc,
+ const scalar_t * data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t* grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int num_threads = (channels > CUDA_NUM_THREADS)?CUDA_NUM_THREADS:channels;
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ if (channels > 1024)
+ {
+ if ((channels & 1023) == 0)
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ else
+ {
+ ms_deformable_col2im_gpu_kernel_gm
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ }
+ else{
+ switch(channels)
+ {
+ case 1:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 2:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 4:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 8:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 16:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 32:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 64:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 128:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 256:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 512:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 1024:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ default:
+ if (channels < 64)
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ else
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ }
+ }
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess)
+ {
+ printf("error in ms_deformable_col2im_cuda: %s\n", cudaGetErrorString(err));
+ }
+
+}
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.h b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.h
new file mode 100644
index 0000000000000000000000000000000000000000..d8c21b4e54dcd7071f5fd27f62410326ac069a94
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.h
@@ -0,0 +1,46 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#pragma once
+#include
+
+at::Tensor ms_deform_attn_cuda_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step);
+
+at::Tensor ms_deform_attn_cuda_forward_bf16(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step);
+
+std::vector ms_deform_attn_cuda_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step);
+
+std::vector ms_deform_attn_cuda_backward_bf16(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step);
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh
new file mode 100644
index 0000000000000000000000000000000000000000..4fb544bf791ddae79238924df591b7a33f3cccdd
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh
@@ -0,0 +1,1327 @@
+/*!
+**************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************
+* Modified from DCN (https://github.com/msracver/Deformable-ConvNets)
+* Copyright (c) 2018 Microsoft
+**************************************************************************
+*/
+
+#include
+#include
+#include
+
+#include
+#include
+
+#include
+
+#define CUDA_KERNEL_LOOP(i, n) \
+ for (int i = blockIdx.x * blockDim.x + threadIdx.x; \
+ i < (n); \
+ i += blockDim.x * gridDim.x)
+
+const int CUDA_NUM_THREADS = 1024;
+inline int GET_BLOCKS(const int N, const int num_threads)
+{
+ return (N + num_threads - 1) / num_threads;
+}
+
+
+template
+__device__ scalar_t ms_deform_attn_im2col_bilinear(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ }
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ return val;
+}
+
+
+template
+__device__ void ms_deform_attn_col2im_bilinear(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
+ const scalar_t &top_grad,
+ const scalar_t &attn_weight,
+ scalar_t* &grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ *grad_attn_weight = top_grad * val;
+ *grad_sampling_loc = width * grad_w_weight * top_grad_value;
+ *(grad_sampling_loc + 1) = height * grad_h_weight * top_grad_value;
+}
+
+
+template
+__device__ void ms_deform_attn_col2im_bilinear_gm(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
+ const scalar_t &top_grad,
+ const scalar_t &attn_weight,
+ scalar_t* &grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ atomicAdd(grad_attn_weight, top_grad * val);
+ atomicAdd(grad_sampling_loc, width * grad_w_weight * top_grad_value);
+ atomicAdd(grad_sampling_loc + 1, height * grad_h_weight * top_grad_value);
+}
+
+
+template
+__global__ void ms_deformable_im2col_gpu_kernel(const int n,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *data_col)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ scalar_t *data_col_ptr = data_col + index;
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+ scalar_t col = 0;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const scalar_t *data_value_ptr = data_value + (data_value_ptr_init_offset + level_start_id * qid_stride);
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ col += ms_deform_attn_im2col_bilinear(data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col) * weight;
+ }
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ }
+ }
+ *data_col_ptr = col;
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0)
+ {
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
+ int sid=2;
+ for (unsigned int tid = 1; tid < blockSize; ++tid)
+ {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockSize/2; s>0; s>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v1(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0)
+ {
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
+ int sid=2;
+ for (unsigned int tid = 1; tid < blockDim.x; ++tid)
+ {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre)
+ {
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre)
+ {
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ atomicAdd(grad_sampling_loc, cache_grad_sampling_loc[0]);
+ atomicAdd(grad_sampling_loc + 1, cache_grad_sampling_loc[1]);
+ atomicAdd(grad_attn_weight, cache_grad_attn_weight[0]);
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_gm(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ [[maybe_unused]] const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear_gm(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ grad_sampling_loc, grad_attn_weight);
+ }
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+void ms_deformable_im2col_cuda(cudaStream_t stream,
+ const scalar_t* data_value,
+ const int64_t* data_spatial_shapes,
+ const int64_t* data_level_start_index,
+ const scalar_t* data_sampling_loc,
+ const scalar_t* data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t* data_col)
+{
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ const int num_threads = CUDA_NUM_THREADS;
+ ms_deformable_im2col_gpu_kernel
+ <<>>(
+ num_kernels, data_value, data_spatial_shapes, data_level_start_index, data_sampling_loc, data_attn_weight,
+ batch_size, spatial_size, num_heads, channels, num_levels, num_query, num_point, data_col);
+
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess)
+ {
+ printf("error in ms_deformable_im2col_cuda: %s\n", cudaGetErrorString(err));
+ }
+
+}
+
+template
+void ms_deformable_col2im_cuda(cudaStream_t stream,
+ const scalar_t* grad_col,
+ const scalar_t* data_value,
+ const int64_t * data_spatial_shapes,
+ const int64_t * data_level_start_index,
+ const scalar_t * data_sampling_loc,
+ const scalar_t * data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t* grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int num_threads = (channels > CUDA_NUM_THREADS)?CUDA_NUM_THREADS:channels;
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ if (channels > 1024)
+ {
+ if ((channels & 1023) == 0)
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ else
+ {
+ ms_deformable_col2im_gpu_kernel_gm
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ }
+ else{
+ switch(channels)
+ {
+ case 1:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 2:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 4:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 8:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 16:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 32:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 64:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 128:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 256:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 512:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 1024:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ default:
+ if (channels < 64)
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ else
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ }
+ }
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess)
+ {
+ printf("error in ms_deformable_col2im_cuda: %s\n", cudaGetErrorString(err));
+ }
+
+}
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/ms_deform_attn.h b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/ms_deform_attn.h
new file mode 100644
index 0000000000000000000000000000000000000000..e649e65e37ae58d789a4cfb396e715ff2e33477f
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/ms_deform_attn.h
@@ -0,0 +1,61 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#pragma once
+
+#include "cpu/ms_deform_attn_cpu.h"
+
+#ifdef WITH_CUDA
+#include "cuda/ms_deform_attn_cuda.h"
+#endif
+
+
+at::Tensor
+ms_deform_attn_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ if (value.is_cuda())
+ {
+#ifdef WITH_CUDA
+ return ms_deform_attn_cuda_forward(
+ value, spatial_shapes, level_start_index, sampling_loc, attn_weight, im2col_step);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ }
+ AT_ERROR("Not implemented on the CPU");
+}
+
+std::vector
+ms_deform_attn_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+ if (value.is_cuda())
+ {
+#ifdef WITH_CUDA
+ return ms_deform_attn_cuda_backward(
+ value, spatial_shapes, level_start_index, sampling_loc, attn_weight, grad_output, im2col_step);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ }
+ AT_ERROR("Not implemented on the CPU");
+}
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/vision.cpp b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/vision.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..6ce3875568b9ba8d660c90acc805077cca98f891
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deformable_detr/vision.cpp
@@ -0,0 +1,16 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include "ms_deform_attn.h"
+
+PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
+ m.def("ms_deform_attn_forward", &ms_deform_attn_forward, "ms_deform_attn_forward");
+ m.def("ms_deform_attn_backward", &ms_deform_attn_backward, "ms_deform_attn_backward");
+}
\ No newline at end of file
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deta/cpu/ms_deform_attn_cpu.cpp b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deta/cpu/ms_deform_attn_cpu.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..388a73d22d4c9b561e2a887b50a1897b8cf2def9
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deta/cpu/ms_deform_attn_cpu.cpp
@@ -0,0 +1,40 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include
+
+#include
+#include
+
+
+at::Tensor
+ms_deform_attn_cpu_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ AT_ERROR("Not implement on cpu");
+}
+
+std::vector
+ms_deform_attn_cpu_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+ AT_ERROR("Not implement on cpu");
+}
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deta/cpu/ms_deform_attn_cpu.h b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deta/cpu/ms_deform_attn_cpu.h
new file mode 100644
index 0000000000000000000000000000000000000000..7eac8c8bcd1bf529bb9c13d54d2d4215c9e4c89f
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deta/cpu/ms_deform_attn_cpu.h
@@ -0,0 +1,32 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#pragma once
+#include
+
+at::Tensor
+ms_deform_attn_cpu_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step);
+
+std::vector
+ms_deform_attn_cpu_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step);
+
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.cu b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.cu
new file mode 100644
index 0000000000000000000000000000000000000000..8ea1d7fabe2684dbb85f00fae2c47b469687cb2c
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.cu
@@ -0,0 +1,156 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include
+#include "cuda/ms_deform_im2col_cuda.cuh"
+
+#include
+#include
+#include
+#include
+
+#pragma once
+#include
+
+
+at::Tensor ms_deform_attn_cuda_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+
+ AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.type().is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto output = at::zeros({batch, num_query, num_heads, channels}, value.options());
+
+ const int batch_n = im2col_step_;
+ auto output_n = output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto columns = output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES(value.type(), "ms_deform_attn_forward_cuda", ([&] {
+ ms_deformable_im2col_cuda(at::cuda::getCurrentCUDAStream(),
+ value.data() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data(),
+ level_start_index.data(),
+ sampling_loc.data() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ columns.data());
+
+ }));
+ }
+
+ output = output.view({batch, num_query, num_heads*channels});
+
+ return output;
+}
+
+
+std::vector ms_deform_attn_cuda_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+ AT_ASSERTM(grad_output.is_contiguous(), "grad_output tensor has to be contiguous");
+
+ AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.type().is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
+ AT_ASSERTM(grad_output.type().is_cuda(), "grad_output must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto grad_value = at::zeros_like(value);
+ auto grad_sampling_loc = at::zeros_like(sampling_loc);
+ auto grad_attn_weight = at::zeros_like(attn_weight);
+
+ const int batch_n = im2col_step_;
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ auto grad_output_n = grad_output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto grad_output_g = grad_output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES(value.type(), "ms_deform_attn_backward_cuda", ([&] {
+ ms_deformable_col2im_cuda(at::cuda::getCurrentCUDAStream(),
+ grad_output_g.data(),
+ value.data() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data(),
+ level_start_index.data(),
+ sampling_loc.data() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ grad_value.data() + n * im2col_step_ * per_value_size,
+ grad_sampling_loc.data() + n * im2col_step_ * per_sample_loc_size,
+ grad_attn_weight.data() + n * im2col_step_ * per_attn_weight_size);
+
+ }));
+ }
+
+ return {
+ grad_value, grad_sampling_loc, grad_attn_weight
+ };
+}
diff --git a/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.cuh b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.cuh
new file mode 100644
index 0000000000000000000000000000000000000000..34f8ae9cb77bbaa8cb4dd25e0cb86632db9ad05d
--- /dev/null
+++ b/tasks/tasksmith-441eeab80047/environment/source/src/transformers/kernels/deta/cuda/ms_deform_attn_cuda.cuh
@@ -0,0 +1,1467 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include
+
+#include
+#include
+
+#include
+#include
+#include
+
+#include
+#include
+
+#include
+
+#define CUDA_KERNEL_LOOP(i, n) \
+ for (int i = blockIdx.x * blockDim.x + threadIdx.x; \
+ i < (n); \
+ i += blockDim.x * gridDim.x)
+
+
+at::Tensor ms_deform_attn_cuda_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+
+ AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.type().is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto output = at::zeros({batch, num_query, num_heads, channels}, value.options());
+
+ const int batch_n = im2col_step_;
+ auto output_n = output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto columns = output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES(value.type(), "ms_deform_attn_forward_cuda", ([&] {
+ ms_deformable_im2col_cuda(at::cuda::getCurrentCUDAStream(),
+ value.data() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data(),
+ level_start_index.data(),
+ sampling_loc.data() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ columns.data());
+
+ }));
+ }
+
+ output = output.view({batch, num_query, num_heads*channels});
+
+ return output;
+}
+
+
+std::vector ms_deform_attn_cuda_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+ AT_ASSERTM(grad_output.is_contiguous(), "grad_output tensor has to be contiguous");
+
+ AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.type().is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
+ AT_ASSERTM(grad_output.type().is_cuda(), "grad_output must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto grad_value = at::zeros_like(value);
+ auto grad_sampling_loc = at::zeros_like(sampling_loc);
+ auto grad_attn_weight = at::zeros_like(attn_weight);
+
+ const int batch_n = im2col_step_;
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ auto grad_output_n = grad_output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto grad_output_g = grad_output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES(value.type(), "ms_deform_attn_backward_cuda", ([&] {
+ ms_deformable_col2im_cuda(at::cuda::getCurrentCUDAStream(),
+ grad_output_g.data(),
+ value.data() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data(),
+ level_start_index.data(),
+ sampling_loc.data() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ grad_value.data() + n * im2col_step_ * per_value_size,
+ grad_sampling_loc.data() + n * im2col_step_ * per_sample_loc_size,
+ grad_attn_weight.data() + n * im2col_step_ * per_attn_weight_size);
+
+ }));
+ }
+
+ return {
+ grad_value, grad_sampling_loc, grad_attn_weight
+ };
+}
+
+const int CUDA_NUM_THREADS = 1024;
+inline int GET_BLOCKS(const int N, const int num_threads)
+{
+ return (N + num_threads - 1) / num_threads;
+}
+
+
+template
+__device__ scalar_t ms_deform_attn_im2col_bilinear(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ }
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ return val;
+}
+
+
+template
+__device__ void ms_deform_attn_col2im_bilinear(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
+ const scalar_t &top_grad,
+ const scalar_t &attn_weight,
+ scalar_t* &grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ *grad_attn_weight = top_grad * val;
+ *grad_sampling_loc = width * grad_w_weight * top_grad_value;
+ *(grad_sampling_loc + 1) = height * grad_h_weight * top_grad_value;
+}
+
+
+template
+__device__ void ms_deform_attn_col2im_bilinear_gm(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
+ const scalar_t &top_grad,
+ const scalar_t &attn_weight,
+ scalar_t* &grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ atomicAdd(grad_attn_weight, top_grad * val);
+ atomicAdd(grad_sampling_loc, width * grad_w_weight * top_grad_value);
+ atomicAdd(grad_sampling_loc + 1, height * grad_h_weight * top_grad_value);
+}
+
+
+template
+__global__ void ms_deformable_im2col_gpu_kernel(const int n,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *data_col)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ scalar_t *data_col_ptr = data_col + index;
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+ scalar_t col = 0;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const scalar_t *data_value_ptr = data_value + (data_value_ptr_init_offset + level_start_id * qid_stride);
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ col += ms_deform_attn_im2col_bilinear(data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col) * weight;
+ }
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ }
+ }
+ *data_col_ptr = col;
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0)
+ {
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
+ int sid=2;
+ for (unsigned int tid = 1; tid < blockSize; ++tid)
+ {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockSize/2; s>0; s>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v1(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0)
+ {
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
+ int sid=2;
+ for (unsigned int tid = 1; tid < blockDim.x; ++tid)
+ {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre)
+ {
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre)
+ {
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ atomicAdd(grad_sampling_loc, cache_grad_sampling_loc[0]);
+ atomicAdd(grad_sampling_loc + 1, cache_grad_sampling_loc[1]);
+ atomicAdd(grad_attn_weight, cache_grad_attn_weight[0]);
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_gm(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear_gm(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ grad_sampling_loc, grad_attn_weight);
+ }
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+void ms_deformable_im2col_cuda(cudaStream_t stream,
+ const scalar_t* data_value,
+ const int64_t* data_spatial_shapes,
+ const int64_t* data_level_start_index,
+ const scalar_t* data_sampling_loc,
+ const scalar_t* data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t* data_col)
+{
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ const int num_threads = CUDA_NUM_THREADS;
+ ms_deformable_im2col_gpu_kernel
+ <<>>(
+ num_kernels, data_value, data_spatial_shapes, data_level_start_index, data_sampling_loc, data_attn_weight,
+ batch_size, spatial_size, num_heads, channels, num_levels, num_query, num_point, data_col);
+
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess)
+ {
+ printf("error in ms_deformable_im2col_cuda: %s\n", cudaGetErrorString(err));
+ }
+
+}
+
+template
+void ms_deformable_col2im_cuda(cudaStream_t stream,
+ const scalar_t* grad_col,
+ const scalar_t* data_value,
+ const int64_t * data_spatial_shapes,
+ const int64_t * data_level_start_index,
+ const scalar_t * data_sampling_loc,
+ const scalar_t * data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t* grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int num_threads = (channels > CUDA_NUM_THREADS)?CUDA_NUM_THREADS:channels;
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ if (channels > 1024)
+ {
+ if ((channels & 1023) == 0)
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ else
+ {
+ ms_deformable_col2im_gpu_kernel_gm
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ }
+ else{
+ switch(channels)
+ {
+ case 1:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 2:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 4:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 8:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 16:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 32:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 64:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 128:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 256:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 512:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2