`."
+ ) from e
+ except RepositoryNotFoundError as e:
+ logger.error(e)
+ raise OSError(f"{path_or_repo} is not a local folder or a valid repository name on 'https://hf.co'.") from e
+ except RevisionNotFoundError as e:
+ logger.error(e)
+ raise OSError(
+ f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for this "
+ f"model name. Check the model page at 'https://huggingface.co/{path_or_repo}' for available revisions."
+ ) from e
+ except EntryNotFoundError:
+ return False # File does not exist
+ except HfHubHTTPError:
+ # Any authentication/authorization error will be caught here => default to cache
+ return has_file_in_cache
+
+
+class PushToHubMixin:
+ """
+ A Mixin containing the functionality to push a model or tokenizer to the hub.
+ """
+
+ def _get_files_timestamps(self, working_dir: str | os.PathLike):
+ """
+ Returns the list of files with their last modification timestamp.
+ """
+ return {f: os.path.getmtime(os.path.join(working_dir, f)) for f in os.listdir(working_dir)}
+
+ def _upload_modified_files(
+ self,
+ working_dir: str | os.PathLike,
+ repo_id: str,
+ files_timestamps: dict[str, float],
+ commit_message: str | None = None,
+ token: bool | str | None = None,
+ create_pr: bool = False,
+ revision: str | None = None,
+ commit_description: str | None = None,
+ ):
+ """
+ Uploads all modified files in `working_dir` to `repo_id`, based on `files_timestamps`.
+ """
+ if commit_message is None:
+ if "Model" in self.__class__.__name__:
+ commit_message = "Upload model"
+ elif "Config" in self.__class__.__name__:
+ commit_message = "Upload config"
+ elif "Tokenizer" in self.__class__.__name__:
+ commit_message = "Upload tokenizer"
+ elif "FeatureExtractor" in self.__class__.__name__:
+ commit_message = "Upload feature extractor"
+ elif "Processor" in self.__class__.__name__:
+ commit_message = "Upload processor"
+ else:
+ commit_message = f"Upload {self.__class__.__name__}"
+ modified_files = [
+ f
+ for f in os.listdir(working_dir)
+ if f not in files_timestamps or os.path.getmtime(os.path.join(working_dir, f)) > files_timestamps[f]
+ ]
+
+ # filter for actual files + folders at the root level
+ modified_files = [
+ f
+ for f in modified_files
+ if os.path.isfile(os.path.join(working_dir, f)) or os.path.isdir(os.path.join(working_dir, f))
+ ]
+
+ operations = []
+ # upload standalone files
+ for file in modified_files:
+ if os.path.isdir(os.path.join(working_dir, file)):
+ # go over individual files of folder
+ for f in os.listdir(os.path.join(working_dir, file)):
+ operations.append(
+ CommitOperationAdd(
+ path_or_fileobj=os.path.join(working_dir, file, f), path_in_repo=os.path.join(file, f)
+ )
+ )
+ else:
+ operations.append(
+ CommitOperationAdd(path_or_fileobj=os.path.join(working_dir, file), path_in_repo=file)
+ )
+
+ if revision is not None and not revision.startswith("refs/pr"):
+ try:
+ create_branch(repo_id=repo_id, branch=revision, token=token, exist_ok=True)
+ except HfHubHTTPError as e:
+ if e.response.status_code == 403 and create_pr:
+ # If we are creating a PR on a repo we don't have access to, we can't create the branch.
+ # so let's assume the branch already exists. If it's not the case, an error will be raised when
+ # calling `create_commit` below.
+ pass
+ else:
+ raise
+
+ logger.info(f"Uploading the following files to {repo_id}: {','.join(modified_files)}")
+ return create_commit(
+ repo_id=repo_id,
+ operations=operations,
+ commit_message=commit_message,
+ commit_description=commit_description,
+ token=token,
+ create_pr=create_pr,
+ revision=revision,
+ )
+
+ def save_pretrained(self, *args, **kwargs):
+ # explicit contract
+ raise NotImplementedError(f"{self.__class__.__name__} must implement `save_pretrained` to use `push_to_hub`.")
+
+ def push_to_hub(
+ self,
+ repo_id: str,
+ *,
+ # Commit details
+ commit_message: str | None = None,
+ commit_description: str | None = None,
+ # Repo / upload details
+ private: bool | None = None,
+ token: bool | str | None = None,
+ revision: str | None = None,
+ create_pr: bool = False,
+ # Serialization details
+ max_shard_size: int | str | None = "50GB",
+ tags: list[str] | None = None,
+ ) -> str:
+ """
+ Upload the {object_files} to the 🤗 Model Hub.
+
+ Parameters:
+ repo_id (`str`):
+ The name of the repository you want to push your {object} to. It should contain your organization name
+ when pushing to a given organization.
+ commit_message (`str`, *optional*):
+ Message to commit while pushing. Will default to `"Upload {object}"`.
+ commit_description (`str`, *optional*):
+ The description of the commit that will be created
+ private (`bool`, *optional*):
+ Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
+ token (`bool` or `str`, *optional*):
+ The token to use as HTTP bearer authorization for remote files. If `True` (default), will use the token generated
+ when running `hf auth login` (stored in `~/.huggingface`).
+ revision (`str`, *optional*):
+ Branch to push the uploaded files to.
+ create_pr (`bool`, *optional*, defaults to `False`):
+ Whether or not to create a PR with the uploaded files or directly commit.
+ max_shard_size (`int` or `str`, *optional*, defaults to `"50GB"`):
+ Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard
+ will then be each of size lower than this size. If expressed as a string, needs to be digits followed
+ by a unit (like `"5MB"`).
+ tags (`list[str]`, *optional*):
+ List of tags to push on the Hub.
+
+ Examples:
+
+ ```python
+ from transformers import {object_class}
+
+ {object} = {object_class}.from_pretrained("google-bert/bert-base-cased")
+
+ # Push the {object} to your namespace with the name "my-finetuned-bert".
+ {object}.push_to_hub("my-finetuned-bert")
+
+ # Push the {object} to an organization with the name "my-finetuned-bert".
+ {object}.push_to_hub("huggingface/my-finetuned-bert")
+ ```
+ """
+ # Create repo if it doesn't exist yet
+ repo_id = create_repo(repo_id, private=private, token=token, exist_ok=True).repo_id
+
+ # Load model card or create a new one + eventually tag it
+ model_card = create_and_tag_model_card(repo_id, tags, token=token)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ # Save all files.
+ self.save_pretrained(tmp_dir, max_shard_size=max_shard_size)
+
+ # Update model card
+ model_card.save(os.path.join(tmp_dir, "README.md"))
+
+ # Upload
+ return self._upload_modified_files(
+ tmp_dir,
+ repo_id,
+ files_timestamps={},
+ commit_message=commit_message,
+ token=token,
+ create_pr=create_pr,
+ revision=revision,
+ commit_description=commit_description,
+ )
+
+
+def convert_file_size_to_int(size: int | str):
+ """
+ Converts a size expressed as a string with digits an unit (like `"5MB"`) to an integer (in bytes).
+
+ Args:
+ size (`int` or `str`): The size to convert. Will be directly returned if an `int`.
+
+ Example:
+ ```py
+ >>> convert_file_size_to_int("1MiB")
+ 1048576
+ ```
+ """
+ if isinstance(size, int):
+ return size
+ if size.upper().endswith("GIB"):
+ return int(size[:-3]) * (2**30)
+ if size.upper().endswith("MIB"):
+ return int(size[:-3]) * (2**20)
+ if size.upper().endswith("KIB"):
+ return int(size[:-3]) * (2**10)
+ if size.upper().endswith("GB"):
+ int_size = int(size[:-2]) * (10**9)
+ return int_size // 8 if size.endswith("b") else int_size
+ if size.upper().endswith("MB"):
+ int_size = int(size[:-2]) * (10**6)
+ return int_size // 8 if size.endswith("b") else int_size
+ if size.upper().endswith("KB"):
+ int_size = int(size[:-2]) * (10**3)
+ return int_size // 8 if size.endswith("b") else int_size
+ raise ValueError("`size` is not in a valid format. Use an integer followed by the unit, e.g., '5GB'.")
+
+
+def get_checkpoint_shard_files(
+ pretrained_model_name_or_path,
+ index_filename,
+ cache_dir=None,
+ force_download=False,
+ proxies=None,
+ local_files_only=False,
+ token=None,
+ user_agent=None,
+ revision=None,
+ subfolder="",
+ _commit_hash=None,
+ **deprecated_kwargs,
+):
+ """
+ For a given model:
+
+ - download and cache all the shards of a sharded checkpoint if `pretrained_model_name_or_path` is a model ID on the
+ Hub
+ - returns the list of paths to all the shards, as well as some metadata.
+
+ For the description of each arg, see [`PreTrainedModel.from_pretrained`]. `index_filename` is the full path to the
+ index (downloaded and cached if `pretrained_model_name_or_path` is a model ID on the Hub).
+ """
+ if not os.path.isfile(index_filename):
+ raise ValueError(f"Can't find a checkpoint index ({index_filename}) in {pretrained_model_name_or_path}.")
+
+ with open(index_filename) as f:
+ index = json.loads(f.read())
+
+ shard_filenames = sorted(set(index["weight_map"].values()))
+ sharded_metadata = index["metadata"]
+ sharded_metadata["all_checkpoint_keys"] = list(index["weight_map"].keys())
+ sharded_metadata["weight_map"] = index["weight_map"].copy()
+
+ # First, let's deal with local folder.
+ if os.path.isdir(pretrained_model_name_or_path):
+ shard_filenames = [os.path.join(pretrained_model_name_or_path, subfolder, f) for f in shard_filenames]
+ return shard_filenames, sharded_metadata
+
+ # At this stage pretrained_model_name_or_path is a model identifier on the Hub. Try to get everything from cache,
+ # or download the files
+ cached_filenames = cached_files(
+ pretrained_model_name_or_path,
+ shard_filenames,
+ cache_dir=cache_dir,
+ force_download=force_download,
+ proxies=proxies,
+ local_files_only=local_files_only,
+ token=token,
+ user_agent=user_agent,
+ revision=revision,
+ subfolder=subfolder,
+ _commit_hash=_commit_hash,
+ )
+
+ return cached_filenames, sharded_metadata
+
+
+def create_and_tag_model_card(repo_id: str, tags: list[str] | None = None, token: str | None = None) -> ModelCard:
+ """
+ Creates or loads an existing model card and tags it.
+
+ Args:
+ repo_id (`str`):
+ The repo_id where to look for the model card.
+ tags (`list[str]`, *optional*):
+ The list of tags to add in the model card
+ token (`str`, *optional*):
+ Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to the stored token.
+ """
+ try:
+ # Check if the model card is present on the remote repo
+ model_card = ModelCard.load(repo_id, token=token)
+ except EntryNotFoundError:
+ # Otherwise create a simple model card from template
+ model_description = "This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated."
+ card_data = ModelCardData(tags=[] if tags is None else tags, library_name="transformers")
+ model_card = ModelCard.from_template(card_data, model_description=model_description)
+
+ if tags is not None:
+ # Ensure model_card.data.tags is a list and not None
+ if model_card.data.tags is None:
+ model_card.data.tags = []
+ for model_tag in tags:
+ if model_tag not in model_card.data.tags:
+ model_card.data.tags.append(model_tag)
+
+ return model_card
+
+
+class PushInProgress:
+ """
+ Internal class to keep track of a push in progress (which might contain multiple `Future` jobs).
+ """
+
+ def __init__(self, jobs: futures.Future | None = None) -> None:
+ self.jobs = [] if jobs is None else jobs
+
+ def is_done(self):
+ return all(job.done() for job in self.jobs)
+
+ def wait_until_done(self):
+ futures.wait(self.jobs)
+
+ def cancel(self) -> None:
+ self.jobs = [
+ job
+ for job in self.jobs
+ # Cancel the job if it wasn't started yet and remove cancelled/done jobs from the list
+ if not (job.cancel() or job.done())
+ ]
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/import_utils.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/import_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..eee9945df85316a8d6a6443c8b4bca55665430b8
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/import_utils.py
@@ -0,0 +1,2846 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Import utilities: Utilities related to imports and our lazy inits.
+"""
+
+import importlib.machinery
+import importlib.metadata
+import importlib.util
+import json
+import operator
+import os
+import re
+import shutil
+import subprocess
+import sys
+from collections import OrderedDict
+from collections.abc import Callable
+from enum import Enum
+from functools import lru_cache
+from itertools import chain
+from types import ModuleType
+from typing import Any
+
+import packaging.version
+from packaging import version
+
+from . import logging
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+PACKAGE_DISTRIBUTION_MAPPING = importlib.metadata.packages_distributions()
+
+
+def _is_package_available(pkg_name: str, return_version: bool = False) -> tuple[bool, str]:
+ """Check if `pkg_name` exist, and optionally try to get its version"""
+ spec = importlib.util.find_spec(pkg_name)
+ package_exists = spec is not None
+ package_version = "N/A"
+ if package_exists and return_version:
+ try:
+ # importlib.metadata works with the distribution package, which may be different from the import
+ # name (e.g. `PIL` is the import name, but `pillow` is the distribution name)
+ distributions = PACKAGE_DISTRIBUTION_MAPPING[pkg_name]
+ # Per PEP 503, underscores and hyphens are equivalent in package names.
+ # Prefer the distribution that matches the (normalized) package name.
+ normalized_pkg_name = pkg_name.replace("_", "-")
+ if normalized_pkg_name in distributions:
+ distribution_name = normalized_pkg_name
+ elif pkg_name in distributions:
+ distribution_name = pkg_name
+ else:
+ distribution_name = distributions[0]
+ package_version = importlib.metadata.version(distribution_name)
+ except (importlib.metadata.PackageNotFoundError, KeyError):
+ # If we cannot find the metadata (because of editable install for example), try to import directly.
+ # Note that this branch will almost never be run, so we do not import packages for nothing here
+ package = importlib.import_module(pkg_name)
+ package_version = getattr(package, "__version__", "N/A")
+ logger.debug(f"Detected {pkg_name} version: {package_version}")
+
+ if return_version:
+ return package_exists, package_version
+ else:
+ return package_exists, None
+
+
+def resolve_internal_import(module: ModuleType | None, chained_path: str) -> Callable | ModuleType | None:
+ """
+ Check if a given `module` has an internal import path as defined by the `chained_path`.
+ This can either be the full path (not exposed in `__init__`) OR the last part of the chain (exposed in `__init__`).
+
+ This is an important helper function for kernels based modules to apply the import from the module
+ itself, i.e. stay compatible with original libraries in certain cases.
+
+ Example:
+ Module: `mamba_ssm`
+ Chained Path: `ops.triton.selective_state_update.selective_state_update`
+ Resulting import attempt at:
+ - `mamba_ssm.selective_state_update`
+ - `mamba_ssm.ops.triton.selective_state_update.selective_state_update`
+ """
+ if not module:
+ return None
+
+ if final_module := getattr(module, chained_path.split(".")[-1], None):
+ return final_module
+
+ final_module = module
+ for path in chained_path.split("."):
+ final_module = getattr(final_module, path, None)
+ if not final_module:
+ return None
+
+ return final_module
+
+
+def is_env_variable_true(env_variable: str) -> bool:
+ """Detect whether `env_variable` has been set to a true value in the environment"""
+ return os.getenv(env_variable, "false").lower() in ("true", "1", "y", "yes", "on")
+
+
+def is_env_variable_false(env_variable: str) -> bool:
+ """Detect whether `env_variable` has been set to a false value in the environment"""
+ return os.getenv(env_variable, "true").lower() in ("false", "0", "n", "no", "off")
+
+
+ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"}
+ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"})
+
+# Try to run a native pytorch job in an environment with TorchXLA installed by setting this value to 0.
+USE_TORCH_XLA = os.environ.get("USE_TORCH_XLA", "1").upper()
+
+ACCELERATE_MIN_VERSION = "1.1.0"
+BITSANDBYTES_MIN_VERSION = "0.46.1"
+SCHEDULEFREE_MIN_VERSION = "1.2.6"
+FSDP_MIN_VERSION = "1.12.0"
+GGUF_MIN_VERSION = "0.10.0"
+XLA_FSDPV2_MIN_VERSION = "2.2.0"
+HQQ_MIN_VERSION = "0.2.1"
+VPTQ_MIN_VERSION = "0.0.4"
+TORCHAO_MIN_VERSION = "0.4.0"
+AUTOROUND_MIN_VERSION = "0.5.0"
+TRITON_MIN_VERSION = "1.0.0"
+KERNELS_MIN_VERSION = "0.10.2"
+
+
+@lru_cache
+def is_torch_available() -> bool:
+ try:
+ is_available, torch_version = _is_package_available("torch", return_version=True)
+ parsed_version = version.parse(torch_version)
+ if is_available and parsed_version < version.parse("2.4.0"):
+ logger.warning_once(f"Disabling PyTorch because PyTorch >= 2.4 is required but found {torch_version}")
+ return is_available and version.parse(torch_version) >= version.parse("2.4.0")
+ except packaging.version.InvalidVersion:
+ return False
+
+
+@lru_cache
+def get_torch_version() -> str:
+ _, torch_version = _is_package_available("torch", return_version=True)
+ return torch_version
+
+
+@lru_cache
+def is_torch_greater_or_equal(library_version: str, accept_dev: bool = False) -> bool:
+ """
+ Accepts a library version and returns True if the current version of the library is greater than or equal to the
+ given version. If `accept_dev` is True, it will also accept development versions (e.g. 2.7.0.dev20250320 matches
+ 2.7.0).
+ """
+ if not is_torch_available():
+ return False
+
+ if accept_dev:
+ return version.parse(version.parse(get_torch_version()).base_version) >= version.parse(library_version)
+ else:
+ return version.parse(get_torch_version()) >= version.parse(library_version)
+
+
+@lru_cache
+def is_torch_less_or_equal(library_version: str, accept_dev: bool = False) -> bool:
+ """
+ Accepts a library version and returns True if the current version of the library is less than or equal to the
+ given version. If `accept_dev` is True, it will also accept development versions (e.g. 2.7.0.dev20250320 matches
+ 2.7.0).
+ """
+ if not is_torch_available():
+ return False
+
+ if accept_dev:
+ return version.parse(version.parse(get_torch_version()).base_version) <= version.parse(library_version)
+ else:
+ return version.parse(get_torch_version()) <= version.parse(library_version)
+
+
+@lru_cache
+def is_torch_accelerator_available() -> bool:
+ if is_torch_available():
+ import torch
+
+ return hasattr(torch, "accelerator")
+
+ return False
+
+
+@lru_cache
+def is_torch_cuda_available() -> bool:
+ if is_torch_available():
+ import torch
+
+ return torch.cuda.is_available()
+ return False
+
+
+@lru_cache
+def is_cuda_platform() -> bool:
+ if is_torch_available():
+ import torch
+
+ return torch.version.cuda is not None
+ return False
+
+
+@lru_cache
+def is_rocm_platform() -> bool:
+ if is_torch_available():
+ import torch
+
+ return torch.version.hip is not None
+ return False
+
+
+@lru_cache
+def is_habana_gaudi1() -> bool:
+ if not is_torch_hpu_available():
+ return False
+
+ import habana_frameworks.torch.utils.experimental as htexp
+
+ # Check if the device is Gaudi1 (vs Gaudi2, Gaudi3)
+ return htexp._get_device_type() == htexp.synDeviceType.synDeviceGaudi
+
+
+@lru_cache
+def is_torch_mps_available(min_version: str | None = None) -> bool:
+ if is_torch_available():
+ import torch
+
+ backend_available = torch.backends.mps.is_available() and torch.backends.mps.is_built()
+ if min_version is not None:
+ flag = version.parse(get_torch_version()) >= version.parse(min_version)
+ backend_available = backend_available and flag
+ return backend_available
+ return False
+
+
+@lru_cache
+def is_torch_npu_available(check_device=False) -> bool:
+ "Checks if `torch_npu` is installed and potentially if a NPU is in the environment"
+ if not is_torch_available() or not _is_package_available("torch_npu")[0]:
+ return False
+
+ import torch
+ import torch_npu # noqa: F401
+
+ if check_device:
+ try:
+ # Will raise a RuntimeError if no NPU is found
+ if hasattr(torch, "npu"):
+ _ = torch.npu.device_count()
+ return torch.npu.is_available()
+ return False
+ except RuntimeError:
+ return False
+ return hasattr(torch, "npu") and torch.npu.is_available()
+
+
+@lru_cache
+def is_torch_xpu_available(check_device: bool = False) -> bool:
+ """
+ Checks if XPU acceleration is available via stock PyTorch (>=2.6) and
+ potentially if a XPU is in the environment.
+ """
+ if not is_torch_available():
+ return False
+
+ torch_version = version.parse(get_torch_version())
+ if torch_version.major == 2 and torch_version.minor < 6:
+ return False
+
+ import torch
+
+ if check_device:
+ try:
+ # Will raise a RuntimeError if no XPU is found
+ _ = torch.xpu.device_count()
+ return torch.xpu.is_available()
+ except RuntimeError:
+ return False
+ return hasattr(torch, "xpu") and torch.xpu.is_available()
+
+
+@lru_cache
+def is_torch_mlu_available() -> bool:
+ """
+ Checks if `mlu` is available via an `cndev-based` check which won't trigger the drivers and leave mlu
+ uninitialized.
+ """
+ if not is_torch_available() or not _is_package_available("torch_mlu")[0]:
+ return False
+
+ import torch
+ import torch_mlu # noqa: F401
+
+ pytorch_cndev_based_mlu_check_previous_value = os.environ.get("PYTORCH_CNDEV_BASED_MLU_CHECK")
+ try:
+ os.environ["PYTORCH_CNDEV_BASED_MLU_CHECK"] = str(1)
+ available = torch.mlu.is_available() if hasattr(torch, "mlu") else False
+ finally:
+ if pytorch_cndev_based_mlu_check_previous_value:
+ os.environ["PYTORCH_CNDEV_BASED_MLU_CHECK"] = pytorch_cndev_based_mlu_check_previous_value
+ else:
+ os.environ.pop("PYTORCH_CNDEV_BASED_MLU_CHECK", None)
+
+ return available
+
+
+@lru_cache
+def is_torch_musa_available(check_device=False) -> bool:
+ "Checks if `torch_musa` is installed and potentially if a MUSA is in the environment"
+ if not is_torch_available() or not _is_package_available("torch_musa")[0]:
+ return False
+
+ import torch
+ import torch_musa # noqa: F401
+
+ torch_musa_min_version = "0.33.0"
+ accelerate_available, accelerate_version = _is_package_available("accelerate", return_version=True)
+ if accelerate_available and version.parse(accelerate_version) < version.parse(torch_musa_min_version):
+ return False
+
+ if check_device:
+ try:
+ # Will raise a RuntimeError if no MUSA is found
+ if hasattr(torch, "musa"):
+ _ = torch.musa.device_count()
+ return torch.musa.is_available()
+ return False
+ except RuntimeError:
+ return False
+ return hasattr(torch, "musa") and torch.musa.is_available()
+
+
+@lru_cache
+def is_torch_xla_available(check_is_tpu=False, check_is_gpu=False) -> bool:
+ """
+ Check if `torch_xla` is available. To train a native pytorch job in an environment with torch xla installed, set
+ the USE_TORCH_XLA to false.
+ """
+ assert not (check_is_tpu and check_is_gpu), "The check_is_tpu and check_is_gpu cannot both be true."
+
+ torch_xla_available = USE_TORCH_XLA in ENV_VARS_TRUE_VALUES and _is_package_available("torch_xla")[0]
+ if not torch_xla_available:
+ return False
+
+ import torch_xla
+
+ if check_is_gpu:
+ return torch_xla.runtime.device_type() in ["GPU", "CUDA"]
+ elif check_is_tpu:
+ return torch_xla.runtime.device_type() == "TPU"
+
+ return True
+
+
+@lru_cache
+def is_torch_hpu_available() -> bool:
+ "Checks if `torch.hpu` is available and potentially if a HPU is in the environment"
+ if (
+ not is_torch_available()
+ or not _is_package_available("habana_frameworks")[0]
+ or not _is_package_available("habana_frameworks.torch")[0]
+ ):
+ return False
+
+ torch_hpu_min_accelerate_version = "1.5.0"
+ accelerate_available, accelerate_version = _is_package_available("accelerate", return_version=True)
+ if accelerate_available and version.parse(accelerate_version) < version.parse(torch_hpu_min_accelerate_version):
+ return False
+
+ import torch
+
+ if os.environ.get("PT_HPU_LAZY_MODE", "1") == "1":
+ # import habana_frameworks.torch in case of lazy mode to patch torch with torch.hpu
+ import habana_frameworks.torch # noqa: F401
+
+ if not hasattr(torch, "hpu") or not torch.hpu.is_available():
+ return False
+
+ # We patch torch.gather for int64 tensors to avoid a bug on Gaudi
+ # Graph compile failed with synStatus 26 [Generic failure]
+ # This can be removed once bug is fixed but for now we need it.
+ original_gather = torch.gather
+
+ def patched_gather(input: torch.Tensor, dim: int, index: torch.LongTensor) -> torch.Tensor:
+ if input.dtype == torch.int64 and input.device.type == "hpu":
+ return original_gather(input.to(torch.int32), dim, index).to(torch.int64)
+ else:
+ return original_gather(input, dim, index)
+
+ torch.gather = patched_gather
+ torch.Tensor.gather = patched_gather
+
+ original_take_along_dim = torch.take_along_dim
+
+ def patched_take_along_dim(input: torch.Tensor, indices: torch.LongTensor, dim: int | None = None) -> torch.Tensor:
+ if input.dtype == torch.int64 and input.device.type == "hpu":
+ return original_take_along_dim(input.to(torch.int32), indices, dim).to(torch.int64)
+ else:
+ return original_take_along_dim(input, indices, dim)
+
+ torch.take_along_dim = patched_take_along_dim
+
+ original_cholesky = torch.linalg.cholesky
+
+ def safe_cholesky(A, *args, **kwargs):
+ output = original_cholesky(A, *args, **kwargs)
+
+ if torch.isnan(output).any():
+ jitter_value = 1e-9
+ diag_jitter = torch.eye(A.size(-1), dtype=A.dtype, device=A.device) * jitter_value
+ output = original_cholesky(A + diag_jitter, *args, **kwargs)
+
+ return output
+
+ torch.linalg.cholesky = safe_cholesky
+
+ original_scatter = torch.scatter
+
+ def patched_scatter(
+ input: torch.Tensor, dim: int, index: torch.Tensor, src: torch.Tensor, *args, **kwargs
+ ) -> torch.Tensor:
+ if input.device.type == "hpu" and input is src:
+ return original_scatter(input, dim, index, src.clone(), *args, **kwargs)
+ else:
+ return original_scatter(input, dim, index, src, *args, **kwargs)
+
+ torch.scatter = patched_scatter
+ torch.Tensor.scatter = patched_scatter
+
+ # IlyasMoutawwakil: we patch torch.compile to use the HPU backend by default
+ # https://github.com/huggingface/transformers/pull/38790#discussion_r2157043944
+ # This is necessary for cases where torch.compile is used as a decorator (defaulting to inductor)
+ # https://github.com/huggingface/transformers/blob/af6120b3eb2470b994c21421bb6eaa76576128b0/src/transformers/models/modernbert/modeling_modernbert.py#L204
+ original_compile = torch.compile
+
+ def hpu_backend_compile(*args, **kwargs):
+ if kwargs.get("backend") not in ["hpu_backend", "eager"]:
+ logger.warning(
+ f"Calling torch.compile with backend={kwargs.get('backend')} on a Gaudi device is not supported. "
+ "We will override the backend with 'hpu_backend' to avoid errors."
+ )
+ kwargs["backend"] = "hpu_backend"
+
+ return original_compile(*args, **kwargs)
+
+ torch.compile = hpu_backend_compile
+
+ return True
+
+
+@lru_cache
+def is_torch_bf16_gpu_available() -> bool:
+ if not is_torch_available():
+ return False
+
+ import torch
+
+ if torch.cuda.is_available():
+ return torch.cuda.is_bf16_supported()
+ if is_torch_xpu_available():
+ return torch.xpu.is_bf16_supported()
+ if is_torch_hpu_available():
+ return True
+ if is_torch_npu_available():
+ return torch.npu.is_bf16_supported() if hasattr(torch, "npu") else False
+ if is_torch_mps_available():
+ # Note: Emulated in software by Metal using fp32 for hardware without native support (like M1/M2)
+ return torch.backends.mps.is_macos_or_newer(14, 0)
+ if is_torch_musa_available():
+ return torch.musa.is_bf16_supported() if hasattr(torch, "musa") else False
+ return False
+
+
+@lru_cache
+def is_torch_fp16_available_on_device(device: str) -> bool:
+ if not is_torch_available():
+ return False
+
+ if is_torch_hpu_available():
+ if is_habana_gaudi1():
+ return False
+ else:
+ return True
+
+ import torch
+
+ try:
+ x = torch.zeros(2, 2, dtype=torch.float16, device=device)
+ _ = x @ x
+ # At this moment, let's be strict of the check: check if `LayerNorm` is also supported on device, because many
+ # models use this layer.
+ batch, sentence_length, embedding_dim = 3, 4, 5
+ embedding = torch.randn(batch, sentence_length, embedding_dim, dtype=torch.float16, device=device)
+ layer_norm = torch.nn.LayerNorm(embedding_dim, dtype=torch.float16, device=device)
+ _ = layer_norm(embedding)
+ return True
+ except Exception:
+ return False
+
+
+@lru_cache
+def is_torch_bf16_available_on_device(device: str) -> bool:
+ if not is_torch_available():
+ return False
+
+ import torch
+
+ if device == "cuda":
+ return is_torch_bf16_gpu_available()
+
+ if device == "hpu":
+ return True
+
+ try:
+ x = torch.zeros(2, 2, dtype=torch.bfloat16, device=device)
+ _ = x @ x
+ return True
+ except Exception:
+ return False
+
+
+@lru_cache
+def is_torch_tf32_available() -> bool:
+ if not is_torch_available():
+ return False
+
+ import torch
+
+ if is_torch_musa_available():
+ if hasattr(torch, "musa"):
+ device_info = torch.musa.get_device_properties(torch.musa.current_device())
+ if f"{device_info.major}{device_info.minor}" >= "22":
+ return True
+ return False
+ if not torch.cuda.is_available() or torch.version.cuda is None:
+ return False
+ if torch.cuda.get_device_properties(torch.cuda.current_device()).major < 8:
+ return False
+ return True
+
+
+@lru_cache
+def enable_tf32(enable: bool) -> None:
+ """
+ Set TF32 mode using the appropriate PyTorch API.
+ For PyTorch 2.9+, uses the new fp32_precision API.
+ For older versions, uses the legacy allow_tf32 flags.
+ Args:
+ enable: Whether to enable TF32 mode
+ """
+ import torch
+
+ pytorch_version = version.parse(get_torch_version())
+ if pytorch_version >= version.parse("2.9.0"):
+ precision_mode = "tf32" if enable else "ieee"
+ if hasattr(torch.backends, "fp32_precision"):
+ torch.backends.fp32_precision = precision_mode
+ else:
+ if is_torch_musa_available():
+ if hasattr(torch.backends, "mudnn"):
+ torch.backends.mudnn.allow_tf32 = enable
+ else:
+ torch.backends.cuda.matmul.allow_tf32 = enable
+ torch.backends.cudnn.allow_tf32 = enable
+
+
+@lru_cache
+def is_torch_flex_attn_available() -> bool:
+ return is_torch_available() and version.parse(get_torch_version()) >= version.parse("2.5.0")
+
+
+@lru_cache
+def is_grouped_mm_available() -> bool:
+ return is_torch_available() and version.parse(get_torch_version()) >= version.parse("2.9.0")
+
+
+@lru_cache
+def is_kenlm_available() -> bool:
+ return _is_package_available("kenlm")[0]
+
+
+@lru_cache
+def is_kernels_available(MIN_VERSION: str = KERNELS_MIN_VERSION) -> bool:
+ is_available, kernels_version = _is_package_available("kernels", return_version=True)
+ return is_available and version.parse(kernels_version) >= version.parse(MIN_VERSION)
+
+
+@lru_cache
+def is_cv2_available() -> bool:
+ return _is_package_available("cv2")[0]
+
+
+@lru_cache
+def is_yt_dlp_available() -> bool:
+ return _is_package_available("yt_dlp")[0]
+
+
+@lru_cache
+def is_libcst_available() -> bool:
+ return _is_package_available("libcst")[0]
+
+
+@lru_cache
+def is_accelerate_available(min_version: str = ACCELERATE_MIN_VERSION) -> bool:
+ is_available, accelerate_version = _is_package_available("accelerate", return_version=True)
+ return is_available and version.parse(accelerate_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_triton_available(min_version: str = TRITON_MIN_VERSION) -> bool:
+ is_available, triton_version = _is_package_available("triton", return_version=True)
+ return is_available and version.parse(triton_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_hadamard_available() -> bool:
+ return _is_package_available("fast_hadamard_transform")[0]
+
+
+@lru_cache
+def is_hqq_available(min_version: str = HQQ_MIN_VERSION) -> bool:
+ is_available, hqq_version = _is_package_available("hqq", return_version=True)
+ return is_available and version.parse(hqq_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_pygments_available() -> bool:
+ return _is_package_available("pygments")[0]
+
+
+@lru_cache
+def is_torchvision_available() -> bool:
+ return _is_package_available("torchvision")[0]
+
+
+@lru_cache
+def is_torchvision_v2_available() -> bool:
+ return is_torchvision_available()
+
+
+@lru_cache
+def is_galore_torch_available() -> bool:
+ return _is_package_available("galore_torch")[0]
+
+
+@lru_cache
+def is_apollo_torch_available() -> bool:
+ return _is_package_available("apollo_torch")[0]
+
+
+@lru_cache
+def is_torch_optimi_available() -> bool:
+ return _is_package_available("optimi")[0]
+
+
+@lru_cache
+def is_lomo_available() -> bool:
+ return _is_package_available("lomo_optim")[0]
+
+
+@lru_cache
+def is_grokadamw_available() -> bool:
+ return _is_package_available("grokadamw")[0]
+
+
+@lru_cache
+def is_schedulefree_available(min_version: str = SCHEDULEFREE_MIN_VERSION) -> bool:
+ is_available, schedulefree_version = _is_package_available("schedulefree", return_version=True)
+ return is_available and version.parse(schedulefree_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_pyctcdecode_available() -> bool:
+ return _is_package_available("pyctcdecode")[0]
+
+
+@lru_cache
+def is_librosa_available() -> bool:
+ return _is_package_available("librosa")[0]
+
+
+@lru_cache
+def is_essentia_available() -> bool:
+ return _is_package_available("essentia")[0]
+
+
+@lru_cache
+def is_pydantic_available() -> bool:
+ return _is_package_available("pydantic")[0]
+
+
+@lru_cache
+def is_fastapi_available() -> bool:
+ return _is_package_available("fastapi")[0]
+
+
+@lru_cache
+def is_uvicorn_available() -> bool:
+ return _is_package_available("uvicorn")[0]
+
+
+@lru_cache
+def is_openai_available() -> bool:
+ return _is_package_available("openai")[0]
+
+
+@lru_cache
+def is_pretty_midi_available() -> bool:
+ return _is_package_available("pretty_midi")[0]
+
+
+@lru_cache
+def is_mamba_ssm_available() -> bool:
+ return is_torch_cuda_available() and _is_package_available("mamba_ssm")[0]
+
+
+@lru_cache
+def is_mamba_2_ssm_available() -> bool:
+ is_available, mamba_ssm_version = _is_package_available("mamba_ssm", return_version=True)
+ return is_torch_cuda_available() and is_available and version.parse(mamba_ssm_version) >= version.parse("2.0.4")
+
+
+@lru_cache
+def is_flash_linear_attention_available():
+ is_available, fla_version = _is_package_available("fla", return_version=True)
+ return is_torch_cuda_available() and is_available and version.parse(fla_version) >= version.parse("0.2.2")
+
+
+@lru_cache
+def is_causal_conv1d_available() -> bool:
+ return is_torch_cuda_available() and _is_package_available("causal_conv1d")[0]
+
+
+@lru_cache
+def is_xlstm_available() -> bool:
+ return is_torch_available() and _is_package_available("xlstm")[0]
+
+
+@lru_cache
+def is_mambapy_available() -> bool:
+ return is_torch_available() and _is_package_available("mambapy")[0]
+
+
+@lru_cache
+def is_peft_available() -> bool:
+ return _is_package_available("peft")[0]
+
+
+@lru_cache
+def is_bs4_available() -> bool:
+ return _is_package_available("bs4")[0]
+
+
+@lru_cache
+def is_coloredlogs_available() -> bool:
+ return _is_package_available("coloredlogs")[0]
+
+
+@lru_cache
+def is_onnx_available() -> bool:
+ return _is_package_available("onnx")[0]
+
+
+@lru_cache
+def is_flute_available() -> bool:
+ is_available, flute_version = _is_package_available("flute", return_version=True)
+ return is_available and version.parse(flute_version) >= version.parse("0.4.1")
+
+
+@lru_cache
+def is_g2p_en_available() -> bool:
+ return _is_package_available("g2p_en")[0]
+
+
+@lru_cache
+def is_torch_neuroncore_available(check_device=True) -> bool:
+ return is_torch_xla_available() and _is_package_available("torch_neuronx")[0]
+
+
+@lru_cache
+def is_torch_tensorrt_fx_available() -> bool:
+ return _is_package_available("torch_tensorrt")[0] and _is_package_available("torch_tensorrt.fx")[0]
+
+
+@lru_cache
+def is_datasets_available() -> bool:
+ return _is_package_available("datasets")[0]
+
+
+@lru_cache
+def is_detectron2_available() -> bool:
+ # We need this try/except block because otherwise after uninstalling the library, it stays available for some reason
+ # i.e. `import detectron2` and `import detectron2.modeling` still work, even though the library is uninstalled
+ # (the package exists but the objects are not reachable) - so here we explicitly try to import an object from it
+ try:
+ from detectron2.modeling import META_ARCH_REGISTRY # noqa
+
+ return True
+ except Exception:
+ return False
+
+
+@lru_cache
+def is_rjieba_available() -> bool:
+ return _is_package_available("rjieba")[0]
+
+
+@lru_cache
+def is_psutil_available() -> bool:
+ return _is_package_available("psutil")[0]
+
+
+@lru_cache
+def is_py3nvml_available() -> bool:
+ return _is_package_available("py3nvml")[0]
+
+
+@lru_cache
+def is_sacremoses_available() -> bool:
+ return _is_package_available("sacremoses")[0]
+
+
+@lru_cache
+def is_apex_available() -> bool:
+ return _is_package_available("apex")[0]
+
+
+@lru_cache
+def is_aqlm_available() -> bool:
+ return _is_package_available("aqlm")[0]
+
+
+@lru_cache
+def is_vptq_available(min_version: str = VPTQ_MIN_VERSION) -> bool:
+ is_available, vptq_version = _is_package_available("vptq", return_version=True)
+ return is_available and version.parse(vptq_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_av_available() -> bool:
+ return _is_package_available("av")[0]
+
+
+@lru_cache
+def is_decord_available() -> bool:
+ return _is_package_available("decord")[0]
+
+
+@lru_cache
+def is_torchcodec_available() -> bool:
+ return _is_package_available("torchcodec")[0]
+
+
+@lru_cache
+def is_ninja_available() -> bool:
+ r"""
+ Code comes from *torch.utils.cpp_extension.is_ninja_available()*. Returns `True` if the
+ [ninja](https://ninja-build.org/) build system is available on the system, `False` otherwise.
+ """
+ try:
+ subprocess.check_output(["ninja", "--version"])
+ except Exception:
+ return False
+ else:
+ return True
+
+
+@lru_cache
+def is_bitsandbytes_available(min_version: str = BITSANDBYTES_MIN_VERSION) -> bool:
+ is_available, bitsandbytes_version = _is_package_available("bitsandbytes", return_version=True)
+ return is_available and version.parse(bitsandbytes_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_flash_attn_2_available() -> bool:
+ is_available, flash_attn_version = _is_package_available("flash_attn", return_version=True)
+ if not is_available or not (is_torch_cuda_available() or is_torch_mlu_available()):
+ return False
+
+ import torch
+
+ try:
+ if torch.version.cuda:
+ return version.parse(flash_attn_version) >= version.parse("2.1.0")
+ elif torch.version.hip:
+ # TODO: Bump the requirement to 2.1.0 once released in https://github.com/ROCmSoftwarePlatform/flash-attention
+ return version.parse(flash_attn_version) >= version.parse("2.0.4")
+ elif is_torch_mlu_available():
+ return version.parse(flash_attn_version) >= version.parse("2.3.3")
+ else:
+ return False
+ except packaging.version.InvalidVersion:
+ return False
+
+
+@lru_cache
+def is_flash_attn_3_available() -> bool:
+ return is_torch_cuda_available() and _is_package_available("flash_attn_3")[0]
+
+
+@lru_cache
+def is_flash_attn_greater_or_equal_2_10() -> bool:
+ _, flash_attn_version = _is_package_available("flash_attn", return_version=True)
+ return is_flash_attn_2_available() and version.parse(flash_attn_version) >= version.parse("2.1.0")
+
+
+@lru_cache
+def is_flash_attn_greater_or_equal(library_version: str) -> bool:
+ is_available, flash_attn_version = _is_package_available("flash_attn", return_version=True)
+ if not is_available:
+ return False
+ try:
+ return version.parse(flash_attn_version) >= version.parse(library_version)
+ except packaging.version.InvalidVersion:
+ return False
+
+
+@lru_cache
+def is_huggingface_hub_greater_or_equal(library_version: str, accept_dev: bool = False) -> bool:
+ is_available, hub_version = _is_package_available("huggingface_hub", return_version=True)
+ if not is_available:
+ return False
+
+ if accept_dev:
+ return version.parse(version.parse(hub_version).base_version) >= version.parse(library_version)
+ else:
+ return version.parse(hub_version) >= version.parse(library_version)
+
+
+@lru_cache
+def is_quanto_greater(library_version: str, accept_dev: bool = False) -> bool:
+ """
+ Accepts a library version and returns True if the current version of the library is greater than or equal to the
+ given version. If `accept_dev` is True, it will also accept development versions (e.g. 2.7.0.dev20250320 matches
+ 2.7.0).
+ """
+ if not is_optimum_quanto_available():
+ return False
+
+ _, quanto_version = _is_package_available("optimum.quanto", return_version=True)
+ if accept_dev:
+ return version.parse(version.parse(quanto_version).base_version) > version.parse(library_version)
+ else:
+ return version.parse(quanto_version) > version.parse(library_version)
+
+
+@lru_cache
+def is_torchdistx_available():
+ return _is_package_available("torchdistx")[0]
+
+
+@lru_cache
+def is_faiss_available() -> bool:
+ return _is_package_available("faiss")[0]
+
+
+@lru_cache
+def is_fouroversix_available() -> bool:
+ return _is_package_available("fouroversix")
+
+
+@lru_cache
+def is_scipy_available() -> bool:
+ return _is_package_available("scipy")[0]
+
+
+@lru_cache
+def is_sklearn_available() -> bool:
+ return _is_package_available("sklearn")[0]
+
+
+@lru_cache
+def is_sentencepiece_available() -> bool:
+ return _is_package_available("sentencepiece")[0]
+
+
+@lru_cache
+def is_seqio_available() -> bool:
+ return _is_package_available("seqio")[0]
+
+
+@lru_cache
+def is_gguf_available(min_version: str = GGUF_MIN_VERSION) -> bool:
+ is_available, gguf_version = _is_package_available("gguf", return_version=True)
+ return is_available and version.parse(gguf_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_protobuf_available() -> bool:
+ return _is_package_available("google")[0] and _is_package_available("google.protobuf")[0]
+
+
+@lru_cache
+def is_fsdp_available(min_version: str = FSDP_MIN_VERSION) -> bool:
+ return is_torch_available() and version.parse(get_torch_version()) >= version.parse(min_version)
+
+
+@lru_cache
+def is_optimum_available() -> bool:
+ return _is_package_available("optimum")[0]
+
+
+@lru_cache
+def is_llm_awq_available() -> bool:
+ return _is_package_available("awq")[0]
+
+
+@lru_cache
+def is_auto_round_available(min_version: str = AUTOROUND_MIN_VERSION) -> bool:
+ is_available, auto_round_version = _is_package_available("auto_round", return_version=True)
+ return is_available and version.parse(auto_round_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_optimum_quanto_available():
+ return is_optimum_available() and _is_package_available("optimum.quanto")[0]
+
+
+@lru_cache
+def is_quark_available() -> bool:
+ return _is_package_available("quark")[0]
+
+
+@lru_cache
+def is_fp_quant_available():
+ is_available, fp_quant_version = _is_package_available("fp_quant", return_version=True)
+ return is_available and version.parse(fp_quant_version) >= version.parse("0.3.2")
+
+
+@lru_cache
+def is_qutlass_available():
+ is_available, qutlass_version = _is_package_available("qutlass", return_version=True)
+ return is_available and version.parse(qutlass_version) >= version.parse("0.2.0")
+
+
+@lru_cache
+def is_compressed_tensors_available() -> bool:
+ return _is_package_available("compressed_tensors")[0]
+
+
+@lru_cache
+def is_sinq_available() -> bool:
+ return _is_package_available("sinq")
+
+
+@lru_cache
+def is_gptqmodel_available() -> bool:
+ return _is_package_available("gptqmodel")[0]
+
+
+@lru_cache
+def is_fbgemm_gpu_available() -> bool:
+ return _is_package_available("fbgemm_gpu")[0]
+
+
+@lru_cache
+def is_levenshtein_available() -> bool:
+ return _is_package_available("Levenshtein")[0]
+
+
+@lru_cache
+def is_optimum_neuron_available() -> bool:
+ return is_optimum_available() and _is_package_available("optimum.neuron")[0]
+
+
+@lru_cache
+def is_tokenizers_available() -> bool:
+ return _is_package_available("tokenizers")[0]
+
+
+@lru_cache
+def is_vision_available() -> bool:
+ return _is_package_available("PIL")[0]
+
+
+@lru_cache
+def is_pytesseract_available() -> bool:
+ return _is_package_available("pytesseract")[0]
+
+
+@lru_cache
+def is_pytest_available() -> bool:
+ return _is_package_available("pytest")[0]
+
+
+@lru_cache
+def is_pytest_order_available() -> bool:
+ return is_pytest_available() and _is_package_available("pytest_order")[0]
+
+
+@lru_cache
+def is_spacy_available() -> bool:
+ return _is_package_available("spacy")[0]
+
+
+@lru_cache
+def is_pytorch_quantization_available() -> bool:
+ return _is_package_available("pytorch_quantization")[0]
+
+
+@lru_cache
+def is_pandas_available() -> bool:
+ return _is_package_available("pandas")[0]
+
+
+@lru_cache
+def is_soundfile_available() -> bool:
+ return _is_package_available("soundfile")[0]
+
+
+@lru_cache
+def is_timm_available() -> bool:
+ return _is_package_available("timm")[0]
+
+
+@lru_cache
+def is_natten_available() -> bool:
+ return _is_package_available("natten")[0]
+
+
+@lru_cache
+def is_nltk_available() -> bool:
+ return _is_package_available("nltk")[0]
+
+
+@lru_cache
+def is_numba_available() -> bool:
+ is_available = _is_package_available("numba")[0]
+ if not is_available:
+ return False
+
+ numpy_available, numpy_version = _is_package_available("numpy", return_version=True)
+ return not numpy_available or version.parse(numpy_version) < version.parse("2.2.0")
+
+
+@lru_cache
+def is_torchaudio_available() -> bool:
+ return _is_package_available("torchaudio")[0]
+
+
+@lru_cache
+def is_torchao_available(min_version: str = TORCHAO_MIN_VERSION) -> bool:
+ is_available, torchao_version = _is_package_available("torchao", return_version=True)
+ return is_available and version.parse(torchao_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_speech_available() -> bool:
+ # For now this depends on torchaudio but the exact dependency might evolve in the future.
+ return is_torchaudio_available()
+
+
+@lru_cache
+def is_spqr_available() -> bool:
+ return _is_package_available("spqr_quant")[0]
+
+
+@lru_cache
+def is_phonemizer_available() -> bool:
+ return _is_package_available("phonemizer")[0]
+
+
+@lru_cache
+def is_uroman_available() -> bool:
+ return _is_package_available("uroman")[0]
+
+
+@lru_cache
+def is_sudachi_available() -> bool:
+ return _is_package_available("sudachipy")[0]
+
+
+@lru_cache
+def is_sudachi_projection_available() -> bool:
+ is_available, sudachipy_version = _is_package_available("sudachipy", return_version=True)
+ return is_available and version.parse(sudachipy_version) >= version.parse("0.6.8")
+
+
+@lru_cache
+def is_jumanpp_available() -> bool:
+ return _is_package_available("rhoknp")[0] and shutil.which("jumanpp") is not None
+
+
+@lru_cache
+def is_cython_available() -> bool:
+ return _is_package_available("pyximport")[0]
+
+
+@lru_cache
+def is_jinja_available() -> bool:
+ return _is_package_available("jinja2")[0]
+
+
+@lru_cache
+def is_jmespath_available() -> bool:
+ return _is_package_available("jmespath")[0]
+
+
+@lru_cache
+def is_mlx_available() -> bool:
+ return _is_package_available("mlx")[0]
+
+
+@lru_cache
+def is_num2words_available() -> bool:
+ return _is_package_available("num2words")[0]
+
+
+@lru_cache
+def is_tiktoken_available(with_blobfile: bool = True) -> bool:
+ if not _is_package_available("tiktoken")[0]:
+ return False
+ return with_blobfile and _is_package_available("blobfile")[0] or True
+
+
+@lru_cache
+def is_liger_kernel_available() -> bool:
+ is_available, liger_kernel_version = _is_package_available("liger_kernel", return_version=True)
+ return is_available and version.parse(liger_kernel_version) >= version.parse("0.3.0")
+
+
+@lru_cache
+def is_rich_available() -> bool:
+ return _is_package_available("rich")[0]
+
+
+@lru_cache
+def is_matplotlib_available() -> bool:
+ return _is_package_available("matplotlib")[0]
+
+
+@lru_cache
+def is_mistral_common_available() -> bool:
+ return _is_package_available("mistral_common")[0]
+
+
+@lru_cache
+def is_opentelemetry_available() -> bool:
+ try:
+ return _is_package_available("opentelemetry")[0] and version.parse(
+ importlib.metadata.version("opentelemetry-api")
+ ) >= version.parse("1.30.0")
+ except Exception as _:
+ return False
+
+
+@lru_cache
+def is_pynvml_available() -> bool:
+ return _is_package_available("pynvml")[0]
+
+
+def check_torch_load_is_safe() -> None:
+ if not is_torch_greater_or_equal("2.6"):
+ raise ValueError(
+ "Due to a serious vulnerability issue in `torch.load`, even with `weights_only=True`, we now require users "
+ "to upgrade torch to at least v2.6 in order to use the function. This version restriction does not apply "
+ "when loading files with safetensors."
+ "\nSee the vulnerability report here https://nvd.nist.gov/vuln/detail/CVE-2025-32434"
+ )
+
+
+def torch_only_method(fn: Callable) -> Callable:
+ def wrapper(*args, **kwargs):
+ if not is_torch_available():
+ raise ImportError("You need to install pytorch to use this method or class")
+ else:
+ return fn(*args, **kwargs)
+
+ return wrapper
+
+
+def is_torch_deterministic() -> bool:
+ """
+ Check whether pytorch uses deterministic algorithms by looking if torch.set_deterministic_debug_mode() is set to 1 or 2"
+ """
+ if is_torch_available():
+ import torch
+
+ if torch.get_deterministic_debug_mode() == 0:
+ return False
+ else:
+ return True
+
+ return False
+
+
+@lru_cache
+def get_torch_major_and_minor_version() -> str:
+ torch_version = get_torch_version()
+ if torch_version == "N/A":
+ return "N/A"
+ parsed_version = version.parse(torch_version)
+ return str(parsed_version.major) + "." + str(parsed_version.minor)
+
+
+def is_torchdynamo_compiling() -> bool:
+ # Importing torch._dynamo causes issues with PyTorch profiler (https://github.com/pytorch/pytorch/issues/130622)
+ # hence rather relying on `torch.compiler.is_compiling()` when possible (torch>=2.3)
+ try:
+ import torch
+
+ return torch.compiler.is_compiling()
+ except Exception:
+ return False
+
+
+def is_torchdynamo_exporting() -> bool:
+ try:
+ import torch
+
+ return torch.compiler.is_exporting()
+ except Exception:
+ return False
+
+
+def is_torch_fx_proxy(x) -> bool:
+ try:
+ import torch.fx
+
+ return isinstance(x, torch.fx.Proxy)
+ except Exception:
+ return False
+
+
+def is_fake_tensor(x) -> bool:
+ try:
+ import torch
+
+ return isinstance(x, torch._subclasses.FakeTensor)
+ except Exception:
+ return False
+
+
+def is_jax_jitting(x):
+ """returns True if we are inside of `jax.jit` context, False otherwise.
+
+ When a torch model is being compiled with `jax.jit` using torchax,
+ the tensor that goes through the model would be an instance of
+ `torchax.tensor.Tensor`, which is a tensor subclass. This tensor has
+ a `jax` method to return the inner Jax array
+ (https://github.com/google/torchax/blob/13ce870a1d9adb2430333c27bb623469e3aea34e/torchax/tensor.py#L134).
+ Here we use ducktyping to detect if the inner jax array is a jax Tracer
+ then we are in tracing context. (See more at: https://github.com/jax-ml/jax/discussions/9241)
+
+ Args:
+ x: torch.Tensor
+
+ Returns:
+ bool: whether we are inside of jax jit tracing.
+ """
+
+ if not hasattr(x, "jax"):
+ return False
+ try:
+ import jax
+
+ return isinstance(x.jax(), jax.core.Tracer)
+ except Exception:
+ return False
+
+
+def is_jit_tracing() -> bool:
+ try:
+ import torch
+
+ return torch.jit.is_tracing()
+ except Exception:
+ return False
+
+
+def is_cuda_stream_capturing() -> bool:
+ try:
+ import torch
+
+ return torch.cuda.is_current_stream_capturing()
+ except Exception:
+ return False
+
+
+def is_tracing(tensor=None) -> bool:
+ """Checks whether we are tracing a graph with dynamo (compile or export), torch.jit, torch.fx, jax.jit (with torchax) or
+ CUDA stream capturing or FakeTensor"""
+
+ # Note that `is_torchdynamo_compiling` checks both compiling and exporting (the export check is stricter and
+ # only checks export)
+ _is_tracing = is_torchdynamo_compiling() or is_jit_tracing() or is_cuda_stream_capturing()
+ if tensor is not None:
+ _is_tracing |= is_torch_fx_proxy(tensor)
+ _is_tracing |= is_fake_tensor(tensor)
+ _is_tracing |= is_jax_jitting(tensor)
+
+ return _is_tracing
+
+
+def torch_compilable_check(cond: Any, msg: str | Callable[[], str], error_type: type[Exception] = ValueError) -> None:
+ """
+ Combines the functionalities of `torch._check`, `torch._check_with` and `torch._check_tensor_all_with` to provide a
+ unified way to perform checks that are compatible with TorchDynamo (torch.compile & torch.export).
+
+ The advantage of using `torch._check(cond, msg, error_type)` over `if cond: raise error_type(msg)` is that the former
+ works as a truthfulness hint for TorchDynamo, instead of failing with a data-dependent control flow error during compilation.
+
+ All checks using this method can be disabled in production environments by setting `TRANSFORMERS_DISABLE_TORCH_CHECK=1`.
+
+ Args:
+ cond (`bool`, `torch.Tensor` or `Callable[[], bool | torch.Tensor]`): The condition to check.
+ msg (`str` or `Callable[[], str]`): The error message to display if the condition is not met.
+ error_type (`type[Exception]`, *optional*, defaults to `ValueError`): The type of error to raise if the condition is not met.
+
+ Raises:
+ error_type: If the condition is not met.
+ """
+ if os.getenv("TRANSFORMERS_DISABLE_TORCH_CHECK", "0") == "1":
+ return
+
+ import torch
+
+ if not callable(msg):
+ # torch._check requires msg to be a callable but we want to keep the API simple for users
+ def msg_callable():
+ return msg
+ else:
+ msg_callable = msg
+
+ if callable(cond):
+ cond = cond()
+
+ # These checks are also compiler hints for TorchDynamo telling
+ # it that the condition is expected to be True during compilation
+ if isinstance(cond, torch.Tensor):
+ torch._check_tensor_all_with(error_type, cond, msg_callable)
+ else:
+ torch._check_with(error_type, cond, msg_callable)
+
+
+@lru_cache
+def is_in_notebook() -> bool:
+ try:
+ # Check if we are running inside Marimo
+ if "marimo" in sys.modules:
+ return True
+ # Test adapted from tqdm.autonotebook: https://github.com/tqdm/tqdm/blob/master/tqdm/autonotebook.py
+ get_ipython = sys.modules["IPython"].get_ipython
+ if "IPKernelApp" not in get_ipython().config:
+ raise ImportError("console")
+ # Removed the lines to include VSCode
+ if "DATABRICKS_RUNTIME_VERSION" in os.environ and os.environ["DATABRICKS_RUNTIME_VERSION"] < "11.0":
+ # Databricks Runtime 11.0 and above uses IPython kernel by default so it should be compatible with Jupyter notebook
+ # https://docs.microsoft.com/en-us/azure/databricks/notebooks/ipython-kernel
+ raise ImportError("databricks")
+
+ return importlib.util.find_spec("IPython") is not None
+ except (AttributeError, ImportError, KeyError):
+ return False
+
+
+def is_sagemaker_dp_enabled() -> bool:
+ # Get the sagemaker specific env variable.
+ sagemaker_params = os.getenv("SM_FRAMEWORK_PARAMS", "{}")
+ try:
+ # Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
+ sagemaker_params = json.loads(sagemaker_params)
+ if not sagemaker_params.get("sagemaker_distributed_dataparallel_enabled", False):
+ return False
+ except json.JSONDecodeError:
+ return False
+ # Lastly, check if the `smdistributed` module is present.
+ return _is_package_available("smdistributed")[0]
+
+
+def is_sagemaker_mp_enabled() -> bool:
+ # Get the sagemaker specific mp parameters from smp_options variable.
+ smp_options = os.getenv("SM_HP_MP_PARAMETERS", "{}")
+ try:
+ # Parse it and check the field "partitions" is included, it is required for model parallel.
+ smp_options = json.loads(smp_options)
+ if "partitions" not in smp_options:
+ return False
+ except json.JSONDecodeError:
+ return False
+
+ # Get the sagemaker specific framework parameters from mpi_options variable.
+ mpi_options = os.getenv("SM_FRAMEWORK_PARAMS", "{}")
+ try:
+ # Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
+ mpi_options = json.loads(mpi_options)
+ if not mpi_options.get("sagemaker_mpi_enabled", False):
+ return False
+ except json.JSONDecodeError:
+ return False
+ # Lastly, check if the `smdistributed` module is present.
+ return _is_package_available("smdistributed")[0]
+
+
+def is_training_run_on_sagemaker() -> bool:
+ return "SAGEMAKER_JOB_NAME" in os.environ
+
+
+# docstyle-ignore
+AV_IMPORT_ERROR = """
+{0} requires the PyAv library but it was not found in your environment. You can install it with:
+```
+pip install av
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+YT_DLP_IMPORT_ERROR = """
+{0} requires the YT-DLP library but it was not found in your environment. You can install it with:
+```
+pip install yt-dlp
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+DECORD_IMPORT_ERROR = """
+{0} requires the PyAv library but it was not found in your environment. You can install it with:
+```
+pip install decord
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+TORCHCODEC_IMPORT_ERROR = """
+{0} requires the TorchCodec (https://github.com/pytorch/torchcodec) library, but it was not found in your environment. You can install it with:
+```
+pip install torchcodec
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+CV2_IMPORT_ERROR = """
+{0} requires the OpenCV library but it was not found in your environment. You can install it with:
+```
+pip install opencv-python
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+DATASETS_IMPORT_ERROR = """
+{0} requires the 🤗 Datasets library but it was not found in your environment. You can install it with:
+```
+pip install datasets
+```
+In a notebook or a colab, you can install it by executing a cell with
+```
+!pip install datasets
+```
+then restarting your kernel.
+
+Note that if you have a local folder named `datasets` or a local python file named `datasets.py` in your current
+working directory, python may try to import this instead of the 🤗 Datasets library. You should rename this folder or
+that python file if that's the case. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+TOKENIZERS_IMPORT_ERROR = """
+{0} requires the 🤗 Tokenizers library but it was not found in your environment. You can install it with:
+```
+pip install tokenizers
+```
+In a notebook or a colab, you can install it by executing a cell with
+```
+!pip install tokenizers
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+SENTENCEPIECE_IMPORT_ERROR = """
+{0} requires the SentencePiece library but it was not found in your environment. Check out the instructions on the
+installation page of its repo: https://github.com/google/sentencepiece#installation and follow the ones
+that match your environment. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+PROTOBUF_IMPORT_ERROR = """
+{0} requires the protobuf library but it was not found in your environment. Check out the instructions on the
+installation page of its repo: https://github.com/protocolbuffers/protobuf/tree/master/python#installation and follow the ones
+that match your environment. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+FAISS_IMPORT_ERROR = """
+{0} requires the faiss library but it was not found in your environment. Check out the instructions on the
+installation page of its repo: https://github.com/facebookresearch/faiss/blob/master/INSTALL.md and follow the ones
+that match your environment. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+PYTORCH_IMPORT_ERROR = """
+{0} requires the PyTorch library but it was not found in your environment. Check out the instructions on the
+installation page: https://pytorch.org/get-started/locally/ and follow the ones that match your environment.
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+TORCHVISION_IMPORT_ERROR = """
+{0} requires the Torchvision library but it was not found in your environment. Check out the instructions on the
+installation page: https://pytorch.org/get-started/locally/ and follow the ones that match your environment.
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+BS4_IMPORT_ERROR = """
+{0} requires the Beautiful Soup library but it was not found in your environment. You can install it with pip:
+`pip install beautifulsoup4`. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+SKLEARN_IMPORT_ERROR = """
+{0} requires the scikit-learn library but it was not found in your environment. You can install it with:
+```
+pip install -U scikit-learn
+```
+In a notebook or a colab, you can install it by executing a cell with
+```
+!pip install -U scikit-learn
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+DETECTRON2_IMPORT_ERROR = """
+{0} requires the detectron2 library but it was not found in your environment. Check out the instructions on the
+installation page: https://github.com/facebookresearch/detectron2/blob/master/INSTALL.md and follow the ones
+that match your environment. Please note that you may need to restart your runtime after installation.
+"""
+
+
+LEVENSHTEIN_IMPORT_ERROR = """
+{0} requires the python-Levenshtein library but it was not found in your environment. You can install it with pip: `pip
+install python-Levenshtein`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+G2P_EN_IMPORT_ERROR = """
+{0} requires the g2p-en library but it was not found in your environment. You can install it with pip:
+`pip install g2p-en`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+PYTORCH_QUANTIZATION_IMPORT_ERROR = """
+{0} requires the pytorch-quantization library but it was not found in your environment. You can install it with pip:
+`pip install pytorch-quantization --extra-index-url https://pypi.ngc.nvidia.com`
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+TORCHAUDIO_IMPORT_ERROR = """
+{0} requires the torchaudio library but it was not found in your environment. Please install it and restart your
+runtime.
+"""
+
+# docstyle-ignore
+PANDAS_IMPORT_ERROR = """
+{0} requires the pandas library but it was not found in your environment. You can install it with pip as
+explained here: https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html.
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+PHONEMIZER_IMPORT_ERROR = """
+{0} requires the phonemizer library but it was not found in your environment. You can install it with pip:
+`pip install phonemizer`. Please note that you may need to restart your runtime after installation.
+"""
+# docstyle-ignore
+UROMAN_IMPORT_ERROR = """
+{0} requires the uroman library but it was not found in your environment. You can install it with pip:
+`pip install uroman`. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+SACREMOSES_IMPORT_ERROR = """
+{0} requires the sacremoses library but it was not found in your environment. You can install it with pip:
+`pip install sacremoses`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+SCIPY_IMPORT_ERROR = """
+{0} requires the scipy library but it was not found in your environment. You can install it with pip:
+`pip install scipy`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+SPEECH_IMPORT_ERROR = """
+{0} requires the torchaudio library but it was not found in your environment. You can install it with pip:
+`pip install torchaudio`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+TIMM_IMPORT_ERROR = """
+{0} requires the timm library but it was not found in your environment. You can install it with pip:
+`pip install timm`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+NATTEN_IMPORT_ERROR = """
+{0} requires the natten library but it was not found in your environment. You can install it by referring to:
+shi-labs.com/natten . You can also install it with pip (may take longer to build):
+`pip install natten`. Please note that you may need to restart your runtime after installation.
+"""
+
+NUMEXPR_IMPORT_ERROR = """
+{0} requires the numexpr library but it was not found in your environment. You can install it by referring to:
+https://numexpr.readthedocs.io/en/latest/index.html.
+"""
+
+
+# docstyle-ignore
+NLTK_IMPORT_ERROR = """
+{0} requires the NLTK library but it was not found in your environment. You can install it by referring to:
+https://www.nltk.org/install.html. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+VISION_IMPORT_ERROR = """
+{0} requires the PIL library but it was not found in your environment. You can install it with pip:
+`pip install pillow`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+PYDANTIC_IMPORT_ERROR = """
+{0} requires the pydantic library but it was not found in your environment. You can install it with pip:
+`pip install pydantic`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+FASTAPI_IMPORT_ERROR = """
+{0} requires the fastapi library but it was not found in your environment. You can install it with pip:
+`pip install fastapi`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+UVICORN_IMPORT_ERROR = """
+{0} requires the uvicorn library but it was not found in your environment. You can install it with pip:
+`pip install uvicorn`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+OPENAI_IMPORT_ERROR = """
+{0} requires the openai library but it was not found in your environment. You can install it with pip:
+`pip install openai`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+PYTESSERACT_IMPORT_ERROR = """
+{0} requires the PyTesseract library but it was not found in your environment. You can install it with pip:
+`pip install pytesseract`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+PYCTCDECODE_IMPORT_ERROR = """
+{0} requires the pyctcdecode library but it was not found in your environment. You can install it with pip:
+`pip install pyctcdecode`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+ACCELERATE_IMPORT_ERROR = """
+{0} requires the accelerate library >= {ACCELERATE_MIN_VERSION} it was not found in your environment.
+You can install or update it with pip: `pip install --upgrade accelerate`. Please note that you may need to restart your
+runtime after installation.
+"""
+
+# docstyle-ignore
+ESSENTIA_IMPORT_ERROR = """
+{0} requires essentia library. But that was not found in your environment. You can install them with pip:
+`pip install essentia==2.1b6.dev1034`
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+LIBROSA_IMPORT_ERROR = """
+{0} requires the librosa library. But that was not found in your environment. You can install them with pip:
+`pip install librosa`
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+PRETTY_MIDI_IMPORT_ERROR = """
+{0} requires the pretty_midi library. But that was not found in your environment. You can install them with pip:
+`pip install pretty_midi`
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+CYTHON_IMPORT_ERROR = """
+{0} requires the Cython library but it was not found in your environment. You can install it with pip: `pip install
+Cython`. Please note that you may need to restart your runtime after installation.
+"""
+
+RJIEBA_IMPORT_ERROR = """
+{0} requires the rjieba library but it was not found in your environment. You can install it with pip: `pip install
+rjieba`. Please note that you may need to restart your runtime after installation.
+"""
+
+PEFT_IMPORT_ERROR = """
+{0} requires the peft library but it was not found in your environment. You can install it with pip: `pip install
+peft`. Please note that you may need to restart your runtime after installation.
+"""
+
+JINJA_IMPORT_ERROR = """
+{0} requires the jinja library but it was not found in your environment. You can install it with pip: `pip install
+jinja2`. Please note that you may need to restart your runtime after installation.
+"""
+
+RICH_IMPORT_ERROR = """
+{0} requires the rich library but it was not found in your environment. You can install it with pip: `pip install
+rich`. Please note that you may need to restart your runtime after installation.
+"""
+
+MISTRAL_COMMON_IMPORT_ERROR = """
+{0} requires the mistral-common library but it was not found in your environment. You can install it with pip: `pip install mistral-common`. Please note that you may need to restart your runtime after installation.
+"""
+
+
+BACKENDS_MAPPING = OrderedDict(
+ [
+ ("av", (is_av_available, AV_IMPORT_ERROR)),
+ ("bs4", (is_bs4_available, BS4_IMPORT_ERROR)),
+ ("cv2", (is_cv2_available, CV2_IMPORT_ERROR)),
+ ("datasets", (is_datasets_available, DATASETS_IMPORT_ERROR)),
+ ("decord", (is_decord_available, DECORD_IMPORT_ERROR)),
+ ("detectron2", (is_detectron2_available, DETECTRON2_IMPORT_ERROR)),
+ ("essentia", (is_essentia_available, ESSENTIA_IMPORT_ERROR)),
+ ("faiss", (is_faiss_available, FAISS_IMPORT_ERROR)),
+ ("g2p_en", (is_g2p_en_available, G2P_EN_IMPORT_ERROR)),
+ ("pandas", (is_pandas_available, PANDAS_IMPORT_ERROR)),
+ ("phonemizer", (is_phonemizer_available, PHONEMIZER_IMPORT_ERROR)),
+ ("uroman", (is_uroman_available, UROMAN_IMPORT_ERROR)),
+ ("pretty_midi", (is_pretty_midi_available, PRETTY_MIDI_IMPORT_ERROR)),
+ ("levenshtein", (is_levenshtein_available, LEVENSHTEIN_IMPORT_ERROR)),
+ ("librosa", (is_librosa_available, LIBROSA_IMPORT_ERROR)),
+ ("protobuf", (is_protobuf_available, PROTOBUF_IMPORT_ERROR)),
+ ("pyctcdecode", (is_pyctcdecode_available, PYCTCDECODE_IMPORT_ERROR)),
+ ("pytesseract", (is_pytesseract_available, PYTESSERACT_IMPORT_ERROR)),
+ ("sacremoses", (is_sacremoses_available, SACREMOSES_IMPORT_ERROR)),
+ ("pytorch_quantization", (is_pytorch_quantization_available, PYTORCH_QUANTIZATION_IMPORT_ERROR)),
+ ("sentencepiece", (is_sentencepiece_available, SENTENCEPIECE_IMPORT_ERROR)),
+ ("sklearn", (is_sklearn_available, SKLEARN_IMPORT_ERROR)),
+ ("speech", (is_speech_available, SPEECH_IMPORT_ERROR)),
+ ("timm", (is_timm_available, TIMM_IMPORT_ERROR)),
+ ("torchaudio", (is_torchaudio_available, TORCHAUDIO_IMPORT_ERROR)),
+ ("natten", (is_natten_available, NATTEN_IMPORT_ERROR)),
+ ("nltk", (is_nltk_available, NLTK_IMPORT_ERROR)),
+ ("tokenizers", (is_tokenizers_available, TOKENIZERS_IMPORT_ERROR)),
+ ("torch", (is_torch_available, PYTORCH_IMPORT_ERROR)),
+ ("torchvision", (is_torchvision_available, TORCHVISION_IMPORT_ERROR)),
+ ("torchcodec", (is_torchcodec_available, TORCHCODEC_IMPORT_ERROR)),
+ ("vision", (is_vision_available, VISION_IMPORT_ERROR)),
+ ("scipy", (is_scipy_available, SCIPY_IMPORT_ERROR)),
+ ("accelerate", (is_accelerate_available, ACCELERATE_IMPORT_ERROR)),
+ ("cython", (is_cython_available, CYTHON_IMPORT_ERROR)),
+ ("rjieba", (is_rjieba_available, RJIEBA_IMPORT_ERROR)),
+ ("peft", (is_peft_available, PEFT_IMPORT_ERROR)),
+ ("jinja", (is_jinja_available, JINJA_IMPORT_ERROR)),
+ ("yt_dlp", (is_yt_dlp_available, YT_DLP_IMPORT_ERROR)),
+ ("rich", (is_rich_available, RICH_IMPORT_ERROR)),
+ ("pydantic", (is_pydantic_available, PYDANTIC_IMPORT_ERROR)),
+ ("fastapi", (is_fastapi_available, FASTAPI_IMPORT_ERROR)),
+ ("uvicorn", (is_uvicorn_available, UVICORN_IMPORT_ERROR)),
+ ("openai", (is_openai_available, OPENAI_IMPORT_ERROR)),
+ ("mistral-common", (is_mistral_common_available, MISTRAL_COMMON_IMPORT_ERROR)),
+ ]
+)
+
+
+def requires_backends(obj, backends):
+ """
+ Method that automatically raises in case the specified backends are not available. It is often used during class
+ initialization to ensure the required dependencies are installed:
+
+ ```py
+ requires_backends(self, ["torch"])
+ ```
+
+ The backends should be defined in the `BACKEND_MAPPING` defined in `transformers.utils.import_utils`.
+
+ Args:
+ obj: object to be checked
+ backends: list or tuple of backends to check.
+ """
+ if not isinstance(backends, (list, tuple)):
+ backends = [backends]
+
+ name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
+
+ failed = []
+ for backend in backends:
+ if isinstance(backend, Backend):
+ available, msg = backend.is_satisfied, backend.error_message
+ else:
+ available, msg = BACKENDS_MAPPING[backend]
+
+ if not available():
+ failed.append(msg.format(name))
+
+ if failed:
+ raise ImportError("".join(failed))
+
+
+class DummyObject(type):
+ """
+ Metaclass for the dummy objects. Any class inheriting from it will return the ImportError generated by
+ `requires_backend` each time a user tries to access any method of that class.
+ """
+
+ is_dummy = True
+
+ def __getattribute__(cls, key):
+ if (key.startswith("_") and key != "_from_config") or key == "is_dummy" or key == "mro" or key == "call":
+ return super().__getattribute__(key)
+ requires_backends(cls, cls._backends)
+
+
+BACKENDS_T = frozenset[str]
+IMPORT_STRUCTURE_T = dict[BACKENDS_T, dict[str, set[str]]]
+
+
+class _LazyModule(ModuleType):
+ """
+ Module class that surfaces all objects but only performs associated imports when the objects are requested.
+ """
+
+ # Very heavily inspired by optuna.integration._IntegrationModule
+ # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py
+ def __init__(
+ self,
+ name: str,
+ module_file: str,
+ import_structure: IMPORT_STRUCTURE_T,
+ module_spec: importlib.machinery.ModuleSpec | None = None,
+ extra_objects: dict[str, object] | None = None,
+ explicit_import_shortcut: dict[str, list[str]] | None = None,
+ ):
+ super().__init__(name)
+
+ self._object_missing_backend = {}
+ self._explicit_import_shortcut = explicit_import_shortcut if explicit_import_shortcut else {}
+
+ if any(isinstance(key, frozenset) for key in import_structure):
+ self._modules = set()
+ self._class_to_module = {}
+ self.__all__ = []
+
+ _import_structure = {}
+
+ for backends, module in import_structure.items():
+ missing_backends = []
+
+ # This ensures that if a module is importable, then all other keys of the module are importable.
+ # As an example, in module.keys() we might have the following:
+ #
+ # dict_keys(['models.nllb_moe.configuration_nllb_moe', 'models.sew_d.configuration_sew_d'])
+ #
+ # with this, we don't only want to be able to import these explicitly, we want to be able to import
+ # every intermediate module as well. Therefore, this is what is returned:
+ #
+ # {
+ # 'models.nllb_moe.configuration_nllb_moe',
+ # 'models.sew_d.configuration_sew_d',
+ # 'models',
+ # 'models.sew_d', 'models.nllb_moe'
+ # }
+
+ module_keys = set(
+ chain(*[[k.rsplit(".", i)[0] for i in range(k.count(".") + 1)] for k in list(module.keys())])
+ )
+
+ for backend in backends:
+ if backend in BACKENDS_MAPPING:
+ callable, _ = BACKENDS_MAPPING[backend]
+ else:
+ if any(key in backend for key in ["=", "<", ">"]):
+ backend = Backend(backend)
+ callable = backend.is_satisfied
+ else:
+ raise ValueError(
+ f"Backend should be defined in the BACKENDS_MAPPING. Offending backend: {backend}"
+ )
+
+ try:
+ if not callable():
+ missing_backends.append(backend)
+ except (ModuleNotFoundError, RuntimeError):
+ missing_backends.append(backend)
+
+ self._modules = self._modules.union(module_keys)
+
+ for key, values in module.items():
+ if missing_backends:
+ self._object_missing_backend[key] = missing_backends
+
+ for value in values:
+ self._class_to_module[value] = key
+ if missing_backends:
+ self._object_missing_backend[value] = missing_backends
+ _import_structure.setdefault(key, []).extend(values)
+
+ # Needed for autocompletion in an IDE
+ self.__all__.extend(module_keys | set(chain(*module.values())))
+
+ self.__file__ = module_file
+ self.__spec__ = module_spec
+ self.__path__ = [os.path.dirname(module_file)]
+ self._objects = {} if extra_objects is None else extra_objects
+ self._name = name
+ self._import_structure = _import_structure
+
+ # This can be removed once every exportable object has a `require()` require.
+ else:
+ self._modules = set(import_structure.keys())
+ self._class_to_module = {}
+ for key, values in import_structure.items():
+ for value in values:
+ self._class_to_module[value] = key
+ # Needed for autocompletion in an IDE
+ self.__all__ = list(import_structure.keys()) + list(chain(*import_structure.values()))
+ self.__file__ = module_file
+ self.__spec__ = module_spec
+ self.__path__ = [os.path.dirname(module_file)]
+ self._objects = {} if extra_objects is None else extra_objects
+ self._name = name
+ self._import_structure = import_structure
+
+ # Needed for autocompletion in an IDE
+ def __dir__(self):
+ result = list(super().__dir__())
+ # The elements of self.__all__ that are submodules may or may not be in the dir already, depending on whether
+ # they have been accessed or not. So we only add the elements of self.__all__ that are not already in the dir.
+ for attr in self.__all__:
+ if attr not in result:
+ result.append(attr)
+ return result
+
+ def __getattr__(self, name: str) -> Any:
+ if name in self._objects:
+ return self._objects[name]
+ if name in self._object_missing_backend:
+ missing_backends = self._object_missing_backend[name]
+
+ class Placeholder(metaclass=DummyObject):
+ _backends = missing_backends
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, missing_backends)
+
+ def call(self, *args, **kwargs):
+ pass
+
+ Placeholder.__name__ = name
+
+ if name not in self._class_to_module:
+ module_name = f"transformers.{name}"
+ else:
+ module_name = self._class_to_module[name]
+ if not module_name.startswith("transformers."):
+ module_name = f"transformers.{module_name}"
+
+ Placeholder.__module__ = module_name
+
+ value = Placeholder
+ elif name in self._class_to_module:
+ try:
+ module = self._get_module(self._class_to_module[name])
+ value = getattr(module, name)
+ except (ModuleNotFoundError, RuntimeError, AttributeError) as e:
+ # V5: If trying to import a *TokenizerFast symbol, transparently fall back to the
+ # non-Fast symbol from the same module when available. This lets us keep only one
+ # backend tokenizer class while preserving legacy public names.
+ if name.endswith("TokenizerFast"):
+ fallback_name = name[:-4]
+ # Prefer importing the module that declares the fallback symbol if known
+ try:
+ if fallback_name in self._class_to_module:
+ fb_module = self._get_module(self._class_to_module[fallback_name])
+ fallback_value = getattr(fb_module, fallback_name)
+ else:
+ module = self._get_module(self._class_to_module[name])
+ fallback_value = getattr(module, fallback_name)
+ setattr(self, fallback_name, fallback_value)
+ value = fallback_value
+ except Exception:
+ # If we can't find the fallback here, try converter logic as a last resort
+ # before giving up
+ value = None
+ # Try converter mapping for Fast tokenizers that don't exist
+ if value is None and name.endswith("TokenizerFast"):
+ lookup_name = name[:-4]
+ try:
+ from ..convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS
+
+ if lookup_name in SLOW_TO_FAST_CONVERTERS:
+ converter_class = SLOW_TO_FAST_CONVERTERS[lookup_name]
+ converter_base_name = converter_class.__name__.replace("Converter", "")
+ preferred_tokenizer_name = f"{converter_base_name}Tokenizer"
+
+ candidate_names = [preferred_tokenizer_name]
+ for tokenizer_name, tokenizer_converter in SLOW_TO_FAST_CONVERTERS.items():
+ if tokenizer_converter is converter_class and tokenizer_name != lookup_name:
+ if tokenizer_name not in candidate_names:
+ candidate_names.append(tokenizer_name)
+
+ # Try to import the preferred candidate directly
+ import importlib
+
+ for candidate_name in candidate_names:
+ base_tokenizer_class = None
+
+ # Try to derive module path from tokenizer name (e.g., "AlbertTokenizer" -> "albert")
+ # Remove "Tokenizer" suffix and convert to lowercase
+ if candidate_name.endswith("Tokenizer"):
+ model_name = candidate_name[:-10].lower() # Remove "Tokenizer"
+ module_path = f"transformers.models.{model_name}.tokenization_{model_name}"
+ try:
+ module = importlib.import_module(module_path)
+ base_tokenizer_class = getattr(module, candidate_name)
+ except Exception:
+ logger.debug(f"{module_path} does not have {candidate_name} defined.")
+
+ # Fallback: try via _class_to_module
+ if base_tokenizer_class is None and candidate_name in self._class_to_module:
+ try:
+ alias_module_name = self._class_to_module[candidate_name]
+ alias_module = self._get_module(alias_module_name)
+ base_tokenizer_class = getattr(alias_module, candidate_name)
+ except Exception:
+ logger.debug(
+ f"{alias_module_name} does not have {candidate_name} defined"
+ )
+
+ # If we still don't have base_tokenizer_class, skip this candidate
+ if base_tokenizer_class is None:
+ logger.debug(f"skipping candidate {candidate_name}")
+ continue
+
+ # If we got here, we have base_tokenizer_class
+ value = base_tokenizer_class
+
+ setattr(self, candidate_name, base_tokenizer_class)
+ if lookup_name != candidate_name:
+ setattr(self, lookup_name, value)
+ setattr(self, name, value)
+ break
+ except Exception as e:
+ logger.debug(f"Could not create tokenizer alias: {e}")
+
+ if value is None:
+ raise ModuleNotFoundError(
+ f"Could not import module '{name}'. Are this object's requirements defined correctly?"
+ ) from e
+ else:
+ raise ModuleNotFoundError(
+ f"Could not import module '{name}'. Are this object's requirements defined correctly?"
+ ) from e
+
+ elif name in self._modules:
+ try:
+ value = self._get_module(name)
+ except (ModuleNotFoundError, RuntimeError) as e:
+ raise ModuleNotFoundError(
+ f"Could not import module '{name}'. Are this object's requirements defined correctly?"
+ ) from e
+ else:
+ # V5: If a *TokenizerFast symbol is requested but not present in the import structure,
+ # try to resolve to the corresponding non-Fast symbol's module if available.
+ if name.endswith("TokenizerFast"):
+ fallback_name = name[:-4]
+ if fallback_name in self._class_to_module:
+ try:
+ fb_module = self._get_module(self._class_to_module[fallback_name])
+ value = getattr(fb_module, fallback_name)
+ setattr(self, fallback_name, value)
+ setattr(self, name, value)
+ return value
+ except Exception as e:
+ logger.debug(f"Could not load fallback {fallback_name}: {e}")
+ # V5: If a tokenizer class doesn't exist, check if it should alias to another tokenizer
+ # via the converter mapping (e.g., FNetTokenizer -> AlbertTokenizer via AlbertConverter)
+ value = None
+ if name.endswith("Tokenizer") or name.endswith("TokenizerFast"):
+ # Strip "Fast" suffix for converter lookup if present
+ lookup_name = name[:-4] if name.endswith("TokenizerFast") else name
+
+ try:
+ # Lazy import to avoid circular dependencies
+ from ..convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS
+
+ # Check if this tokenizer has a converter mapping
+ if lookup_name in SLOW_TO_FAST_CONVERTERS:
+ converter_class = SLOW_TO_FAST_CONVERTERS[lookup_name]
+
+ # Find which tokenizer class uses the same converter (reverse lookup)
+ # Prefer the tokenizer that matches the converter name pattern
+ # (e.g., AlbertConverter -> AlbertTokenizer)
+ converter_base_name = converter_class.__name__.replace("Converter", "")
+ preferred_tokenizer_name = f"{converter_base_name}Tokenizer"
+
+ # Try preferred tokenizer first
+ candidate_names = [preferred_tokenizer_name]
+ # Then try all other tokenizers with the same converter
+ for tokenizer_name, tokenizer_converter in SLOW_TO_FAST_CONVERTERS.items():
+ if tokenizer_converter is converter_class and tokenizer_name != lookup_name:
+ if tokenizer_name not in candidate_names:
+ candidate_names.append(tokenizer_name)
+
+ # Try to import one of the candidate tokenizers
+ for candidate_name in candidate_names:
+ if candidate_name in self._class_to_module:
+ try:
+ alias_module = self._get_module(self._class_to_module[candidate_name])
+ base_tokenizer_class = getattr(alias_module, candidate_name)
+ value = base_tokenizer_class
+
+ # Cache both names for future imports
+ setattr(self, candidate_name, base_tokenizer_class)
+ if lookup_name != candidate_name:
+ setattr(self, lookup_name, value)
+ setattr(self, name, value)
+ break
+ except Exception:
+ # If this candidate fails, try the next one
+ continue
+ else:
+ # Candidate not in _class_to_module - might need recursive resolution
+ # Try importing it directly to trigger lazy loading
+ try:
+ # Try to get it from transformers module to trigger lazy loading
+ transformers_module = sys.modules.get("transformers")
+ if transformers_module and hasattr(transformers_module, candidate_name):
+ base_tokenizer_class = getattr(transformers_module, candidate_name)
+ value = base_tokenizer_class
+
+ if lookup_name != candidate_name:
+ setattr(self, lookup_name, value)
+ setattr(self, name, value)
+ break
+ except Exception:
+ continue
+ except (ImportError, AttributeError):
+ pass
+
+ if value is None:
+ for key, values in self._explicit_import_shortcut.items():
+ if name in values:
+ value = self._get_module(key)
+ break
+
+ if value is None:
+ raise AttributeError(f"module {self.__name__} has no attribute {name}")
+
+ setattr(self, name, value)
+ return value
+
+ def _get_module(self, module_name: str):
+ try:
+ return importlib.import_module("." + module_name, self.__name__)
+ except Exception as e:
+ raise e
+
+ def __reduce__(self):
+ return (self.__class__, (self._name, self.__file__, self._import_structure))
+
+
+class OptionalDependencyNotAvailable(BaseException):
+ """Internally used error class for signalling an optional dependency was not found."""
+
+
+def direct_transformers_import(path: str, file="__init__.py") -> ModuleType:
+ """Imports transformers directly
+
+ Args:
+ path (`str`): The path to the source file
+ file (`str`, *optional*): The file to join with the path. Defaults to "__init__.py".
+
+ Returns:
+ `ModuleType`: The resulting imported module
+ """
+ name = "transformers"
+ location = os.path.join(path, file)
+ spec = importlib.util.spec_from_file_location(name, location, submodule_search_locations=[path])
+ if spec is not None and spec.loader is not None:
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ module = sys.modules[name]
+ return module
+ raise ImportError(f"Could not load module {name} from {location}")
+
+
+class VersionComparison(Enum):
+ EQUAL = operator.eq
+ NOT_EQUAL = operator.ne
+ GREATER_THAN = operator.gt
+ LESS_THAN = operator.lt
+ GREATER_THAN_OR_EQUAL = operator.ge
+ LESS_THAN_OR_EQUAL = operator.le
+
+ @staticmethod
+ def from_string(version_string: str) -> "VersionComparison":
+ string_to_operator = {
+ "=": VersionComparison.EQUAL,
+ "==": VersionComparison.EQUAL,
+ "!=": VersionComparison.NOT_EQUAL,
+ ">": VersionComparison.GREATER_THAN,
+ "<": VersionComparison.LESS_THAN,
+ ">=": VersionComparison.GREATER_THAN_OR_EQUAL,
+ "<=": VersionComparison.LESS_THAN_OR_EQUAL,
+ }
+
+ return string_to_operator[version_string]
+
+
+@lru_cache
+def split_package_version(package_version_str) -> tuple[str, str, str]:
+ pattern = r"([a-zA-Z0-9_-]+)([!<>=~]+)([0-9.]+)"
+ match = re.match(pattern, package_version_str)
+ if match:
+ return (match.group(1), match.group(2), match.group(3))
+ else:
+ raise ValueError(f"Invalid package version string: {package_version_str}")
+
+
+class Backend:
+ def __init__(self, backend_requirement: str):
+ self.package_name, self.version_comparison, self.version = split_package_version(backend_requirement)
+
+ if self.package_name not in BACKENDS_MAPPING:
+ raise ValueError(
+ f"Backends should be defined in the BACKENDS_MAPPING. Offending backend: {self.package_name}"
+ )
+
+ def get_installed_version(self) -> str:
+ """Return the currently installed version of the backend"""
+ is_available, current_version = _is_package_available(self.package_name, return_version=True)
+ if not is_available:
+ raise RuntimeError(f"Backend {self.package_name} is not available.")
+ return current_version
+
+ def is_satisfied(self) -> bool:
+ return VersionComparison.from_string(self.version_comparison).value(
+ version.parse(self.get_installed_version()), version.parse(self.version)
+ )
+
+ def __repr__(self) -> str:
+ return f'Backend("{self.package_name}", {VersionComparison[self.version_comparison]}, "{self.version}")'
+
+ @property
+ def error_message(self):
+ return (
+ f"{{0}} requires the {self.package_name} library version {self.version_comparison}{self.version}. That"
+ f" library was not found with this version in your environment."
+ )
+
+
+def requires(*, backends=()):
+ """
+ This decorator enables two things:
+ - Attaching a `__backends` tuple to an object to see what are the necessary backends for it
+ to execute correctly without instantiating it
+ - The '@requires' string is used to dynamically import objects
+ """
+
+ if not isinstance(backends, tuple):
+ raise TypeError("Backends should be a tuple.")
+
+ applied_backends = []
+ for backend in backends:
+ if backend in BACKENDS_MAPPING:
+ applied_backends.append(backend)
+ else:
+ if any(key in backend for key in ["=", "<", ">"]):
+ applied_backends.append(Backend(backend))
+ else:
+ raise ValueError(f"Backend should be defined in the BACKENDS_MAPPING. Offending backend: {backend}")
+
+ def inner_fn(fun):
+ fun.__backends = applied_backends
+ return fun
+
+ return inner_fn
+
+
+BASE_FILE_REQUIREMENTS = {
+ lambda e: "modeling_" in e: ("torch",),
+ lambda e: e.startswith("tokenization_") and e.endswith("_fast"): ("tokenizers",),
+ lambda e: e.startswith("image_processing_") and e.endswith("_fast"): ("vision", "torch", "torchvision"),
+ lambda e: e.startswith("image_processing_"): ("vision",),
+ lambda e: e.startswith("video_processing_"): ("vision", "torch", "torchvision"),
+}
+
+
+def fetch__all__(file_content) -> list[str]:
+ """
+ Returns the content of the __all__ variable in the file content.
+ Returns None if not defined, otherwise returns a list of strings.
+ """
+
+ if "__all__" not in file_content:
+ return []
+
+ start_index = None
+ lines = file_content.splitlines()
+ for index, line in enumerate(lines):
+ if line.startswith("__all__"):
+ start_index = index
+
+ # There is no line starting with `__all__`
+ if start_index is None:
+ return []
+
+ lines = lines[start_index:]
+
+ if not lines[0].startswith("__all__"):
+ raise ValueError(
+ "fetch__all__ accepts a list of lines, with the first line being the __all__ variable declaration"
+ )
+
+ # __all__ is defined on a single line
+ if lines[0].endswith("]"):
+ return [obj.strip("\"' ") for obj in lines[0].split("=")[1].strip(" []").split(",")]
+
+ # __all__ is defined on multiple lines
+ else:
+ _all: list[str] = []
+ for __all__line_index in range(1, len(lines)):
+ if lines[__all__line_index].strip() == "]":
+ return _all
+ else:
+ _all.append(lines[__all__line_index].strip("\"', "))
+
+ return _all
+
+
+@lru_cache
+def create_import_structure_from_path(module_path):
+ """
+ This method takes the path to a file/a folder and returns the import structure.
+ If a file is given, it will return the import structure of the parent folder.
+
+ Import structures are designed to be digestible by `_LazyModule` objects. They are
+ created from the __all__ definitions in each files as well as the `@require` decorators
+ above methods and objects.
+
+ The import structure allows explicit display of the required backends for a given object.
+ These backends are specified in two ways:
+
+ 1. Through their `@require`, if they are exported with that decorator. This `@require` decorator
+ accepts a `backend` tuple kwarg mentioning which backends are required to run this object.
+
+ 2. If an object is defined in a file with "default" backends, it will have, at a minimum, this
+ backend specified. The default backends are defined according to the filename:
+
+ - If a file is named like `modeling_*.py`, it will have a `torch` backend
+ - If a file is named like `tokenization_*_fast.py`, it will have a `tokenizers` backend
+ - If a file is named like `image_processing*_fast.py`, it will have a `torchvision` + `torch` backend
+
+ Backends serve the purpose of displaying a clear error message to the user in case the backends are not installed.
+ Should an object be imported without its required backends being in the environment, any attempt to use the
+ object will raise an error mentioning which backend(s) should be added to the environment in order to use
+ that object.
+
+ Here's an example of an input import structure at the src.transformers.models level:
+
+ {
+ 'albert': {
+ frozenset(): {
+ 'configuration_albert': {'AlbertConfig'}
+ },
+ frozenset({'tokenizers'}): {
+ 'tokenization_albert_fast': {'AlbertTokenizer'}
+ },
+ },
+ 'align': {
+ frozenset(): {
+ 'configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
+ 'processing_align': {'AlignProcessor'}
+ },
+ },
+ 'altclip': {
+ frozenset(): {
+ 'configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
+ 'processing_altclip': {'AltCLIPProcessor'},
+ }
+ }
+ }
+ """
+ import_structure = {}
+
+ if os.path.isfile(module_path):
+ module_path = os.path.dirname(module_path)
+
+ directory = module_path
+ adjacent_modules = []
+
+ for f in os.listdir(module_path):
+ if f != "__pycache__" and os.path.isdir(os.path.join(module_path, f)):
+ import_structure[f] = create_import_structure_from_path(os.path.join(module_path, f))
+
+ elif not os.path.isdir(os.path.join(directory, f)):
+ adjacent_modules.append(f)
+
+ # We're only taking a look at files different from __init__.py
+ # We could theoretically require things directly from the __init__.py
+ # files, but this is not supported at this time.
+ if "__init__.py" in adjacent_modules:
+ adjacent_modules.remove("__init__.py")
+
+ # Modular files should not be imported
+ def find_substring(substring, list_):
+ return any(substring in x for x in list_)
+
+ if find_substring("modular_", adjacent_modules) and find_substring("modeling_", adjacent_modules):
+ adjacent_modules = [module for module in adjacent_modules if "modular_" not in module]
+
+ module_requirements = {}
+ for module_name in adjacent_modules:
+ # Only modules ending in `.py` are accepted here.
+ if not module_name.endswith(".py"):
+ continue
+
+ with open(os.path.join(directory, module_name), encoding="utf-8") as f:
+ file_content = f.read()
+
+ # Remove the .py suffix
+ module_name = module_name[:-3]
+
+ previous_line = ""
+ previous_index = 0
+
+ # Some files have some requirements by default.
+ # For example, any file named `modeling_xxx.py`
+ # should have torch as a required backend.
+ base_requirements = ()
+ for string_check, requirements in BASE_FILE_REQUIREMENTS.items():
+ if string_check(module_name):
+ base_requirements = requirements
+ break
+
+ # Objects that have a `@require` assigned to them will get exported
+ # with the backends specified in the decorator as well as the file backends.
+ exported_objects = set()
+ if "@requires" in file_content:
+ lines = file_content.split("\n")
+ for index, line in enumerate(lines):
+ # This allows exporting items with other decorators. We'll take a look
+ # at the line that follows at the same indentation level.
+ if line.startswith((" ", "\t", "@", ")")) and not line.startswith("@requires"):
+ continue
+
+ # Skipping line enables putting whatever we want between the
+ # export() call and the actual class/method definition.
+ # This is what enables having # Copied from statements, docs, etc.
+ skip_line = False
+
+ if "@requires" in previous_line:
+ skip_line = False
+
+ # Backends are defined on the same line as export
+ if "backends" in previous_line:
+ backends_string = previous_line.split("backends=")[1].split("(")[1].split(")")[0]
+ backends = tuple(sorted([b.strip("'\",") for b in backends_string.split(", ") if b]))
+
+ # Backends are defined in the lines following export, for example such as:
+ # @export(
+ # backends=(
+ # "sentencepiece",
+ # "torch",
+ # )
+ # )
+ #
+ # or
+ #
+ # @export(
+ # backends=(
+ # "sentencepiece",
+ # )
+ # )
+ elif "backends" in lines[previous_index + 1]:
+ backends = []
+ for backend_line in lines[previous_index:index]:
+ if "backends" in backend_line:
+ backend_line = backend_line.split("=")[1]
+ if '"' in backend_line or "'" in backend_line:
+ if ", " in backend_line:
+ backends.extend(backend.strip("()\"', ") for backend in backend_line.split(", "))
+ else:
+ backends.append(backend_line.strip("()\"', "))
+
+ # If the line is only a ')', then we reached the end of the backends and we break.
+ if backend_line.strip() == ")":
+ break
+ backends = tuple(backends)
+
+ # No backends are registered for export
+ else:
+ backends = ()
+
+ backends = frozenset(backends + base_requirements)
+ if backends not in module_requirements:
+ module_requirements[backends] = {}
+ if module_name not in module_requirements[backends]:
+ module_requirements[backends][module_name] = set()
+
+ if not line.startswith("class") and not line.startswith("def"):
+ skip_line = True
+ else:
+ start_index = 6 if line.startswith("class") else 4
+ object_name = line[start_index:].split("(")[0].strip(":")
+ module_requirements[backends][module_name].add(object_name)
+ exported_objects.add(object_name)
+
+ if not skip_line:
+ previous_line = line
+ previous_index = index
+
+ # All objects that are in __all__ should be exported by default.
+ # These objects are exported with the file backends.
+ if "__all__" in file_content:
+ for _all_object in fetch__all__(file_content):
+ if _all_object not in exported_objects:
+ backends = frozenset(base_requirements)
+ if backends not in module_requirements:
+ module_requirements[backends] = {}
+ if module_name not in module_requirements[backends]:
+ module_requirements[backends][module_name] = set()
+
+ module_requirements[backends][module_name].add(_all_object)
+
+ import_structure = {**module_requirements, **import_structure}
+ return import_structure
+
+
+def spread_import_structure(nested_import_structure):
+ """
+ This method takes as input an unordered import structure and brings the required backends at the top-level,
+ aggregating modules and objects under their required backends.
+
+ Here's an example of an input import structure at the src.transformers.models level:
+
+ {
+ 'albert': {
+ frozenset(): {
+ 'configuration_albert': {'AlbertConfig'}
+ },
+ frozenset({'tokenizers'}): {
+ 'tokenization_albert_fast': {'AlbertTokenizer'}
+ },
+ },
+ 'align': {
+ frozenset(): {
+ 'configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
+ 'processing_align': {'AlignProcessor'}
+ },
+ },
+ 'altclip': {
+ frozenset(): {
+ 'configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
+ 'processing_altclip': {'AltCLIPProcessor'},
+ }
+ }
+ }
+
+ Here's an example of an output import structure at the src.transformers.models level:
+
+ {
+ frozenset({'tokenizers'}): {
+ 'albert.tokenization_albert_fast': {'AlbertTokenizer'}
+ },
+ frozenset(): {
+ 'albert.configuration_albert': {'AlbertConfig'},
+ 'align.processing_align': {'AlignProcessor'},
+ 'align.configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
+ 'altclip.configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
+ 'altclip.processing_altclip': {'AltCLIPProcessor'}
+ }
+ }
+
+ """
+
+ def propagate_frozenset(unordered_import_structure):
+ frozenset_first_import_structure = {}
+ for _key, _value in unordered_import_structure.items():
+ # If the value is not a dict but a string, no need for custom manipulation
+ if not isinstance(_value, dict):
+ frozenset_first_import_structure[_key] = _value
+
+ elif any(isinstance(v, frozenset) for v in _value):
+ for k, v in _value.items():
+ if isinstance(k, frozenset):
+ # Here we want to switch around _key and k to propagate k upstream if it is a frozenset
+ if k not in frozenset_first_import_structure:
+ frozenset_first_import_structure[k] = {}
+ if _key not in frozenset_first_import_structure[k]:
+ frozenset_first_import_structure[k][_key] = {}
+
+ frozenset_first_import_structure[k][_key].update(v)
+
+ else:
+ # If k is not a frozenset, it means that the dictionary is not "level": some keys (top-level)
+ # are frozensets, whereas some are not -> frozenset keys are at an unknown depth-level of the
+ # dictionary.
+ #
+ # We recursively propagate the frozenset for this specific dictionary so that the frozensets
+ # are at the top-level when we handle them.
+ propagated_frozenset = propagate_frozenset({k: v})
+ for r_k, r_v in propagated_frozenset.items():
+ if isinstance(_key, frozenset):
+ if r_k not in frozenset_first_import_structure:
+ frozenset_first_import_structure[r_k] = {}
+ if _key not in frozenset_first_import_structure[r_k]:
+ frozenset_first_import_structure[r_k][_key] = {}
+
+ # _key is a frozenset -> we switch around the r_k and _key
+ frozenset_first_import_structure[r_k][_key].update(r_v)
+ else:
+ if _key not in frozenset_first_import_structure:
+ frozenset_first_import_structure[_key] = {}
+ if r_k not in frozenset_first_import_structure[_key]:
+ frozenset_first_import_structure[_key][r_k] = {}
+
+ # _key is not a frozenset -> we keep the order of r_k and _key
+ frozenset_first_import_structure[_key][r_k].update(r_v)
+
+ else:
+ frozenset_first_import_structure[_key] = propagate_frozenset(_value)
+
+ return frozenset_first_import_structure
+
+ def flatten_dict(_dict, previous_key=None):
+ items = []
+ for _key, _value in _dict.items():
+ _key = f"{previous_key}.{_key}" if previous_key is not None else _key
+ if isinstance(_value, dict):
+ items.extend(flatten_dict(_value, _key).items())
+ else:
+ items.append((_key, _value))
+ return dict(items)
+
+ # The tuples contain the necessary backends. We want these first, so we propagate them up the
+ # import structure.
+ ordered_import_structure = nested_import_structure
+
+ # 6 is a number that gives us sufficient depth to go through all files and foreseeable folder depths
+ # while not taking too long to parse.
+ for i in range(6):
+ ordered_import_structure = propagate_frozenset(ordered_import_structure)
+
+ # We then flatten the dict so that it references a module path.
+ flattened_import_structure = {}
+ for key, value in ordered_import_structure.copy().items():
+ if isinstance(key, str):
+ del ordered_import_structure[key]
+ else:
+ flattened_import_structure[key] = flatten_dict(value)
+
+ return flattened_import_structure
+
+
+@lru_cache
+def define_import_structure(module_path: str, prefix: str | None = None) -> IMPORT_STRUCTURE_T:
+ """
+ This method takes a module_path as input and creates an import structure digestible by a _LazyModule.
+
+ Here's an example of an output import structure at the src.transformers.models level:
+
+ {
+ frozenset({'tokenizers'}): {
+ 'albert.tokenization_albert_fast': {'AlbertTokenizer'}
+ },
+ frozenset(): {
+ 'albert.configuration_albert': {'AlbertConfig'},
+ 'align.processing_align': {'AlignProcessor'},
+ 'align.configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
+ 'altclip.configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
+ 'altclip.processing_altclip': {'AltCLIPProcessor'}
+ }
+ }
+
+ The import structure is a dict defined with frozensets as keys, and dicts of strings to sets of objects.
+
+ If `prefix` is not None, it will add that prefix to all keys in the returned dict.
+ """
+ import_structure = create_import_structure_from_path(module_path)
+ spread_dict = spread_import_structure(import_structure)
+
+ if prefix is None:
+ return spread_dict
+ else:
+ spread_dict = {k: {f"{prefix}.{kk}": vv for kk, vv in v.items()} for k, v in spread_dict.items()}
+ return spread_dict
+
+
+def clear_import_cache() -> None:
+ """
+ Clear cached Transformers modules to allow reloading modified code.
+
+ This is useful when actively developing/modifying Transformers code.
+ """
+ # Get all transformers modules
+ transformers_modules = [mod_name for mod_name in sys.modules if mod_name.startswith("transformers.")]
+
+ # Remove them from sys.modules
+ for mod_name in transformers_modules:
+ module = sys.modules[mod_name]
+ # Clear _LazyModule caches if applicable
+ if isinstance(module, _LazyModule):
+ module._objects = {} # Clear cached objects
+ del sys.modules[mod_name]
+
+ # Force reload main transformers module
+ if "transformers" in sys.modules:
+ main_module = sys.modules["transformers"]
+ if isinstance(main_module, _LazyModule):
+ main_module._objects = {} # Clear cached objects
+ importlib.reload(main_module)
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/kernel_config.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/kernel_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..742f2b6c456c32168624d4e00549a7012b38441b
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/kernel_config.py
@@ -0,0 +1,280 @@
+# 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 ..utils import PushToHubMixin, is_torch_available
+
+
+if is_torch_available():
+ import torch
+
+
+def infer_device(model):
+ """
+ Infers the device type from the model parameters.
+ Args:
+ model: The model instance.
+
+ Returns:
+ The device type.
+ """
+ EXAMPLE_MAPPING = """
+ {
+ "RMSNorm": {
+ "cuda":
+ "kernels-community/layer_norm:LlamaRMSNorm",
+ ...
+ },
+ ...
+ }
+ """
+ try:
+ param = next(model.parameters())
+ except StopIteration:
+ raise ValueError(
+ f"Cannot determine model device, please provide a device to the mapping. Example: {EXAMPLE_MAPPING}"
+ )
+
+ dev_type = param.device.type
+ if dev_type == "cuda":
+ # Refine based on actual platform
+ if torch.version.hip is not None:
+ return "rocm"
+
+ return dev_type
+
+
+def add_to_mapping(layer_name, device, repo_name, mode, compatible_mapping):
+ from kernels import LayerRepository
+
+ if device not in ["cuda", "rocm", "xpu", "npu"]:
+ raise ValueError(f"Only cuda, rocm, xpu and npu devices supported, got: {device}")
+ repo_layer_name = repo_name.split(":")[1]
+ repo_id = repo_name.split(":")[0]
+ compatible_mapping[layer_name] = {
+ device: {
+ mode: LayerRepository(
+ repo_id=repo_id,
+ layer_name=repo_layer_name,
+ )
+ }
+ }
+
+
+def add_to_mapping_local(layer_name, device, repo_name, mode, compatible_mapping):
+ from pathlib import Path
+
+ from kernels import LocalLayerRepository
+
+ if device not in ["cuda", "rocm", "xpu", "npu"]:
+ raise ValueError(f"Only cuda, rocm, xpu and npu devices supported, got: {device}")
+ repo_layer_name = repo_name.split(":")[1]
+ repo_path = repo_name.split(":")[0]
+ repo_package_name = repo_path.split("/")[-1]
+ compatible_mapping[layer_name] = {
+ device: {
+ mode: LocalLayerRepository(
+ repo_path=Path(repo_path),
+ package_name=repo_package_name,
+ layer_name=repo_layer_name,
+ )
+ }
+ }
+
+
+class KernelConfig(PushToHubMixin):
+ """
+ Kernel configuration class. This class is used to configure the kernel mapping for a model.
+ """
+
+ def __init__(self, kernel_mapping=None, use_local_kernel=False):
+ self.kernel_mapping = kernel_mapping if kernel_mapping is not None else {}
+ self.registered_layer_names = {}
+ self.use_local_kernel = use_local_kernel
+
+ def update_kernel(self, repo_id, registered_name, layer_name, device, mode, revision=None):
+ from kernels import LayerRepository
+
+ self.kernel_mapping[registered_name] = {
+ device: {
+ mode: LayerRepository(
+ repo_id=repo_id,
+ layer_name=layer_name,
+ revision=revision,
+ )
+ }
+ }
+
+ def store_registered_layer_names(self, model):
+ for name, module in model.named_modules():
+ if hasattr(module, "kernel_layer_name"):
+ self.registered_layer_names[name] = module.kernel_layer_name
+
+ def sanitize_kernel_mapping(self, model):
+ """
+ Validates the kernel_mapping to ensure that:
+ 1. Each layer_name in the mapping is registered in the model (i.e., the model contains a module with a matching kernel_layer_name).
+ 2. Each kernel value is either a string of the form 'org/repo:layer_name' or a dict mapping device types ("cuda", "rocm", "xpu", "npu") to such strings.
+ 3. Each device key in a dict is one of "cuda", "rocm", "xpu", or "npu".
+ 4. Each repo_name is a valid repository and layer name in the format 'org/repo:layer_name' (i.e., a string containing both a slash and a colon).
+ 5. If a local path is detected, it should be in the format '/abs/path:layer_name'. The absolute path must include the `package_name`, like "/home/user/layer_norm".
+
+ Args:
+ model: The model instance whose modules are checked for registered kernel_layer_name attributes.
+
+ Raises:
+ ValueError: If a layer_name is not registered in the model, if a device is not supported,
+ or if a repo_name is not a valid 'org/repo:layer_name' string.
+ """
+ MAPPING_FORMAT = """
+ For single device form remote
+ {
+ "RMSNorm":
+ "kernels-community/layer_norm:LlamaRMSNorm",
+ ...
+ },
+ For multiple devices form remote
+ {
+ "RMSNorm": {
+ "cuda":
+ "kernels-community/layer_norm:LlamaRMSNorm",
+ "rocm":
+ "kernels-community/layer_norm:LlamaRMSNorm",
+ ...
+ },
+ ...
+ }
+ For single device form local
+ {
+ "RMSNorm":
+ "/abs/path:LlamaRMSNorm",
+ ...
+ },
+ For multiple devices form local
+ {
+ "RMSNorm": {
+ "cuda":
+ "/abs/path:LlamaRMSNorm",
+ "rocm":
+ "/abs/path:LlamaRMSNorm",
+ ...
+ },
+ ...
+ }
+ """
+ self.store_registered_layer_names(model)
+ # Validate that the kernel mapping is a dict
+ if not isinstance(self.kernel_mapping, dict):
+ raise ValueError(
+ f"Kernel mapping must be a dict of the following format: {MAPPING_FORMAT}, got: {type(self.kernel_mapping)}"
+ )
+
+ for layer_name, kernel in self.kernel_mapping.items():
+ if layer_name not in self.registered_layer_names.values():
+ raise ValueError(
+ f"Layer {layer_name} is not registered in the model, please register it first using use_kernel_forward_from_hub"
+ )
+
+ if isinstance(kernel, str):
+ if "/" not in kernel or ":" not in kernel:
+ raise ValueError(
+ f"Kernel mapping for '{layer_name}' must be a valid repo name with a layer name (e.g., 'org/repo:layer_name' or '/abs/path:layer_name'), got: {kernel}"
+ )
+
+ elif isinstance(kernel, dict):
+ for device, repo_name in kernel.items():
+ if device not in ["cuda", "rocm", "xpu", "npu"]:
+ raise ValueError(f"Only cuda, rocm, xpu and npu devices supported, got: {device}")
+
+ if not isinstance(repo_name, str) or "/" not in repo_name or ":" not in repo_name:
+ raise ValueError(
+ f"Kernel mapping for '{layer_name}' must be a valid repo name with a layer name (e.g., 'org/repo:layer_name' or '/abs/path:layer_name'), got: {repo_name}"
+ )
+ else:
+ raise ValueError(f"Kernel mapping must follow the format: {MAPPING_FORMAT}, got: {kernel}")
+
+ def create_compatible_mapping(self, model, compile=False):
+ """
+ Transforms a simple kernel_mapping of the form:
+ {
+ "RMSNorm":
+ "kernels-community/layer_norm:LlamaRMSNorm",
+ ...
+ },
+
+ or for local path:
+
+ {
+ "RMSNorm":
+ "/home/user/liger_kernels:LigerRMSNorm",
+ ...
+ },
+
+ into a nested mapping:
+
+ {
+ "RMSNorm": {
+ "cuda": {
+ Mode.INFERENCE: LayerRepository(
+ repo_id="kernels-community/layer_norm",
+ layer_name="LlamaRMSNorm",
+ )
+ }
+ }
+ }
+
+ or for local path:
+
+ {
+ "RMSNorm": {
+ "cuda": {
+ Mode.INFERENCE: LocalLayerRepository(
+ repo_path=Path("/home/user/liger_kernels"),
+ package_name="liger_kernels",
+ layer_name="LigerRMSNorm",
+ )
+ }
+ }
+ }
+
+ that's compatible with the kernels library.
+
+ The device is inferred from the model's parameters if not provided.
+ The Mode is inferred from the model's training state.
+ """
+ from kernels import Mode
+
+ compatible_mapping = {}
+ current_device = infer_device(model)
+ for layer_name, kernel in self.kernel_mapping.items():
+ # Infer Mode: use Mode.TRAINING if model is training, else use Mode.INFERENCE
+ mode = Mode.TRAINING if model.training else Mode.INFERENCE
+ if compile:
+ mode = mode | Mode.TORCH_COMPILE
+
+ if isinstance(kernel, str):
+ repo_name = kernel
+ if not self.use_local_kernel:
+ add_to_mapping(layer_name, current_device, repo_name, mode, compatible_mapping)
+ else:
+ add_to_mapping_local(layer_name, current_device, repo_name, mode, compatible_mapping)
+ elif isinstance(kernel, dict):
+ for device, repo_name in kernel.items():
+ if device != current_device:
+ continue
+ if not self.use_local_kernel:
+ add_to_mapping(layer_name, device, repo_name, mode, compatible_mapping)
+ else:
+ add_to_mapping_local(layer_name, device, repo_name, mode, compatible_mapping)
+
+ self.kernel_mapping = compatible_mapping
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/loading_report.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/loading_report.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e5810abd8c1eed721f33362f50e242b16b4604c
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/loading_report.py
@@ -0,0 +1,280 @@
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import logging
+import re
+import shutil
+import sys
+from collections import OrderedDict, defaultdict
+from dataclasses import dataclass
+from typing import Any
+
+
+_DIGIT_RX = re.compile(r"(?<=\.)(\d+)(?=\.|$)") # numbers between dots or at the end
+
+
+def _pattern_of(key: str) -> str:
+ """Replace every dot-delimited integer with '*' to get the structure."""
+ return _DIGIT_RX.sub("*", key)
+
+
+def _fmt_indices(values: list[int], cutoff=10) -> str:
+ """Format a list of ints as single number, {a, ..., b}, or first...last."""
+ if len(values) == 1:
+ return str(values[0])
+ values = sorted(values)
+ if len(values) > cutoff:
+ return f"{values[0]}...{values[-1]}"
+ return ", ".join(map(str, values))
+
+
+def update_key_name(mapping: dict[str, Any]) -> dict[str, Any]:
+ """
+ Merge keys like 'layers.0.x', 'layers.1.x' into 'layers.{0, 1}.x'
+ BUT only merge together keys that have the exact same value.
+ Returns a new dict {merged_key: value}.
+ """
+ # (pattern, value) -> list[set[int]] (per-star index values)
+ not_mapping = False
+ if not isinstance(mapping, dict):
+ mapping = {k: k for k in mapping}
+ not_mapping = True
+
+ bucket: dict[str, list[set[int] | Any]] = defaultdict(list)
+ for key, val in mapping.items():
+ digs = _DIGIT_RX.findall(key)
+ patt = _pattern_of(key)
+ for i, d in enumerate(digs):
+ if len(bucket[patt]) <= i:
+ bucket[patt].append(set())
+ bucket[patt][i].add(int(d))
+ bucket[patt].append(val)
+
+ out_items = {}
+ for patt, values in bucket.items():
+ sets, val = values[:-1], values[-1]
+ parts = patt.split("*") # stars are between parts
+ final = parts[0]
+ for i in range(1, len(parts)):
+ if i - 1 < len(sets) and sets[i - 1]:
+ insert = _fmt_indices(sorted(sets[i - 1]))
+ if len(sets[i - 1]) > 1:
+ final += "{" + insert + "}"
+ else:
+ final += insert
+ else:
+ final += "*"
+ final += parts[i]
+
+ out_items[final] = val
+ out = OrderedDict(out_items)
+ if not_mapping:
+ return out.keys()
+ return out
+
+
+_ansi_re = re.compile(r"\x1b\[[0-9;]*m")
+
+
+def _strip_ansi(s: str) -> str:
+ return _ansi_re.sub("", str(s))
+
+
+def _pad(text, width):
+ t = str(text)
+ pad = max(0, width - len(_strip_ansi(t)))
+ return t + " " * pad
+
+
+def _make_table(rows, headers):
+ # compute display widths while ignoring ANSI codes
+ cols = list(zip(*([headers] + rows))) if rows else [headers]
+ widths = [max(len(_strip_ansi(x)) for x in col) for col in cols]
+ header_line = " | ".join(_pad(h, w) for h, w in zip(headers, widths))
+ sep_line = "-+-".join("-" * w for w in widths)
+ body = [" | ".join(_pad(c, w) for c, w in zip(r, widths)) for r in rows]
+ return "\n".join([header_line, sep_line] + body)
+
+
+PALETTE = {
+ "reset": "[0m",
+ "red": "[31m",
+ "yellow": "[33m",
+ "orange": "[38;5;208m",
+ "purple": "[35m",
+ "bold": "[1m",
+ "italic": "[3m",
+ "dim": "[2m",
+}
+
+
+def _color(s, color):
+ """Return color-formatted input `s` if `sys.stdout` is interactive, e.g. connected to a terminal."""
+ if sys.stdout.isatty():
+ return f"{PALETTE[color]}{s}{PALETTE['reset']}"
+ else:
+ return s
+
+
+def _get_terminal_width(default=80):
+ try:
+ return shutil.get_terminal_size().columns
+ except Exception:
+ return default
+
+
+@dataclass
+class LoadStateDictInfo:
+ """
+ Mutable container for state-dict loading results and diagnostics. Each entry in this structure is mutable,
+ and will usually be mutated in-place during the loading pipeline.
+
+ Attributes:
+ missing_keys (`set[str]`):
+ Keys that are missing from the loaded checkpoints but expected in the model's architecture.
+ unexpected_keys (`set[str]`):
+ Keys that are found in the checkpoints, but not expected in the model's architecture.
+ mismatched_keys (`set[tuple[str, tuple[int], tuple[int]]]`):
+ Keys that are found in the checkpoints and are expected in the model's architecture, but with a different shape.
+ error_msgs ( `list[str]`):
+ Some potential error messages.
+ conversion_errors (`dict[str, str]`):
+ Errors happening during the on-the-fly weight conversion process.
+ """
+
+ missing_keys: set[str]
+ unexpected_keys: set[str]
+ mismatched_keys: set[tuple[str, tuple[int], tuple[int]]]
+ error_msgs: list[str]
+ conversion_errors: dict[str, str]
+
+ def missing_and_mismatched(self):
+ """Return all effective missing keys, including `missing` and `mismatched` keys."""
+ return self.missing_keys | {k[0] for k in self.mismatched_keys}
+
+ def to_dict(self):
+ # Does not include the `conversion_errors` to be coherent with legacy reporting in the tests
+ return {
+ "missing_keys": self.missing_keys,
+ "unexpected_keys": self.unexpected_keys,
+ "mismatched_keys": self.mismatched_keys,
+ "error_msgs": self.error_msgs,
+ }
+
+ def create_loading_report(self) -> str | None:
+ """Generate the minimal table of a loading report."""
+ term_w = _get_terminal_width()
+
+ rows = []
+ tips = ""
+ if self.unexpected_keys:
+ tips += (
+ f"\n- {_color('UNEXPECTED', 'orange') + PALETTE['italic']}\t:can be ignored when loading from different "
+ "task/architecture; not ok if you expect identical arch."
+ )
+ for k in update_key_name(self.unexpected_keys):
+ status = _color("UNEXPECTED", "orange")
+ rows.append([k, status, "", ""])
+
+ if self.missing_keys:
+ tips += (
+ f"\n- {_color('MISSING', 'red') + PALETTE['italic']}\t:those params were newly initialized because missing "
+ "from the checkpoint. Consider training on your downstream task."
+ )
+ for k in update_key_name(self.missing_keys):
+ status = _color("MISSING", "red")
+ rows.append([k, status, ""])
+
+ if self.mismatched_keys:
+ tips += (
+ f"\n- {_color('MISMATCH', 'yellow') + PALETTE['italic']}\t:ckpt weights were loaded, but they did not match "
+ "the original empty weight shapes."
+ )
+ iterator = {a: (b, c) for a, b, c in self.mismatched_keys}
+ for key, (shape_ckpt, shape_model) in update_key_name(iterator).items():
+ status = _color("MISMATCH", "yellow")
+ data = [
+ key,
+ status,
+ f"Reinit due to size mismatch - ckpt: {str(shape_ckpt)} vs model:{str(shape_model)}",
+ ]
+ rows.append(data)
+
+ if self.conversion_errors:
+ tips += f"\n- {_color('CONVERSION', 'purple') + PALETTE['italic']}\t:originate from the conversion scheme"
+ for k, v in update_key_name(self.conversion_errors).items():
+ status = _color("CONVERSION", "purple")
+ _details = f"\n\n{v}\n\n"
+ rows.append([k, status, _details])
+
+ # If nothing is wrong, return None
+ if len(rows) == 0:
+ return None
+
+ headers = ["Key", "Status"]
+ if term_w > 200:
+ headers += ["Details"]
+ else:
+ headers += ["", ""]
+ table = _make_table(rows, headers=headers)
+ tips = f"\n\n{PALETTE['italic']}Notes:{tips}{PALETTE['reset']}"
+ report = table + tips
+
+ return report
+
+
+def log_state_dict_report(
+ model,
+ pretrained_model_name_or_path: str,
+ ignore_mismatched_sizes: bool,
+ loading_info: LoadStateDictInfo,
+ logger: logging.Logger | None = None,
+):
+ """
+ Log a readable report about state_dict loading issues.
+
+ This version is terminal-size aware: for very small terminals it falls back to a compact
+ Key | Status view so output doesn't wrap badly.
+ """
+ if logger is None:
+ logger = logging.getLogger(__name__)
+
+ # Re-raise errors early if needed
+ if loading_info.error_msgs:
+ error_msg = "\n\t".join(loading_info.error_msgs)
+ if "size mismatch" in error_msg:
+ error_msg += (
+ "\n\tYou may consider adding `ignore_mismatched_sizes=True` to `from_pretrained(...)` if appropriate."
+ )
+ raise RuntimeError(f"Error(s) in loading state_dict for {model.__class__.__name__}:\n\t{error_msg}")
+
+ # Create the report table
+ report = loading_info.create_loading_report()
+ if report is None:
+ return
+
+ prelude = f"{PALETTE['bold']}{model.__class__.__name__} LOAD REPORT{PALETTE['reset']} from: {pretrained_model_name_or_path}\n"
+
+ # Log the report as warning
+ logger.warning(prelude + report)
+
+ # Re-raise in those case, after the report
+ if loading_info.conversion_errors:
+ raise RuntimeError(
+ "We encountered some issues during automatic conversion of the weights. For details look at the `CONVERSION` entries of "
+ "the above report!"
+ )
+ if not ignore_mismatched_sizes and loading_info.mismatched_keys:
+ raise RuntimeError(
+ "You set `ignore_mismatched_sizes` to `False`, thus raising an error. For details look at the above report!"
+ )
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/logging.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b38b824ede7d619804342cd785969fca714c3a6
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/logging.py
@@ -0,0 +1,411 @@
+# Copyright 2020 Optuna, Hugging Face
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Logging utilities."""
+
+import functools
+import logging
+import os
+import sys
+import threading
+from logging import (
+ CRITICAL, # NOQA
+ DEBUG,
+ ERROR,
+ FATAL, # NOQA
+ INFO,
+ NOTSET, # NOQA
+ WARN, # NOQA
+ WARNING,
+)
+from logging import captureWarnings as _captureWarnings
+
+import huggingface_hub.utils as hf_hub_utils
+from tqdm import auto as tqdm_lib
+
+from ._typing import TransformersLogger
+
+
+_lock = threading.Lock()
+_default_handler: logging.Handler | None = None
+
+log_levels = {
+ "detail": logging.DEBUG, # will also print filename and line number
+ "debug": logging.DEBUG,
+ "info": logging.INFO,
+ "warning": logging.WARNING,
+ "error": logging.ERROR,
+ "critical": logging.CRITICAL,
+}
+
+_default_log_level = logging.WARNING
+
+_tqdm_active = not hf_hub_utils.are_progress_bars_disabled()
+
+
+def _get_default_logging_level():
+ """
+ If TRANSFORMERS_VERBOSITY env var is set to one of the valid choices return that as the new default level. If it is
+ not - fall back to `_default_log_level`
+ """
+ env_level_str = os.getenv("TRANSFORMERS_VERBOSITY", None)
+ if env_level_str:
+ if env_level_str in log_levels:
+ return log_levels[env_level_str]
+ else:
+ logging.getLogger().warning(
+ f"Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, "
+ f"has to be one of: {', '.join(log_levels.keys())}"
+ )
+ return _default_log_level
+
+
+def _get_library_name() -> str:
+ return __name__.split(".")[0]
+
+
+def _get_library_root_logger() -> logging.Logger:
+ return logging.getLogger(_get_library_name())
+
+
+def _configure_library_root_logger() -> None:
+ global _default_handler
+
+ with _lock:
+ if _default_handler:
+ # This library has already configured the library root logger.
+ return
+ _default_handler = logging.StreamHandler() # Set sys.stderr as stream.
+ # set defaults based on https://github.com/pyinstaller/pyinstaller/issues/7334#issuecomment-1357447176
+ if sys.stderr is None:
+ sys.stderr = open(os.devnull, "w")
+
+ _default_handler.flush = sys.stderr.flush
+
+ # Apply our default configuration to the library root logger.
+ library_root_logger = _get_library_root_logger()
+ library_root_logger.addHandler(_default_handler)
+ library_root_logger.setLevel(_get_default_logging_level())
+ # if logging level is debug, we add pathname and lineno to formatter for easy debugging
+ if os.getenv("TRANSFORMERS_VERBOSITY", None) == "detail":
+ formatter = logging.Formatter("[%(levelname)s|%(pathname)s:%(lineno)s] %(asctime)s >> %(message)s")
+ _default_handler.setFormatter(formatter)
+
+ ci = os.getenv("CI")
+ is_ci = ci is not None and ci.upper() in {"1", "ON", "YES", "TRUE"}
+ library_root_logger.propagate = is_ci
+
+
+def _reset_library_root_logger() -> None:
+ global _default_handler
+
+ with _lock:
+ if not _default_handler:
+ return
+
+ library_root_logger = _get_library_root_logger()
+ library_root_logger.removeHandler(_default_handler)
+ library_root_logger.setLevel(logging.NOTSET)
+ _default_handler = None
+
+
+def get_log_levels_dict():
+ return log_levels
+
+
+def captureWarnings(capture):
+ """
+ Calls the `captureWarnings` method from the logging library to enable management of the warnings emitted by the
+ `warnings` library.
+
+ Read more about this method here:
+ https://docs.python.org/3/library/logging.html#integration-with-the-warnings-module
+
+ All warnings will be logged through the `py.warnings` logger.
+
+ Careful: this method also adds a handler to this logger if it does not already have one, and updates the logging
+ level of that logger to the library's root logger.
+ """
+ logger = get_logger("py.warnings")
+
+ if not logger.handlers:
+ logger.addHandler(_default_handler)
+
+ logger.setLevel(_get_library_root_logger().level)
+
+ _captureWarnings(capture)
+
+
+def get_logger(name: str | None = None) -> TransformersLogger:
+ """
+ Return a logger with the specified name.
+
+ This function is not supposed to be directly accessed unless you are writing a custom transformers module.
+ """
+
+ if name is None:
+ name = _get_library_name()
+
+ _configure_library_root_logger()
+ return logging.getLogger(name)
+
+
+def get_verbosity() -> int:
+ """
+ Return the current level for the 🤗 Transformers's root logger as an int.
+
+ Returns:
+ `int`: The logging level.
+
+
+
+ 🤗 Transformers has following logging levels:
+
+ - 50: `transformers.logging.CRITICAL` or `transformers.logging.FATAL`
+ - 40: `transformers.logging.ERROR`
+ - 30: `transformers.logging.WARNING` or `transformers.logging.WARN`
+ - 20: `transformers.logging.INFO`
+ - 10: `transformers.logging.DEBUG`
+
+ """
+
+ _configure_library_root_logger()
+ return _get_library_root_logger().getEffectiveLevel()
+
+
+def set_verbosity(verbosity: int) -> None:
+ """
+ Set the verbosity level for the 🤗 Transformers's root logger.
+
+ Args:
+ verbosity (`int`):
+ Logging level, e.g., one of:
+
+ - `transformers.logging.CRITICAL` or `transformers.logging.FATAL`
+ - `transformers.logging.ERROR`
+ - `transformers.logging.WARNING` or `transformers.logging.WARN`
+ - `transformers.logging.INFO`
+ - `transformers.logging.DEBUG`
+ """
+
+ _configure_library_root_logger()
+ _get_library_root_logger().setLevel(verbosity)
+
+
+def set_verbosity_info():
+ """Set the verbosity to the `INFO` level."""
+ return set_verbosity(INFO)
+
+
+def set_verbosity_warning():
+ """Set the verbosity to the `WARNING` level."""
+ return set_verbosity(WARNING)
+
+
+def set_verbosity_debug():
+ """Set the verbosity to the `DEBUG` level."""
+ return set_verbosity(DEBUG)
+
+
+def set_verbosity_error():
+ """Set the verbosity to the `ERROR` level."""
+ return set_verbosity(ERROR)
+
+
+def disable_default_handler() -> None:
+ """Disable the default handler of the HuggingFace Transformers's root logger."""
+
+ _configure_library_root_logger()
+
+ assert _default_handler is not None
+ _get_library_root_logger().removeHandler(_default_handler)
+
+
+def enable_default_handler() -> None:
+ """Enable the default handler of the HuggingFace Transformers's root logger."""
+
+ _configure_library_root_logger()
+
+ assert _default_handler is not None
+ _get_library_root_logger().addHandler(_default_handler)
+
+
+def add_handler(handler: logging.Handler) -> None:
+ """adds a handler to the HuggingFace Transformers's root logger."""
+
+ _configure_library_root_logger()
+
+ assert handler is not None
+ _get_library_root_logger().addHandler(handler)
+
+
+def remove_handler(handler: logging.Handler) -> None:
+ """removes given handler from the HuggingFace Transformers's root logger."""
+
+ _configure_library_root_logger()
+
+ assert handler is not None and handler not in _get_library_root_logger().handlers
+ _get_library_root_logger().removeHandler(handler)
+
+
+def disable_propagation() -> None:
+ """
+ Disable propagation of the library log outputs. Note that log propagation is disabled by default.
+ """
+
+ _configure_library_root_logger()
+ _get_library_root_logger().propagate = False
+
+
+def enable_propagation() -> None:
+ """
+ Enable propagation of the library log outputs. Please disable the HuggingFace Transformers's default handler to
+ prevent double logging if the root logger has been configured.
+ """
+
+ _configure_library_root_logger()
+ _get_library_root_logger().propagate = True
+
+
+def enable_explicit_format() -> None:
+ """
+ Enable explicit formatting for every HuggingFace Transformers's logger. The explicit formatter is as follows:
+ ```
+ [LEVELNAME|FILENAME|LINE NUMBER] TIME >> MESSAGE
+ ```
+ All handlers currently bound to the root logger are affected by this method.
+ """
+ handlers = _get_library_root_logger().handlers
+
+ for handler in handlers:
+ formatter = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s")
+ handler.setFormatter(formatter)
+
+
+def reset_format() -> None:
+ """
+ Resets the formatting for HuggingFace Transformers's loggers.
+
+ All handlers currently bound to the root logger are affected by this method.
+ """
+ handlers = _get_library_root_logger().handlers
+
+ for handler in handlers:
+ handler.setFormatter(None)
+
+
+def warning_advice(self, *args, **kwargs):
+ """
+ This method is identical to `logger.warning()`, but if env var TRANSFORMERS_NO_ADVISORY_WARNINGS=1 is set, this
+ warning will not be printed
+ """
+ no_advisory_warnings = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS")
+ if no_advisory_warnings:
+ return
+ self.warning(*args, **kwargs)
+
+
+logging.Logger.warning_advice = warning_advice # type: ignore[unresolved-attribute]
+
+
+@functools.lru_cache(None)
+def warning_once(self, *args, **kwargs):
+ """
+ This method is identical to `logger.warning()`, but will emit the warning with the same message only once
+
+ Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the cache.
+ The assumption here is that all warning messages are unique across the code. If they aren't then need to switch to
+ another type of cache that includes the caller frame information in the hashing function.
+ """
+ self.warning(*args, **kwargs)
+
+
+logging.Logger.warning_once = warning_once # type: ignore[unresolved-attribute]
+
+
+@functools.lru_cache(None)
+def info_once(self, *args, **kwargs):
+ """
+ This method is identical to `logger.info()`, but will emit the info with the same message only once
+
+ Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the cache.
+ The assumption here is that all warning messages are unique across the code. If they aren't then need to switch to
+ another type of cache that includes the caller frame information in the hashing function.
+ """
+ self.info(*args, **kwargs)
+
+
+logging.Logger.info_once = info_once # type: ignore[unresolved-attribute]
+
+
+class EmptyTqdm:
+ """Dummy tqdm which doesn't do anything."""
+
+ def __init__(self, *args, **kwargs): # pylint: disable=unused-argument
+ self._iterator = args[0] if args else None
+
+ def __iter__(self):
+ return iter(self._iterator)
+
+ def __getattr__(self, _):
+ """Return empty function."""
+
+ def empty_fn(*args, **kwargs): # pylint: disable=unused-argument
+ return
+
+ return empty_fn
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, type_, value, traceback):
+ return
+
+
+class _tqdm_cls:
+ def __call__(self, *args, **kwargs):
+ if _tqdm_active:
+ return tqdm_lib.tqdm(*args, **kwargs)
+ else:
+ return EmptyTqdm(*args, **kwargs)
+
+ def set_lock(self, *args, **kwargs):
+ self._lock = None
+ if _tqdm_active:
+ return tqdm_lib.tqdm.set_lock(*args, **kwargs)
+
+ def get_lock(self):
+ if _tqdm_active:
+ return tqdm_lib.tqdm.get_lock()
+
+
+tqdm = _tqdm_cls()
+
+
+def is_progress_bar_enabled() -> bool:
+ """Return a boolean indicating whether tqdm progress bars are enabled."""
+ return bool(_tqdm_active)
+
+
+def enable_progress_bar():
+ """Enable tqdm progress bar."""
+ global _tqdm_active
+ _tqdm_active = True
+ hf_hub_utils.enable_progress_bars()
+
+
+def disable_progress_bar():
+ """Disable tqdm progress bar."""
+ global _tqdm_active
+ _tqdm_active = False
+ hf_hub_utils.disable_progress_bars()
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/metrics.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/metrics.py
new file mode 100644
index 0000000000000000000000000000000000000000..998595dd94bae6053921c5f83b46d0975b090639
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/metrics.py
@@ -0,0 +1,404 @@
+import functools
+import logging
+import time
+from collections.abc import Callable
+from enum import Enum
+from typing import Any
+
+from .import_utils import is_opentelemetry_available
+
+
+class RequestStatus(Enum):
+ """Status of a generation request through its lifecycle."""
+
+ PENDING = "pending"
+ PREFILLING = "prefilling"
+ PREFILLING_SPLIT = "prefilling_split"
+ SPLIT_PENDING_REMAINDER = "split_pending_remainder"
+ DECODING = "decoding"
+ FINISHED = "finished"
+ FAILED = "failed"
+
+
+if is_opentelemetry_available():
+ from opentelemetry import metrics
+ from opentelemetry.trace import Status, StatusCode, get_tracer
+
+ _has_opentelemetry = True
+else:
+ _has_opentelemetry = False
+
+
+def attach_tracer(tracer_name_template=None):
+ """
+ Decorator that attaches a tracer to a class.
+
+ This decorator should be applied to classes that need OpenTelemetry tracing.
+ It adds a tracer attribute to the class instance that can be used by the traced decorator.
+
+ Args:
+ tracer_name_template: Optional template string for the tracer name.
+ If provided, it should contain {module} which will be replaced with the class's full module path
+ and {class_name} for the class name.
+ If None, a default naming scheme will be used where:
+ - If the module already starts with "transformers.", it will use that directly
+ - Otherwise, it will prepend "transformers." to the module name
+
+ Returns:
+ Class decorator function
+ """
+ if not _has_opentelemetry:
+ return lambda cls: cls
+
+ def decorator(cls):
+ original_init = cls.__init__
+
+ @functools.wraps(original_init)
+ def init_with_tracer(self, *args, **kwargs):
+ original_init(self, *args, **kwargs)
+
+ module_name = cls.__module__
+ class_name = cls.__qualname__
+
+ if tracer_name_template is None:
+ if module_name.startswith("transformers."):
+ tracer_name = f"{module_name}.{class_name}"
+ else:
+ tracer_name = f"transformers.{module_name}.{class_name}"
+ else:
+ tracer_name = tracer_name_template.format(module=module_name, class_name=class_name)
+
+ self.tracer = get_tracer(tracer_name)
+
+ cls.__init__ = init_with_tracer
+ return cls
+
+ return decorator
+
+
+def traced(
+ func=None,
+ *,
+ span_name=None,
+ standalone=False,
+ additional_attributes: list[tuple[str, str, Any | Callable[[Any], Any]]] | None = None,
+):
+ """
+ Decorator to trace function calls with OpenTelemetry.
+
+ Can be used as @traced or @traced(span_name="custom_name")
+
+ Args:
+ func: The function to trace
+ span_name: Optional custom name for the span (defaults to function name)
+ standalone: If True, creates a parentless span
+ additional_attributes: Optional list of additional attributes to set on the span.
+ Each item is a tuple of (instance_attribute_name, span_attribute_key, value_or_transform_function)
+ where:
+ - instance_attribute_name: Name of the attribute to get from the class instance
+ - span_attribute_key: Key to use when setting the attribute on the span
+ - value_or_transform_function: Either a raw value to use directly, or a function to transform
+ the attribute value before setting it on the span
+
+ Returns:
+ Decorated function with tracing
+ """
+
+ def decorator(func):
+ if not _has_opentelemetry:
+ return func
+
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ instance = args[0] if args and (hasattr(func, "__self__") and func.__self__ is not None) else None
+ is_method = instance is not None
+
+ if is_method and hasattr(instance, "tracer"):
+ tracer = instance.tracer
+ else:
+ tracer = get_tracer(f"transformers.{func.__module__}.{func.__name__}")
+
+ name = span_name or func.__name__
+ span_fn = tracer.start_span if standalone else tracer.start_as_current_span
+ with span_fn(name) as span:
+ span.set_attribute("function.name", func.__name__)
+ span.set_attribute("function.module", func.__module__)
+ span.set_attribute("function.is_method", is_method)
+
+ if args:
+ for i, arg in enumerate(args):
+ if isinstance(arg, (str, int, float, bool)) or arg is None:
+ span.set_attribute(f"args.{i}", str(arg))
+ else:
+ span.set_attribute(f"args.{i}", str(type(arg)))
+ if kwargs:
+ for key, value in kwargs.items():
+ if isinstance(value, (str, int, float, bool)) or value is None:
+ span.set_attribute(f"kwargs.{key}", str(value))
+ else:
+ span.set_attribute(f"kwargs.{key}", str(type(value)))
+
+ if additional_attributes and is_method:
+ for attr_config in additional_attributes:
+ instance_attribute_name, span_attribute_key, value_or_transform_function = attr_config
+ if hasattr(instance, instance_attribute_name):
+ attribute_value = getattr(instance, instance_attribute_name)
+ if callable(value_or_transform_function):
+ transformed_value = value_or_transform_function(attribute_value)
+ else:
+ transformed_value = value_or_transform_function
+ span.set_attribute(span_attribute_key, transformed_value)
+
+ try:
+ result = func(*args, **kwargs)
+ return result
+ except Exception as e:
+ span.set_status(Status(StatusCode.ERROR))
+ span.record_exception(e)
+ raise
+
+ return wrapper
+
+ if func is None:
+ return decorator
+ return decorator(func)
+
+
+logger = logging.getLogger(__name__)
+
+
+@attach_tracer()
+class ContinuousBatchProcessorMetrics:
+ """Metrics collection for ContinuousBatchProcessor."""
+
+ def __init__(self, max_batch_tokens: int):
+ """Initialize metrics for continuous batch processor.
+
+ Args:
+ max_batch_tokens: Maximum number of tokens in a batch
+ """
+ self.max_batch_tokens = max_batch_tokens
+
+ self._setup_metrics()
+
+ def _setup_metrics(self):
+ """Initialize OpenTelemetry metrics and tracing if the library is available."""
+
+ if not _has_opentelemetry:
+ logger.info(
+ "OpenTelemetry is not installed. Metrics and tracing will not be recorded."
+ "You can install it with `pip install opentelemetry-api>=1.30.0`"
+ )
+ return
+
+ self.meter = metrics.get_meter("transformers.generation.continuous_batch_processor")
+
+ # Define appropriate buckets for TTFT (typically ranges from ~50ms to several seconds)
+ ttft_buckets = [10, 25, 50, 75, 100, 150, 200, 300, 500, 750, 1000, 2000, 5000, 10000]
+
+ self.ttft_histogram = self.meter.create_histogram(
+ name="ttft_milliseconds",
+ description="Time to first token in milliseconds",
+ unit="ms",
+ explicit_bucket_boundaries_advisory=ttft_buckets,
+ )
+
+ self.active_requests_gauge = self.meter.create_gauge(
+ name="active_requests_count",
+ description="Number of active requests currently being processed",
+ unit="requests",
+ )
+
+ self.waiting_requests_gauge = self.meter.create_gauge(
+ name="waiting_requests_count",
+ description="Number of requests waiting to be processed",
+ unit="requests",
+ )
+
+ # Define appropriate buckets for request latency (similar to TTFT but with higher upper bounds)
+ latency_buckets = [50, 100, 250, 500, 1000, 2000, 5000, 10000, 20000, 30000, 60000]
+
+ self.request_latency_histogram = self.meter.create_histogram(
+ name="request_latency_milliseconds",
+ description="End-to-end latency for completed requests in milliseconds",
+ unit="ms",
+ explicit_bucket_boundaries_advisory=latency_buckets,
+ )
+
+ self.decode_prefill_ratio_gauge = self.meter.create_gauge(
+ name="decode_prefill_ratio",
+ description="Ratio of decode tokens to prefill tokens in a batch",
+ unit="ratio",
+ )
+
+ self.prefill_tokens_counter = self.meter.create_counter(
+ name="prefill_tokens_processed",
+ description="Number of prefill tokens processed",
+ unit="tokens",
+ )
+
+ self.decode_tokens_counter = self.meter.create_counter(
+ name="decode_tokens_processed",
+ description="Number of decode tokens processed",
+ unit="tokens",
+ )
+
+ # Define appropriate buckets for batch fill percentage (0-100%)
+ batch_fill_buckets = [5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 98, 100]
+
+ self.batch_fill_percentage_histogram = self.meter.create_histogram(
+ name="batch_fill_percentage",
+ description="Percentage of max_batch_tokens utilized in each batch",
+ unit="percent",
+ explicit_bucket_boundaries_advisory=batch_fill_buckets,
+ )
+
+ self.kv_cache_free_memory_gauge = self.meter.create_gauge(
+ name="kv_cache_free_memory_bytes",
+ description="Free memory of the PagedAttentionCache in bytes",
+ unit="bytes",
+ )
+
+ self.kv_cache_memory_gauge = self.meter.create_gauge(
+ name="kv_cache_memory_bytes",
+ description="Memory usage of the PagedAttentionCache in bytes",
+ unit="bytes",
+ )
+
+ @traced
+ def record_ttft_metric(self, created_time: float, request_id: str) -> None:
+ """Record Time to First Token (TTFT).
+
+ Args:
+ created_time: The time the request was created
+ request_id: The ID of the request
+ """
+ if not _has_opentelemetry:
+ return
+
+ ttft_ms = (time.time() - created_time) * 1000.0
+
+ try:
+ self.ttft_histogram.record(ttft_ms)
+ logger.debug(f"Recorded TTFT for request {request_id}: {ttft_ms:.2f}ms")
+ except Exception as e:
+ logger.warning(f"Failed to record TTFT metric: {e}")
+
+ @traced
+ def record_batch_metrics(self, requests_in_batch: list) -> None:
+ """Record metrics about the batch composition including decode/prefill ratio and batch fill percentage.
+
+ Args:
+ requests_in_batch: List of request states in the current batch
+ """
+ if not _has_opentelemetry or not requests_in_batch:
+ return
+
+ decode_tokens = 0
+ prefill_tokens = 0
+
+ for state in requests_in_batch:
+ if state.status == RequestStatus.DECODING:
+ decode_tokens += 1
+ elif state.status in [RequestStatus.PREFILLING, RequestStatus.PREFILLING_SPLIT]:
+ prefill_tokens += len(state.prompt_ids)
+
+ total_batch_tokens = decode_tokens + prefill_tokens
+
+ try:
+ if prefill_tokens > 0:
+ self.prefill_tokens_counter.add(prefill_tokens)
+
+ if decode_tokens > 0:
+ self.decode_tokens_counter.add(decode_tokens)
+
+ if prefill_tokens > 0:
+ ratio = decode_tokens / prefill_tokens
+ self.decode_prefill_ratio_gauge.set(ratio)
+
+ fill_percentage = (total_batch_tokens / self.max_batch_tokens) * 100.0
+ self.batch_fill_percentage_histogram.record(fill_percentage)
+ logger.debug(
+ f"Batch metrics: {decode_tokens} decode tokens, {prefill_tokens} prefill tokens, "
+ f"batch fill: {fill_percentage:.2f}% ({total_batch_tokens}/{self.max_batch_tokens})"
+ )
+ except Exception as e:
+ logger.warning(f"Failed to record batch metrics: {e}")
+
+ @traced
+ def record_kv_cache_memory_metrics(self, cache) -> None:
+ """Record memory usage of the PagedAttentionCache without GPU synchronization.
+
+ This calculates the theoretical memory usage based on cache configuration
+ and the number of blocks currently in use.
+
+ Args:
+ cache: The PagedAttentionCache object to measure
+ """
+ if not _has_opentelemetry:
+ return
+
+ try:
+ # Retrieve the memory footprint of the cache
+ page_size = cache.head_dim * cache.num_key_value_heads
+ page_mem_in_bytes = page_size * cache.dtype.itemsize
+ # When a block is allocated, it is for both K and V, so we multiply by 2
+ # It's also allocated across all cache tensors, so we multiply by the nb of tensors: len(cache.key_cache)
+ block_mem_in_bytes = 2 * len(cache.key_cache) * cache.block_size * page_mem_in_bytes
+
+ # Retrieve the number of used and free blocks
+ free_blocks = cache.get_num_free_blocks()
+ used_blocks = cache.num_blocks - free_blocks
+
+ # Convert that into used and free memory in bytes
+ used_memory_bytes = used_blocks * block_mem_in_bytes
+ free_memory_bytes = free_blocks * block_mem_in_bytes
+
+ # Update the telemetry gauges and add a message in the logs
+ self.kv_cache_memory_gauge.set(used_memory_bytes)
+ self.kv_cache_free_memory_gauge.set(free_memory_bytes)
+ logger.debug(
+ f"KV Cache memory: {used_memory_bytes / (1024 * 1024):.2f}MB, "
+ f"Used blocks: {used_blocks}/{cache.num_blocks} "
+ f"({used_blocks / cache.num_blocks * 100:.1f}%)"
+ )
+ except Exception as e:
+ logger.warning(f"Failed to record KV cache memory metrics: {e}")
+
+ @traced
+ def record_queue_metrics(self, active_requests: int, waiting_requests: int) -> None:
+ """Record metrics about active and waiting requests.
+
+ Args:
+ active_requests: Number of active requests
+ waiting_requests: Number of waiting requests
+ """
+ if not _has_opentelemetry:
+ return
+
+ try:
+ self.active_requests_gauge.set(active_requests)
+ self.waiting_requests_gauge.set(waiting_requests)
+ logger.debug(f"Queue metrics: {active_requests} active requests, {waiting_requests} waiting requests")
+ except Exception as e:
+ logger.warning(f"Failed to record queue metrics: {e}")
+
+ @traced
+ def record_request_completion(self, created_time: float, request_id: str) -> None:
+ """Record metrics about a completed request.
+
+ Args:
+ created_time: The time the request was created
+ request_id: The ID of the request
+ """
+ if not _has_opentelemetry:
+ return
+
+ latency_ms = (time.time() - created_time) * 1000.0
+
+ try:
+ self.request_latency_histogram.record(latency_ms)
+
+ logger.debug(f"Recorded request completion for {request_id}: {latency_ms:.2f}ms")
+ except Exception as e:
+ logger.warning(f"Failed to record request completion metric: {e}")
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/notebook.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/notebook.py
new file mode 100644
index 0000000000000000000000000000000000000000..ecbe8271fe139896c318fe69cbfc13a82c8a4269
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/notebook.py
@@ -0,0 +1,397 @@
+# Copyright 2020 Hugging Face
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import re
+import time
+from typing import Optional, TypeVar
+
+import IPython.display as disp
+
+from ..trainer_callback import TrainerCallback
+from ..trainer_utils import IntervalStrategy, has_length
+
+
+_T = TypeVar("_T")
+
+
+def _require(x: _T | None, msg: str) -> _T:
+ if x is None:
+ raise RuntimeError(msg)
+ return x
+
+
+def format_time(t):
+ "Format `t` (in seconds) to (h):mm:ss"
+ t = int(t)
+ h, m, s = t // 3600, (t // 60) % 60, t % 60
+ return f"{h}:{m:02d}:{s:02d}" if h != 0 else f"{m:02d}:{s:02d}"
+
+
+def html_progress_bar(value, total, prefix, label, width=300):
+ # docstyle-ignore
+ return f"""
+
+ """
+
+
+def text_to_html_table(items):
+ "Put the texts in `items` in an HTML table."
+ html_code = """\n"""
+ html_code += """ \n \n"""
+ for i in items[0]:
+ html_code += f" | {i} | \n"
+ html_code += "
\n \n \n"
+ for line in items[1:]:
+ html_code += " \n"
+ for elt in line:
+ elt = f"{elt:.6f}" if isinstance(elt, float) else str(elt)
+ html_code += f" | {elt} | \n"
+ html_code += "
\n"
+ html_code += " \n
"
+ return html_code
+
+
+class NotebookProgressBar:
+ """
+ A progress par for display in a notebook.
+
+ Class attributes (overridden by derived classes)
+
+ - **warmup** (`int`) -- The number of iterations to do at the beginning while ignoring `update_every`.
+ - **update_every** (`float`) -- Since calling the time takes some time, we only do it every presumed
+ `update_every` seconds. The progress bar uses the average time passed up until now to guess the next value
+ for which it will call the update.
+
+ Args:
+ total (`int`):
+ The total number of iterations to reach.
+ prefix (`str`, *optional*):
+ A prefix to add before the progress bar.
+ leave (`bool`, *optional*, defaults to `True`):
+ Whether or not to leave the progress bar once it's completed. You can always call the
+ [`~utils.notebook.NotebookProgressBar.close`] method to make the bar disappear.
+ parent ([`~notebook.NotebookTrainingTracker`], *optional*):
+ A parent object (like [`~utils.notebook.NotebookTrainingTracker`]) that spawns progress bars and handle
+ their display. If set, the object passed must have a `display()` method.
+ width (`int`, *optional*, defaults to 300):
+ The width (in pixels) that the bar will take.
+
+ Example:
+
+ ```python
+ import time
+
+ pbar = NotebookProgressBar(100)
+ for val in range(100):
+ pbar.update(val)
+ time.sleep(0.07)
+ pbar.update(100)
+ ```"""
+
+ warmup = 5
+ update_every = 0.2
+
+ def __init__(
+ self,
+ total: int,
+ prefix: str | None = None,
+ leave: bool = True,
+ parent: Optional["NotebookTrainingTracker"] = None,
+ width: int = 300,
+ ):
+ self.total = total
+ self.prefix = "" if prefix is None else prefix
+ self.leave = leave
+ self.parent = parent
+ self.width = width
+ self.last_value = None
+ self.comment = None
+ self.output = None
+ self.value = None
+ self.label = None
+ if "VSCODE_PID" in os.environ:
+ self.update_every = 0.5 # Adjusted for smooth updated as html rending is slow on VS Code
+ # This is the only adjustment required to optimize training html rending
+
+ def update(self, value: int, force_update: bool = False, comment: str | None = None):
+ """
+ The main method to update the progress bar to `value`.
+
+ Args:
+ value (`int`):
+ The value to use. Must be between 0 and `total`.
+ force_update (`bool`, *optional*, defaults to `False`):
+ Whether or not to force and update of the internal state and display (by default, the bar will wait for
+ `value` to reach the value it predicted corresponds to a time of more than the `update_every` attribute
+ since the last update to avoid adding boilerplate).
+ comment (`str`, *optional*):
+ A comment to add on the left of the progress bar.
+ """
+ self.value = value
+ if comment is not None:
+ self.comment = comment
+ if self.last_value is None:
+ self.start_time = self.last_time = time.time()
+ self.start_value = self.last_value = value
+ self.elapsed_time = self.predicted_remaining = None
+ self.first_calls = self.warmup
+ self.wait_for = 1
+ self.update_bar(value)
+ elif value <= self.last_value and not force_update:
+ return
+ elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for, self.total):
+ if self.first_calls > 0:
+ self.first_calls -= 1
+ current_time = time.time()
+ self.elapsed_time = current_time - self.start_time
+ # We could have value = self.start_value if the update is called twixe with the same start value.
+ if value > self.start_value:
+ self.average_time_per_item = self.elapsed_time / (value - self.start_value)
+ else:
+ self.average_time_per_item = None
+ if value >= self.total:
+ value = self.total
+ self.predicted_remaining = None
+ if not self.leave:
+ self.close()
+ elif self.average_time_per_item is not None:
+ self.predicted_remaining = self.average_time_per_item * (self.total - value)
+ self.update_bar(value)
+ self.last_value = value
+ self.last_time = current_time
+ if (self.average_time_per_item is None) or (self.average_time_per_item == 0):
+ self.wait_for = 1
+ else:
+ self.wait_for = max(int(self.update_every / self.average_time_per_item), 1)
+
+ def update_bar(self, value, comment=None):
+ spaced_value = " " * (len(str(self.total)) - len(str(value))) + str(value)
+ if self.elapsed_time is None:
+ self.label = f"[{spaced_value}/{self.total} : < :"
+ elif self.predicted_remaining is None:
+ self.label = f"[{spaced_value}/{self.total} {format_time(self.elapsed_time)}"
+ else:
+ self.label = (
+ f"[{spaced_value}/{self.total} {format_time(self.elapsed_time)} <"
+ f" {format_time(self.predicted_remaining)}"
+ )
+ if self.average_time_per_item == 0:
+ self.label += ", +inf it/s"
+ else:
+ self.label += f", {1 / self.average_time_per_item:.2f} it/s"
+
+ self.label += "]" if self.comment is None or len(self.comment) == 0 else f", {self.comment}]"
+ self.display()
+
+ def display(self):
+ self.html_code = html_progress_bar(self.value, self.total, self.prefix, self.label, self.width)
+ if self.parent is not None:
+ # If this is a child bar, the parent will take care of the display.
+ self.parent.display()
+ return
+ if self.output is None:
+ self.output = disp.display(disp.HTML(self.html_code), display_id=True)
+ else:
+ self.output.update(disp.HTML(self.html_code))
+
+ def close(self):
+ "Closes the progress bar."
+ if self.parent is None and self.output is not None:
+ self.output.update(disp.HTML(""))
+
+
+class NotebookTrainingTracker(NotebookProgressBar):
+ """
+ An object tracking the updates of an ongoing training with progress bars and a nice table reporting metrics.
+
+ Args:
+ num_steps (`int`): The number of steps during training. column_names (`list[str]`, *optional*):
+ The list of column names for the metrics table (will be inferred from the first call to
+ [`~utils.notebook.NotebookTrainingTracker.write_line`] if not set).
+ """
+
+ def __init__(self, num_steps, column_names=None):
+ super().__init__(num_steps)
+ self.inner_table = None if column_names is None else [column_names]
+ self.child_bar = None
+
+ def display(self):
+ self.html_code = html_progress_bar(self.value, self.total, self.prefix, self.label, self.width)
+ if self.inner_table is not None:
+ self.html_code += text_to_html_table(self.inner_table)
+ if self.child_bar is not None:
+ self.html_code += self.child_bar.html_code
+ if self.output is None:
+ self.output = disp.display(disp.HTML(self.html_code), display_id=True)
+ else:
+ self.output.update(disp.HTML(self.html_code))
+
+ def write_line(self, values):
+ """
+ Write the values in the inner table.
+
+ Args:
+ values (`dict[str, float]`): The values to display.
+ """
+ if self.inner_table is None:
+ self.inner_table = [list(values.keys()), list(values.values())]
+ else:
+ columns = self.inner_table[0]
+ for key in values:
+ if key not in columns:
+ columns.append(key)
+ self.inner_table[0] = columns
+ if len(self.inner_table) > 1:
+ last_values = self.inner_table[-1]
+ first_column = self.inner_table[0][0]
+ if last_values[0] != values[first_column]:
+ # write new line
+ self.inner_table.append([values.get(c, "No Log") for c in columns])
+ else:
+ # update last line
+ new_values = values
+ for c in columns:
+ if c not in new_values:
+ new_values[c] = last_values[columns.index(c)]
+ self.inner_table[-1] = [new_values[c] for c in columns]
+ else:
+ self.inner_table.append([values[c] for c in columns])
+
+ def add_child(self, total, prefix=None, width=300):
+ """
+ Add a child progress bar displayed under the table of metrics. The child progress bar is returned (so it can be
+ easily updated).
+
+ Args:
+ total (`int`): The number of iterations for the child progress bar.
+ prefix (`str`, *optional*): A prefix to write on the left of the progress bar.
+ width (`int`, *optional*, defaults to 300): The width (in pixels) of the progress bar.
+ """
+ self.child_bar = NotebookProgressBar(total, prefix=prefix, parent=self, width=width)
+ return self.child_bar
+
+ def remove_child(self):
+ """
+ Closes the child progress bar.
+ """
+ self.child_bar = None
+ self.display()
+
+
+class NotebookProgressCallback(TrainerCallback):
+ """
+ A [`TrainerCallback`] that displays the progress of training or evaluation, optimized for Jupyter Notebooks or
+ Google colab.
+ """
+
+ def __init__(self):
+ self.training_tracker = None
+ self.prediction_bar = None
+ self._force_next_update = False
+
+ def on_train_begin(self, args, state, control, **kwargs):
+ self.first_column = "Epoch" if args.eval_strategy == IntervalStrategy.EPOCH else "Step"
+ self.training_loss = 0
+ self.last_log = 0
+ column_names = [self.first_column] + ["Training Loss"]
+ if args.eval_strategy != IntervalStrategy.NO:
+ column_names.append("Validation Loss")
+ self.training_tracker = NotebookTrainingTracker(state.max_steps, column_names)
+
+ def on_step_end(self, args, state, control, **kwargs):
+ epoch = int(state.epoch) if int(state.epoch) == state.epoch else f"{state.epoch:.2f}"
+ tt = _require(self.training_tracker, "on_train_begin must be called before on_step_end")
+ tt.update(
+ state.global_step + 1,
+ comment=f"Epoch {epoch}/{state.num_train_epochs}",
+ force_update=self._force_next_update,
+ )
+ self._force_next_update = False
+
+ def on_prediction_step(self, args, state, control, eval_dataloader=None, **kwargs):
+ if not has_length(eval_dataloader):
+ return
+ if self.prediction_bar is None:
+ if self.training_tracker is not None:
+ self.prediction_bar = self.training_tracker.add_child(len(eval_dataloader))
+ else:
+ self.prediction_bar = NotebookProgressBar(len(eval_dataloader))
+ self.prediction_bar.update(1)
+ else:
+ self.prediction_bar.update(self.prediction_bar.value + 1)
+
+ def on_predict(self, args, state, control, **kwargs):
+ if self.prediction_bar is not None:
+ self.prediction_bar.close()
+ self.prediction_bar = None
+
+ def on_log(self, args, state, control, logs=None, **kwargs):
+ # Only for when there is no evaluation
+ if args.eval_strategy == IntervalStrategy.NO and "loss" in logs:
+ tt = _require(self.training_tracker, "on_train_begin must be called before on_log")
+ values = {"Training Loss": logs["loss"]}
+ # First column is necessarily Step sine we're not in epoch eval strategy
+ values["Step"] = state.global_step
+ tt.write_line(values)
+
+ def on_evaluate(self, args, state, control, metrics=None, **kwargs):
+ tt = _require(self.training_tracker, "on_train_begin must be called before on_evaluate")
+
+ values = {"Training Loss": "No log", "Validation Loss": "No log"}
+ for log in reversed(state.log_history):
+ if "loss" in log:
+ values["Training Loss"] = log["loss"]
+ break
+
+ if self.first_column == "Epoch":
+ values["Epoch"] = int(state.epoch)
+ else:
+ values["Step"] = state.global_step
+ if metrics is None:
+ metrics = {}
+ metric_key_prefix = "eval"
+ for k in metrics:
+ if k.endswith("_loss"):
+ metric_key_prefix = re.sub(r"\_loss$", "", k)
+ _ = metrics.pop("total_flos", None)
+ _ = metrics.pop("epoch", None)
+ _ = metrics.pop(f"{metric_key_prefix}_runtime", None)
+ _ = metrics.pop(f"{metric_key_prefix}_samples_per_second", None)
+ _ = metrics.pop(f"{metric_key_prefix}_steps_per_second", None)
+ for k, v in metrics.items():
+ splits = k.split("_")
+ name = " ".join([part.capitalize() for part in splits[1:]])
+ if name == "Loss":
+ # Single dataset
+ name = "Validation Loss"
+ values[name] = v
+ tt.write_line(values)
+ tt.remove_child()
+ self.prediction_bar = None
+ # Evaluation takes a long time so we should force the next update.
+ self._force_next_update = True
+
+ def on_train_end(self, args, state, control, **kwargs):
+ tt = _require(self.training_tracker, "on_train_begin must be called before on_train_end")
+ tt.update(
+ state.global_step,
+ comment=f"Epoch {int(state.epoch)}/{state.num_train_epochs}",
+ force_update=True,
+ )
+ self.training_tracker = None
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/output_capturing.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/output_capturing.py
new file mode 100644
index 0000000000000000000000000000000000000000..0aa4c0290e05dfcd1a7f2349f8c5562136ded904
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/output_capturing.py
@@ -0,0 +1,290 @@
+# Copyright 2026 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.
+"""
+Contains the logic for automatic additional output capture with our forward decorators.
+This mostly describe the hooks used and the logic to make capture thread/context safe.
+"""
+
+from __future__ import annotations
+
+import threading
+from contextvars import ContextVar
+from dataclasses import dataclass
+from functools import wraps
+from typing import TYPE_CHECKING
+
+from .import_utils import is_torchdynamo_compiling, requires
+
+
+if TYPE_CHECKING:
+ from torch import nn
+
+ from ..modeling_utils import PreTrainedModel
+
+
+_CAN_RECORD_REGISTRY = {}
+
+
+@dataclass
+@requires(backends=("torch",))
+class OutputRecorder:
+ """
+ Configuration for recording outputs from a model via hooks.
+
+ Attributes:
+ target_class (Type): The class (e.g., nn.Module) to which the hook will be attached.
+ index (Optional[int]): If the output is a tuple/list, optionally record only at a specific index.
+ layer_name (Optional[str]): Name of the submodule to target (if needed), e.g., "transformer.layer.3.attn".
+ class_name (Optional[str]): Name of the class to which the hook will be attached. Could be the suffix of class name in some cases.
+ """
+
+ target_class: type[nn.Module]
+ index: int = 0
+ layer_name: str | None = None
+ class_name: str | None = None
+
+
+class CompileableContextVar:
+ """
+ Convenience wrapper around a ContextVar for usage with `torch.compile`.
+ This behaves exactly as a `ContextVar`, except when compilation is triggered in which case it behaves as a simple
+ global variable. This is useful as `torch.compile` cannot trace the `get` method of `ContextVar`. This however means
+ that the access to the underlying variable is not thread-safe when compilation is triggered.
+ """
+
+ def __init__(self, name, default):
+ self.context_var = ContextVar(name, default=default)
+ self.global_var = default
+ self.compiling = False
+
+ def get(self):
+ # Set was called before and compilation was already detected
+ if self.compiling:
+ return self.global_var
+ else:
+ # Set was maybe never called, so still check it here
+ if is_torchdynamo_compiling():
+ self.is_compiling = True
+ return self.global_var
+ else:
+ return self.context_var.get()
+
+ def set(self, value):
+ if is_torchdynamo_compiling():
+ self.global_var = value
+ self.compiling = True
+ return None
+ else:
+ return self.context_var.set(value)
+
+ def reset(self, token):
+ if self.compiling or token is None:
+ self.global_var = None
+ self.compiling = False
+ else:
+ self.context_var.reset(token)
+
+
+# Thread/context-safe global variable
+_active_collector = CompileableContextVar("output_collector", default=None)
+
+
+def install_output_capuring_hook(module: nn.Module, key: str, index: int) -> None:
+ """Install the forward hook needed to capture the output described by `key` and `index` in `module`."""
+
+ def output_capturing_hook(module, args, output):
+ # Get the current thread-local collector
+ collected_outputs = _active_collector.get()
+ # If it's None or not a key we want to capture, simply return, the hook is inactive
+ if collected_outputs is None or key not in collected_outputs.keys():
+ return
+
+ if key == "hidden_states" and len(collected_outputs[key]) == 0:
+ collected_outputs[key].append(args[0])
+ if not isinstance(output, tuple):
+ collected_outputs[key].append(output)
+ elif output[index] is not None:
+ collected_outputs[key].append(output[index])
+
+ module.register_forward_hook(output_capturing_hook)
+
+
+def recursively_install_hooks(
+ parent_module: nn.Module, module_name: str, capture_tasks: list[tuple[str, OutputRecorder]]
+) -> None:
+ """
+ Recursively install all output capturing hooks on all submodules of `parent_module`.
+ Note that we need to use this recursive approach instead of simply iterating over all modules, because we want
+ to respect the `capture_tasks` of all individual submodels (`PreTrainedModel` instances) in the graph. That is, once
+ we reach a submodel in the graph, its children should use this submodel's `capture_tasks`, but other parts of the graph
+ should not.
+ """
+ from ..modeling_utils import PreTrainedModel
+
+ # First dispatch to children if needed
+ for name, module in parent_module.named_children():
+ # Keep dispatching the same `capture_tasks`
+ if not isinstance(module, PreTrainedModel):
+ recursively_install_hooks(module, f"{module_name}.{name}", capture_tasks)
+ # New Submodel: we need to dispatch its own `capture_tasks`
+ else:
+ install_all_output_capturing_hooks(module, prefix=f"{module_name}.{name}")
+
+ # Potentially install the hook on current `parent_module`
+ for key, specs in capture_tasks:
+ # The second check is for multimodals where only backbone layer suffix is available
+ if (specs.target_class is not None and isinstance(parent_module, specs.target_class)) or (
+ specs.class_name is not None and module_name.endswith(specs.class_name)
+ ):
+ if specs.layer_name is not None and specs.layer_name not in module_name:
+ continue
+ install_output_capuring_hook(parent_module, key, specs.index)
+
+
+def install_all_output_capturing_hooks(model: PreTrainedModel, prefix: str | None = None) -> None:
+ """
+ Install the output recording hooks on all the modules in `model`. Tis will take care of correctly dispatching
+ the `_can_record_outputs` property of each individual submodels in case of composite models.
+ """
+ # _can_record_outputs is None by default
+ capture_flags = _CAN_RECORD_REGISTRY.get(str(model.__class__)) or {} # there is a weak ref for executorch
+
+ capture_tasks = []
+ for key, layer_specs in capture_flags.items():
+ if not isinstance(layer_specs, list):
+ layer_specs = [layer_specs]
+ for specs in layer_specs:
+ if not isinstance(specs, OutputRecorder):
+ index = 0 if "hidden_states" in key else 1
+ class_name = None if not isinstance(specs, str) else specs
+ target_class = specs if not isinstance(specs, str) else None
+ specs = OutputRecorder(target_class=target_class, index=index, class_name=class_name)
+ capture_tasks.append((key, specs))
+
+ # Install the hooks
+ prefix = prefix if prefix is not None else ""
+ recursively_install_hooks(model, prefix, capture_tasks)
+ # Mark the model as already hooked
+ setattr(model, "_output_capturing_hooks_installed", True)
+
+
+# We need this to make sure we don't have race conditions when installing hooks, resulting in them being installed
+# several times
+_hook_installation_lock = threading.Lock()
+
+
+def maybe_install_capturing_hooks(model: PreTrainedModel) -> None:
+ """
+ Check if the model already has output capturing hooks installed, and install them if it is not already the
+ case.
+ Note that this is thread-safe, in case 2 (or more) threads want to install them concurrently.
+ """
+ # First check
+ if getattr(model, "_output_capturing_hooks_installed", False):
+ return
+
+ with _hook_installation_lock:
+ # Second check, in case several threads entered this function concurrently and did not return on the
+ # previous check
+ if getattr(model, "_output_capturing_hooks_installed", False):
+ return
+ # This will install the hooks and mark the model as hooked
+ install_all_output_capturing_hooks(model)
+
+
+def capture_outputs(func=None, *, tie_last_hidden_states=True):
+ """
+ Decorator to intercept specific layer outputs through hooks. The hooks are installed only once and lazily,
+ the first time output capture is requested with the `output_xxx` kwargs/config.
+ The implementation is fully context/thread safe, except when using `torch.compile`, as dynamo is unable to trace
+ through `ContextVar` methods.
+
+ Args:
+ tie_last_hidden_states (`bool`, *optional*, defaults to `True`):
+ Whether to overwrite `out.hidden_states[-1]` with the `out.last_hidden_state`.
+ This is true for all language models and should be toggled off only if
+ `out.hidden_states[-1]` has to be the hidden state before last layer norm, which
+ is needed for some vision models (e.g. CLIP, SigLIP)
+ """
+
+ def wrapped_fn(func):
+ @wraps(func)
+ def wrapper(self, *args, **kwargs):
+ # Pop it so that internal modules always return a dict even if False is requested
+ return_dict = kwargs.pop("return_dict", getattr(self.config, "return_dict", True))
+
+ # _can_record_outputs is None by default
+ capturable_flags = _CAN_RECORD_REGISTRY.get(str(self.__class__)) or {}
+ recordable_keys = {
+ f"output_{k}": kwargs.get(f"output_{k}", getattr(self.config, f"output_{k}", False))
+ for k in capturable_flags
+ }
+ # For BC as cross-attentions used to be captured with `output_attentions`
+ if "cross_attentions" in capturable_flags:
+ recordable_keys["output_cross_attentions"] = kwargs.get(
+ "output_attentions", getattr(self.config, "output_attentions", False)
+ )
+ # The sam model variants need this annoying exception as well...
+ if "mask_decoder_attentions" in capturable_flags:
+ recordable_keys["output_mask_decoder_attentions"] = kwargs.get(
+ "output_attentions", getattr(self.config, "output_attentions", False)
+ )
+
+ collected_outputs = {k.replace("output_", ""): [] for k, v in recordable_keys.items() if v}
+ # Make sure hooks are installed if we need to collect outputs
+ if len(collected_outputs) > 0:
+ maybe_install_capturing_hooks(self)
+ # Let's activate the output collector hooks if needed!
+ output_token = _active_collector.set(collected_outputs)
+
+ # Run the forward
+ try:
+ outputs = func(self, *args, **kwargs)
+ # Reset the states
+ finally:
+ _active_collector.reset(output_token)
+
+ # Inject collected outputs into model output (return everything as tuples for BC)
+ for key in collected_outputs:
+ if key == "hidden_states":
+ if not tie_last_hidden_states:
+ pass
+ elif hasattr(outputs, "vision_hidden_states"):
+ collected_outputs[key] = collected_outputs[key][:-1]
+ collected_outputs[key].append(outputs.vision_hidden_states)
+ elif hasattr(outputs, "last_hidden_state"):
+ collected_outputs[key] = collected_outputs[key][:-1]
+ collected_outputs[key].append(outputs.last_hidden_state)
+
+ outputs[key] = tuple(collected_outputs[key])
+ elif key == "attentions":
+ # In this case, the second item are cross attentions
+ if isinstance(capturable_flags[key], list) and len(capturable_flags[key]) == 2:
+ outputs[key] = tuple(collected_outputs[key][0::2])
+ outputs["cross_" + key] = tuple(collected_outputs[key][1::2])
+ else:
+ outputs[key] = tuple(collected_outputs[key])
+ else:
+ outputs[key] = tuple(collected_outputs[key])
+
+ if return_dict is False:
+ outputs = outputs.to_tuple()
+
+ return outputs
+
+ return wrapper
+
+ if func is not None:
+ return wrapped_fn(func)
+ return wrapped_fn
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/peft_utils.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/peft_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1ec093b4e672c362e9fcaecd4363d29339d4b6e
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/peft_utils.py
@@ -0,0 +1,117 @@
+# 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 importlib.metadata
+import os
+
+from packaging import version
+
+from .hub import cached_file
+from .import_utils import is_peft_available
+
+
+ADAPTER_CONFIG_NAME = "adapter_config.json"
+ADAPTER_WEIGHTS_NAME = "adapter_model.bin"
+ADAPTER_SAFE_WEIGHTS_NAME = "adapter_model.safetensors"
+
+
+def find_adapter_config_file(
+ model_id: str,
+ cache_dir: str | os.PathLike | None = None,
+ force_download: bool = False,
+ proxies: dict[str, str] | None = None,
+ token: bool | str | None = None,
+ revision: str | None = None,
+ local_files_only: bool = False,
+ subfolder: str = "",
+ _commit_hash: str | None = None,
+) -> str | None:
+ r"""
+ Simply checks if the model stored on the Hub or locally is an adapter model or not, return the path of the adapter
+ config file if it is, None otherwise.
+
+ Args:
+ model_id (`str`):
+ The identifier of the model to look for, can be either a local path or an id to the repository on the Hub.
+ cache_dir (`str` or `os.PathLike`, *optional*):
+ Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
+ cache should not be used.
+ force_download (`bool`, *optional*, defaults to `False`):
+ Whether or not to force to (re-)download the configuration files and override the cached versions if they
+ exist.
+ 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 `hf auth login` (stored in `~/.huggingface`).
+ revision (`str`, *optional*, defaults to `"main"`):
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
+ identifier allowed by git.
+
+
+
+ To test a pull request you made on the Hub, you can pass `revision="refs/pr/".
+
+
+
+ local_files_only (`bool`, *optional*, defaults to `False`):
+ If `True`, will only try to load the tokenizer configuration from local files.
+ subfolder (`str`, *optional*, defaults to `""`):
+ In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
+ specify the folder name here.
+ """
+ adapter_cached_filename = None
+ if model_id is None:
+ return None
+ elif os.path.isdir(model_id):
+ list_remote_files = os.listdir(model_id)
+ if ADAPTER_CONFIG_NAME in list_remote_files:
+ adapter_cached_filename = os.path.join(model_id, ADAPTER_CONFIG_NAME)
+ else:
+ adapter_cached_filename = cached_file(
+ model_id,
+ ADAPTER_CONFIG_NAME,
+ cache_dir=cache_dir,
+ force_download=force_download,
+ proxies=proxies,
+ token=token,
+ revision=revision,
+ local_files_only=local_files_only,
+ subfolder=subfolder,
+ _commit_hash=_commit_hash,
+ _raise_exceptions_for_gated_repo=False,
+ _raise_exceptions_for_missing_entries=False,
+ _raise_exceptions_for_connection_errors=False,
+ )
+
+ return adapter_cached_filename
+
+
+def check_peft_version(min_version: str) -> None:
+ r"""
+ Checks if the version of PEFT is compatible.
+
+ Args:
+ version (`str`):
+ The version of PEFT to check against.
+ """
+ if not is_peft_available():
+ raise ValueError("PEFT is not installed. Please install it with `pip install peft`")
+
+ is_peft_version_compatible = version.parse(importlib.metadata.version("peft")) >= version.parse(min_version)
+
+ if not is_peft_version_compatible:
+ raise ValueError(f"The version of PEFT you are using is not compatible, please use a version >= {min_version}")
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/pytest_helpers.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/pytest_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f22e01ba5081318e38f591d15f29ad833a7aa2d
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/pytest_helpers.py
@@ -0,0 +1,111 @@
+import argparse
+import json
+import re
+from collections import Counter
+from pathlib import Path
+
+
+def _base_test_name(nodeid: str) -> str:
+ # Strip parameters like [param=..] from the last component
+ name = nodeid.split("::")[-1]
+ return re.sub(r"\[.*\]$", "", name)
+
+
+def _class_name(nodeid: str) -> str | None:
+ parts = nodeid.split("::")
+ # nodeid can be: file::Class::test or file::test
+ if len(parts) >= 3:
+ return parts[-2]
+ return None
+
+
+def _file_path(nodeid: str) -> str:
+ return nodeid.split("::")[0]
+
+
+def _modeling_key(file_path: str) -> str | None:
+ # Extract "xxx" from test_modeling_xxx.py
+ m = re.search(r"test_modeling_([A-Za-z0-9_]+)\.py$", file_path)
+ if m:
+ return m.group(1)
+ return None
+
+
+def summarize(report_path: str):
+ p = Path(report_path)
+ if not p.exists():
+ raise FileNotFoundError(f"Report file not found: {p.resolve()}")
+
+ data = json.loads(p.read_text())
+ tests = data.get("tests", [])
+
+ # Overall counts
+ outcomes = Counter(t.get("outcome", "unknown") for t in tests)
+
+ # Filter failures (pytest-json-report uses "failed" and may have "error")
+ failed = [t for t in tests if t.get("outcome") in ("failed", "error")]
+
+ # 1) Failures per test file
+ failures_per_file = Counter(_file_path(t.get("nodeid", "")) for t in failed)
+
+ # 2) Failures per class (if any; otherwise "NO_CLASS")
+ failures_per_class = Counter((_class_name(t.get("nodeid", "")) or "NO_CLASS") for t in failed)
+
+ # 3) Failures per base test name (function), aggregating parametrized cases
+ failures_per_testname = Counter(_base_test_name(t.get("nodeid", "")) for t in failed)
+
+ # 4) Failures per test_modeling_xxx (derived from filename)
+ failures_per_modeling_key = Counter()
+ for t in failed:
+ key = _modeling_key(_file_path(t.get("nodeid", "")))
+ if key:
+ failures_per_modeling_key[key] += 1
+
+ return {
+ "outcomes": outcomes,
+ "failures_per_file": failures_per_file,
+ "failures_per_class": failures_per_class,
+ "failures_per_testname": failures_per_testname,
+ "failures_per_modeling_key": failures_per_modeling_key,
+ }
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Summarize pytest JSON report failures")
+ parser.add_argument(
+ "--report", default="report.json", help="Path to pytest JSON report file (default: report.json)"
+ )
+ args = parser.parse_args()
+
+ try:
+ summary = summarize(args.report)
+ except FileNotFoundError as e:
+ print(str(e))
+ return
+
+ outcomes = summary["outcomes"]
+ print("=== Overall ===")
+ total = sum(outcomes.values())
+ print(f"Total tests: {total}")
+ for k in sorted(outcomes):
+ print(f"{k:>10}: {outcomes[k]}")
+
+ def _print_counter(title, counter: Counter, label=""):
+ print(f"\n=== {title} ===")
+ if not counter:
+ print("None")
+ return
+ for key, cnt in sorted(counter.items(), key=lambda x: (x[1], x[0])):
+ if label:
+ print(f"{cnt:4d} {label}{key}")
+ else:
+ print(f"{cnt:4d} {key}")
+
+ _print_counter("Failures per test class", summary["failures_per_class"], label="class ")
+ _print_counter("Failures per test_modeling_xxx", summary["failures_per_modeling_key"], label="model ")
+ _print_counter("Failures per test file", summary["failures_per_file"])
+ _print_counter("Failures per test name (base)", summary["failures_per_testname"])
+
+
+if __name__ == "__main__":
+ main()
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/quantization_config.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/quantization_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e51c830427ab8948bea7cbb260ec499b0ff5eeb
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/quantization_config.py
@@ -0,0 +1,2106 @@
+#!/usr/bin/env python
+
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+# Modifications Copyright (C) 2025, Advanced Micro Devices, Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import copy
+import dataclasses
+import importlib.metadata
+import json
+import os
+from dataclasses import dataclass, is_dataclass
+from enum import Enum
+from inspect import Parameter, signature
+from typing import Any, Optional, Union
+
+from packaging import version
+
+from ..utils import (
+ is_compressed_tensors_available,
+ is_hqq_available,
+ is_quark_available,
+ is_torch_available,
+ is_torchao_available,
+ logging,
+)
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+class QuantizationMethod(str, Enum):
+ BITS_AND_BYTES = "bitsandbytes"
+ GPTQ = "gptq"
+ AWQ = "awq"
+ AQLM = "aqlm"
+ VPTQ = "vptq"
+ QUANTO = "quanto"
+ EETQ = "eetq"
+ HIGGS = "higgs"
+ HQQ = "hqq"
+ COMPRESSED_TENSORS = "compressed-tensors"
+ FBGEMM_FP8 = "fbgemm_fp8"
+ TORCHAO = "torchao"
+ BITNET = "bitnet"
+ SPQR = "spqr"
+ FP8 = "fp8"
+ QUARK = "quark"
+ FPQUANT = "fp_quant"
+ AUTOROUND = "auto-round"
+ MXFP4 = "mxfp4"
+ METAL = "metal"
+ FOUR_OVER_SIX = "fouroversix"
+ SINQ = "sinq"
+
+
+class AwqFormat(str, Enum):
+ GEMM = "gemm"
+ GEMV = "gemv"
+ GEMV_FAST = "gemv_fast"
+ LLM_AWQ = "llm-awq"
+
+
+class AwqBackend(str, Enum):
+ LEGACY_AWQ = "autoawq"
+ AUTO = "auto"
+ AUTO_TRAINABLE = "auto_trainable"
+ MACHETE = "machete"
+ MARLIN = "marlin"
+ EXLLAMA_V2 = "exllama_v2"
+ EXLLAMA_V1 = "exllama_v1"
+ GEMM = "gemm"
+ GEMM_TRITON = "gemm_triton"
+ GEMV = "gemv"
+ GEMV_FAST = "gemv_fast"
+ TORCH_AWQ = "torch_awq"
+ TORCH_FUSED_AWQ = "torch_fused_awq"
+
+
+@dataclass
+class QuantizationConfigMixin:
+ """
+ Mixin class for quantization config
+ """
+
+ quant_method: QuantizationMethod
+
+ @classmethod
+ def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs):
+ """
+ Instantiates a [`QuantizationConfigMixin`] from a Python dictionary of parameters.
+
+ Args:
+ config_dict (`dict[str, Any]`):
+ Dictionary that will be used to instantiate the configuration object.
+ return_unused_kwargs (`bool`,*optional*, defaults to `False`):
+ Whether or not to return a list of unused keyword arguments. Used for `from_pretrained` method in
+ `PreTrainedModel`.
+ kwargs (`dict[str, Any]`):
+ Additional parameters from which to initialize the configuration object.
+
+ Returns:
+ [`QuantizationConfigMixin`]: The configuration object instantiated from those parameters.
+ """
+ config = cls(**config_dict)
+
+ to_remove = []
+ for key, value in kwargs.items():
+ if hasattr(config, key):
+ setattr(config, key, value)
+ to_remove.append(key)
+ for key in to_remove:
+ kwargs.pop(key, None)
+
+ if return_unused_kwargs:
+ return config, kwargs
+ else:
+ return config
+
+ def to_json_file(self, json_file_path: str | os.PathLike):
+ """
+ Save this instance to a JSON file.
+
+ Args:
+ json_file_path (`str` or `os.PathLike`):
+ Path to the JSON file in which this configuration instance's parameters will be saved.
+ use_diff (`bool`, *optional*, defaults to `True`):
+ If set to `True`, only the difference between the config instance and the default
+ `QuantizationConfig()` is serialized to JSON file.
+ """
+ with open(json_file_path, "w", encoding="utf-8") as writer:
+ config_dict = self.to_dict()
+ json_string = json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
+
+ writer.write(json_string)
+
+ def to_dict(self) -> dict[str, Any]:
+ """
+ Serializes this instance to a Python dictionary. Returns:
+ `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
+ """
+ return copy.deepcopy(self.__dict__)
+
+ def __iter__(self):
+ """allows `dict(obj)` for situations where obj may be a dict or QuantizationConfigMixin"""
+ yield from copy.deepcopy(self.__dict__).items()
+
+ def __repr__(self):
+ return f"{self.__class__.__name__} {self.to_json_string()}"
+
+ def to_diff_dict(self) -> dict[str, Any]:
+ """
+ Default behavior: no diffing implemented for this config.
+ """
+ return self.to_dict()
+
+ def to_json_string(self, use_diff: bool = True) -> str:
+ """
+ Serializes this instance to a JSON string.
+
+ Args:
+ use_diff (`bool`, *optional*, defaults to `True`):
+ If set to `True`, only the difference between the config instance and the default `PreTrainedConfig()`
+ is serialized to JSON string.
+
+ Returns:
+ `str`: String containing all the attributes that make up this configuration instance in JSON format.
+ """
+ config_dict = self.to_diff_dict() if use_diff else self.to_dict()
+ return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
+
+ def update(self, **kwargs):
+ """
+ Updates attributes of this class instance with attributes from `kwargs` if they match existing attributes,
+ returning all the unused kwargs.
+
+ Args:
+ kwargs (`dict[str, Any]`):
+ Dictionary of attributes to tentatively update this class.
+
+ Returns:
+ `dict[str, Any]`: Dictionary containing all the key-value pairs that were not used to update the instance.
+ """
+ to_remove = []
+ for key, value in kwargs.items():
+ if hasattr(self, key):
+ setattr(self, key, value)
+ to_remove.append(key)
+
+ # Remove all the attributes that were updated, without modifying the input dict
+ unused_kwargs = {key: value for key, value in kwargs.items() if key not in to_remove}
+ return unused_kwargs
+
+
+@dataclass
+class AutoRoundConfig(QuantizationConfigMixin):
+ """This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded AutoRound quantization.
+
+ Args:
+ bits (`int`, *optional*, defaults to 4):
+ The number of bits to quantize to, supported numbers are (2, 3, 4, 8).
+ group_size (`int`, *optional*, defaults to 128): Group-size value
+ sym (`bool`, *optional*, defaults to `True`): Symmetric quantization or not
+ backend (`str`, *optional*, defaults to `"auto"`): The kernel to use, e.g., ipex,marlin, exllamav2, triton, etc. Ref. https://github.com/intel/auto-round?tab=readme-ov-file#specify-backend
+ """
+
+ def __init__(
+ self,
+ bits: int = 4,
+ group_size: int = 128,
+ sym: bool = True,
+ backend: str = "auto",
+ **kwargs,
+ ):
+ self.bits = bits
+ self.group_size = group_size
+ self.sym = sym
+ self.backend = backend
+ self.packing_format = "auto_round:gptq"
+ if kwargs is not None:
+ for key, value in kwargs.items():
+ setattr(self, key, value)
+ self.quant_method = QuantizationMethod.AUTOROUND
+ self.post_init()
+
+ def post_init(self):
+ r"""Safety checker that arguments are correct."""
+ if self.bits not in [2, 3, 4, 8]:
+ raise ValueError(f"Only support quantization to [2,3,4,8] bits but found {self.bits}")
+ if self.group_size != -1 and self.group_size <= 0:
+ raise ValueError("group_size must be greater than 0 or equal to -1")
+
+ def get_loading_attributes(self):
+ loading_attributes_dict = {"backend": self.backend}
+ return loading_attributes_dict
+
+ def to_dict(self):
+ config_dict = super().to_dict()
+ return config_dict
+
+ @classmethod
+ def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs):
+ quant_method = config_dict["quant_method"]
+ if "auto-round" not in quant_method and "gptq" not in quant_method and "awq" not in quant_method:
+ raise NotImplementedError(
+ "Failed to convert to auto_round format. Only `gptqv1`, `awq`, and `auto-round` formats are supported."
+ )
+
+ if "gptq" in quant_method and "meta" in config_dict:
+ raise NotImplementedError("Failed to convert gptq format to auto_round format. Only supports `gptqv1`")
+
+ if "awq" in quant_method and config_dict.get("version", "gemm") != "gemm":
+ raise NotImplementedError(
+ "Failed to convert awq format to auto_round format. Only supports awq format with gemm version"
+ )
+
+ if "auto-round" not in quant_method:
+ config_dict["packing_format"] = f"auto_round:{quant_method}"
+
+ return super().from_dict(config_dict, return_unused_kwargs=return_unused_kwargs, **kwargs)
+
+
+@dataclass
+class HqqConfig(QuantizationConfigMixin):
+ """
+ This is wrapper around hqq's BaseQuantizeConfig.
+
+ Args:
+ nbits (`int`, *optional*, defaults to 4):
+ Number of bits. Supported values are (8, 4, 3, 2, 1).
+ group_size (`int`, *optional*, defaults to 64):
+ Group-size value. Supported values are any value that is divisible by weight.shape[axis]).
+ view_as_float (`bool`, *optional*, defaults to `False`):
+ View the quantized weight as float (used in distributed training) if set to `True`.
+ axis (`Optional[int]`, *optional*):
+ Axis along which grouping is performed. Supported values are 0 or 1.
+ dynamic_config (dict, *optional*):
+ Parameters for dynamic configuration. The key is the name tag of the layer and the value is a quantization config.
+ If set, each layer specified by its id will use its dedicated quantization configuration.
+ skip_modules (`list[str]`, *optional*, defaults to `['lm_head']`):
+ List of `nn.Linear` layers to skip.
+ kwargs (`dict[str, Any]`, *optional*):
+ Additional parameters from which to initialize the configuration object.
+ """
+
+ def __init__(
+ self,
+ nbits: int = 4,
+ group_size: int = 64,
+ view_as_float: bool = False,
+ axis: int | None = None,
+ dynamic_config: dict | None = None,
+ skip_modules: list[str] = ["lm_head"],
+ **kwargs,
+ ):
+ if is_hqq_available():
+ from hqq.core.quantize import BaseQuantizeConfig as HQQBaseQuantizeConfig
+ else:
+ raise ImportError(
+ "A valid HQQ version (>=0.2.1) is not available. Please follow the instructions to install it: `https://github.com/mobiusml/hqq/`."
+ )
+
+ if axis is None:
+ axis = 1
+ logger.info("Setting axis=1 as faster backends such as TorchAO or BitBlas are only compatible with it.")
+
+ if axis not in [0, 1]:
+ raise ValueError("Invalid axis value. Only 0 and 1 are allowed.")
+
+ if dynamic_config is not None:
+ self.quant_config = {}
+ for key in dynamic_config:
+ self.quant_config[key] = HQQBaseQuantizeConfig(**dynamic_config[key])
+ else:
+ self.quant_config = HQQBaseQuantizeConfig(
+ nbits=nbits, group_size=group_size, view_as_float=view_as_float, axis=axis
+ )
+
+ self.quant_method = QuantizationMethod.HQQ
+ self.skip_modules = skip_modules
+
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
+ """
+
+ @classmethod
+ def from_dict(cls, config: dict[str, Any]):
+ """
+ Override from_dict, used in AutoQuantizationConfig.from_dict in quantizers/auto.py
+ """
+ instance = cls()
+ instance.quant_config = config["quant_config"]
+ instance.skip_modules = config["skip_modules"]
+ return instance
+
+ def to_dict(self) -> dict[str, Any]:
+ """
+ Serializes this instance to a Python dictionary. Returns:
+ `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
+ """
+ return {
+ "quant_config": self.quant_config,
+ "quant_method": self.quant_method,
+ "skip_modules": self.skip_modules,
+ }
+
+ def __repr__(self):
+ config_dict = self.to_dict()
+ return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n"
+
+ def to_diff_dict(self) -> dict[str, Any]:
+ """
+ Removes all attributes from config which correspond to the default config attributes for better readability and
+ serializes to a Python dictionary.
+ Returns:
+ `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
+ """
+ config_dict = self.to_dict()
+
+ # get the default config dict
+ default_config_dict = HqqConfig().to_dict()
+
+ serializable_config_dict = {}
+
+ # only serialize values that differ from the default config
+ for key, value in config_dict.items():
+ if value != default_config_dict[key]:
+ serializable_config_dict[key] = value
+
+ return serializable_config_dict
+
+
+@dataclass
+class BitsAndBytesConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded using `bitsandbytes`.
+
+ Currently only supports `LLM.int8()`, `FP4`, and `NF4` quantization. If more methods are added to `bitsandbytes`,
+ then more arguments will be added to this class.
+
+ Args:
+ load_in_8bit (`bool`, *optional*, defaults to `False`):
+ This flag is used to enable 8-bit quantization with LLM.int8().
+ load_in_4bit (`bool`, *optional*, defaults to `False`):
+ This flag is used to enable 4-bit quantization by replacing the Linear layers with FP4/NF4 layers from
+ `bitsandbytes`.
+ llm_int8_threshold (`float`, *optional*, defaults to 6.0):
+ This corresponds to the outlier threshold for outlier detection as described in `LLM.int8() : 8-bit Matrix
+ Multiplication for Transformers at Scale` paper: https://huggingface.co/papers/2208.07339 Any hidden states value
+ that is above this threshold will be considered an outlier and the operation on those values will be done
+ in fp16. Values are usually normally distributed, that is, most values are in the range [-3.5, 3.5], but
+ there are some exceptional systematic outliers that are very differently distributed for large models.
+ These outliers are often in the interval [-60, -6] or [6, 60]. Int8 quantization works well for values of
+ magnitude ~5, but beyond that, there is a significant performance penalty. A good default threshold is 6,
+ but a lower threshold might be needed for more unstable models (small models, fine-tuning).
+ llm_int8_skip_modules (`list[str]`, *optional*):
+ An explicit list of the modules that we do not want to convert in 8-bit. This is useful for models such as
+ Jukebox that has several heads in different places and not necessarily at the last position. For example
+ for `CausalLM` models, the last `lm_head` is kept in its original `dtype`.
+ llm_int8_enable_fp32_cpu_offload (`bool`, *optional*, defaults to `False`):
+ This flag is used for advanced use cases and users that are aware of this feature. If you want to split
+ your model in different parts and run some parts in int8 on GPU and some parts in fp32 on CPU, you can use
+ this flag. This is useful for offloading large models such as `google/flan-t5-xxl`. Note that the int8
+ operations will not be run on CPU.
+ llm_int8_has_fp16_weight (`bool`, *optional*, defaults to `False`):
+ This flag runs LLM.int8() with 16-bit main weights. This is useful for fine-tuning as the weights do not
+ have to be converted back and forth for the backward pass.
+ bnb_4bit_compute_dtype (`torch.dtype` or str, *optional*, defaults to `torch.float32`):
+ This sets the computational type which might be different than the input type. For example, inputs might be
+ fp32, but computation can be set to bf16 for speedups.
+ bnb_4bit_quant_type (`str`, *optional*, defaults to `"fp4"`):
+ This sets the quantization data type in the bnb.nn.Linear4Bit layers. Options are FP4 and NF4 data types
+ which are specified by `fp4` or `nf4`.
+ bnb_4bit_use_double_quant (`bool`, *optional*, defaults to `False`):
+ This flag is used for nested quantization where the quantization constants from the first quantization are
+ quantized again.
+ bnb_4bit_quant_storage (`torch.dtype` or str, *optional*, defaults to `torch.uint8`):
+ This sets the storage type to pack the quantized 4-bit params.
+ kwargs (`dict[str, Any]`, *optional*):
+ Additional parameters from which to initialize the configuration object.
+ """
+
+ def __init__(
+ self,
+ load_in_8bit=False,
+ load_in_4bit=False,
+ llm_int8_threshold=6.0,
+ llm_int8_skip_modules=None,
+ llm_int8_enable_fp32_cpu_offload=False,
+ llm_int8_has_fp16_weight=False,
+ bnb_4bit_compute_dtype=None,
+ bnb_4bit_quant_type="fp4",
+ bnb_4bit_use_double_quant=False,
+ bnb_4bit_quant_storage=None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.BITS_AND_BYTES
+
+ if load_in_4bit and load_in_8bit:
+ raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
+
+ self._load_in_8bit = load_in_8bit
+ self._load_in_4bit = load_in_4bit
+ self.llm_int8_threshold = llm_int8_threshold
+ self.llm_int8_skip_modules = llm_int8_skip_modules
+ self.llm_int8_enable_fp32_cpu_offload = llm_int8_enable_fp32_cpu_offload
+ self.llm_int8_has_fp16_weight = llm_int8_has_fp16_weight
+ self.bnb_4bit_quant_type = bnb_4bit_quant_type
+ self.bnb_4bit_use_double_quant = bnb_4bit_use_double_quant
+
+ if bnb_4bit_compute_dtype is None:
+ self.bnb_4bit_compute_dtype = torch.float32
+ elif isinstance(bnb_4bit_compute_dtype, str):
+ self.bnb_4bit_compute_dtype = getattr(torch, bnb_4bit_compute_dtype)
+ elif isinstance(bnb_4bit_compute_dtype, torch.dtype):
+ self.bnb_4bit_compute_dtype = bnb_4bit_compute_dtype
+ else:
+ raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype")
+
+ if bnb_4bit_quant_storage is None:
+ self.bnb_4bit_quant_storage = torch.uint8
+ elif isinstance(bnb_4bit_quant_storage, str):
+ if bnb_4bit_quant_storage not in ["float16", "float32", "int8", "uint8", "float64", "bfloat16"]:
+ raise ValueError(
+ "`bnb_4bit_quant_storage` must be a valid string (one of 'float16', 'float32', 'int8', 'uint8', 'float64', 'bfloat16') "
+ )
+ self.bnb_4bit_quant_storage = getattr(torch, bnb_4bit_quant_storage)
+ elif isinstance(bnb_4bit_quant_storage, torch.dtype):
+ self.bnb_4bit_quant_storage = bnb_4bit_quant_storage
+ else:
+ raise ValueError("bnb_4bit_quant_storage must be a string or a torch.dtype")
+
+ if kwargs:
+ logger.info(f"Unused kwargs: {list(kwargs.keys())}. These kwargs are not used in {self.__class__}.")
+
+ self.post_init()
+
+ @property
+ def load_in_4bit(self):
+ return self._load_in_4bit
+
+ @load_in_4bit.setter
+ def load_in_4bit(self, value: bool):
+ if not isinstance(value, bool):
+ raise TypeError("load_in_4bit must be a boolean")
+
+ if self.load_in_8bit and value:
+ raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
+ self._load_in_4bit = value
+
+ @property
+ def load_in_8bit(self):
+ return self._load_in_8bit
+
+ @load_in_8bit.setter
+ def load_in_8bit(self, value: bool):
+ if not isinstance(value, bool):
+ raise TypeError("load_in_8bit must be a boolean")
+
+ if self.load_in_4bit and value:
+ raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
+ self._load_in_8bit = value
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
+ """
+ if not isinstance(self.load_in_4bit, bool):
+ raise TypeError("load_in_4bit must be a boolean")
+
+ if not isinstance(self.load_in_8bit, bool):
+ raise TypeError("load_in_8bit must be a boolean")
+
+ if not isinstance(self.llm_int8_threshold, float):
+ raise TypeError("llm_int8_threshold must be a float")
+
+ if self.llm_int8_skip_modules is not None and not isinstance(self.llm_int8_skip_modules, list):
+ raise TypeError("llm_int8_skip_modules must be a list of strings")
+ if not isinstance(self.llm_int8_enable_fp32_cpu_offload, bool):
+ raise TypeError("llm_int8_enable_fp32_cpu_offload must be a boolean")
+
+ if not isinstance(self.llm_int8_has_fp16_weight, bool):
+ raise TypeError("llm_int8_has_fp16_weight must be a boolean")
+
+ if self.bnb_4bit_compute_dtype is not None and not isinstance(self.bnb_4bit_compute_dtype, torch.dtype):
+ raise TypeError("bnb_4bit_compute_dtype must be torch.dtype")
+
+ if not isinstance(self.bnb_4bit_quant_type, str):
+ raise TypeError("bnb_4bit_quant_type must be a string")
+
+ if not isinstance(self.bnb_4bit_use_double_quant, bool):
+ raise TypeError("bnb_4bit_use_double_quant must be a boolean")
+
+ def is_quantizable(self):
+ r"""
+ Returns `True` if the model is quantizable, `False` otherwise.
+ """
+ return self.load_in_8bit or self.load_in_4bit
+
+ def quantization_method(self):
+ r"""
+ This method returns the quantization method used for the model. If the model is not quantizable, it returns
+ `None`.
+ """
+ if self.load_in_8bit:
+ return "llm_int8"
+ elif self.load_in_4bit and self.bnb_4bit_quant_type == "fp4":
+ return "fp4"
+ elif self.load_in_4bit and self.bnb_4bit_quant_type == "nf4":
+ return "nf4"
+ else:
+ return None
+
+ def to_dict(self) -> dict[str, Any]:
+ """
+ Serializes this instance to a Python dictionary. Returns:
+ `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
+ """
+ output = copy.deepcopy(self.__dict__)
+ output["bnb_4bit_compute_dtype"] = str(output["bnb_4bit_compute_dtype"]).split(".")[1]
+ output["bnb_4bit_quant_storage"] = str(output["bnb_4bit_quant_storage"]).split(".")[1]
+ output["load_in_4bit"] = self.load_in_4bit
+ output["load_in_8bit"] = self.load_in_8bit
+
+ return output
+
+ def __repr__(self):
+ config_dict = self.to_dict()
+ return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n"
+
+ def to_diff_dict(self) -> dict[str, Any]:
+ """
+ Removes all attributes from config which correspond to the default config attributes for better readability and
+ serializes to a Python dictionary.
+
+ Returns:
+ `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
+ """
+ config_dict = self.to_dict()
+
+ # get the default config dict
+ default_config_dict = BitsAndBytesConfig().to_dict()
+
+ serializable_config_dict = {}
+
+ # only serialize values that differ from the default config
+ for key, value in config_dict.items():
+ if value != default_config_dict[key]:
+ serializable_config_dict[key] = value
+
+ return serializable_config_dict
+
+
+class ExllamaVersion(int, Enum):
+ ONE = 1
+ TWO = 2
+
+
+@dataclass
+class GPTQConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded using `optimum` api for GPTQ quantization relying on the gptqmodel backend.
+
+ Args:
+ bits (`int`):
+ The number of bits to quantize to, supported numbers are (2, 3, 4, 8).
+ tokenizer (`str` or `PreTrainedTokenizerBase`, *optional*):
+ The tokenizer used to process the dataset. You can pass either:
+ - A custom tokenizer object.
+ - A string, the *model id* of a predefined tokenizer hosted inside a model repo on huggingface.co.
+ - A path to a *directory* containing vocabulary files required by the tokenizer, for instance saved
+ using the [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
+ dataset (`Union[list[str]]`, *optional*):
+ The dataset used for quantization. You can provide your own dataset in a list of string or just use the
+ original datasets used in GPTQ paper ['wikitext2','c4','c4-new']
+ group_size (`int`, *optional*, defaults to 128):
+ The group size to use for quantization. Recommended value is 128 and -1 uses per-column quantization.
+ damp_percent (`float`, *optional*, defaults to 0.1):
+ The percent of the average Hessian diagonal to use for dampening. Recommended value is 0.1.
+ desc_act (`bool`, *optional*, defaults to `False`):
+ Whether to quantize columns in order of decreasing activation size. Setting it to False can significantly
+ speed up inference but the perplexity may become slightly worse. Also known as act-order.
+ act_group_aware (`bool`, *optional*, defaults to `True`):
+ Use GAR (group aware activation order) during quantization. Has measurable positive impact on quantization
+ quality. Only applicable when `desc_act = False`. Will forced to be `False` when `desc_act = True`.
+ sym (`bool`, *optional*, defaults to `True`):
+ Whether to use symmetric quantization.
+ true_sequential (`bool`, *optional*, defaults to `True`):
+ Whether to perform sequential quantization even within a single Transformer block. Instead of quantizing
+ the entire block at once, we perform layer-wise quantization. As a result, each layer undergoes
+ quantization using inputs that have passed through the previously quantized layers.
+ format (`str`, *optional*, defaults to `"gptq"`):
+ GPTQ weight format. `gptq` (v1) is supported by gptqmodel. `gptq_v2` is gptqmodel only.
+ meta (`dict[str, any]`, *optional*):
+ Properties, such as tooling:version, that do not directly contributes to quantization or quant inference are stored in meta.
+ i.e. `meta.quantizer`: ["optimum:_version_", "gptqmodel:_version_"]
+ backend (`str`, *optional*):
+ Controls which kernel to use. Valid values for gptqmodel are `auto`, `auto_trainable` and more. Ref gptqmodel backends:
+ https://github.com/ModelCloud/GPTQModel/blob/main/gptqmodel/utils/backend.py
+ model_seqlen (`int`, *optional*):
+ The maximum sequence length that the model can take.
+ block_name_to_quantize (`str`, *optional*):
+ The transformers block name to quantize. If None, we will infer the block name using common patterns (e.g. model.layers)
+ module_name_preceding_first_block (`list[str]`, *optional*):
+ The layers that are preceding the first Transformer block.
+ batch_size (`int`, *optional*, defaults to 1):
+ The batch size used when processing the dataset
+ pad_token_id (`int`, *optional*):
+ The pad token id. Needed to prepare the dataset when `batch_size` > 1.
+ max_input_length (`int`, *optional*):
+ The maximum input length. This is needed to initialize a buffer that depends on the maximum expected input
+ length. It is specific to the exllama backend with act-order.
+ cache_block_outputs (`bool`, *optional*, defaults to `True`):
+ Whether to cache block outputs to reuse as inputs for the succeeding block.
+ modules_in_block_to_quantize (`list[list[str]]`, *optional*):
+ List of list of module names to quantize in the specified block. This argument is useful to exclude certain linear modules from being quantized.
+ The block to quantize can be specified by setting `block_name_to_quantize`. We will quantize each list sequentially. If not set, we will quantize all linear layers.
+ Example: `modules_in_block_to_quantize =[["self_attn.k_proj", "self_attn.v_proj", "self_attn.q_proj"], ["self_attn.o_proj"]]`.
+ In this example, we will first quantize the q,k,v layers simultaneously since they are independent.
+ Then, we will quantize `self_attn.o_proj` layer with the q,k,v layers quantized. This way, we will get
+ better results since it reflects the real input `self_attn.o_proj` will get when the model is quantized.
+ """
+
+ def __init__(
+ self,
+ bits: int,
+ tokenizer: Any = None,
+ dataset: list[str] | str | None = None,
+ group_size: int = 128,
+ damp_percent: float = 0.1,
+ desc_act: bool = False,
+ act_group_aware: bool = True,
+ sym: bool = True,
+ true_sequential: bool = True,
+ format: str = "gptq",
+ meta: dict[str, Any] | None = None,
+ backend: str | None = None,
+ model_seqlen: int | None = None,
+ block_name_to_quantize: str | None = None,
+ module_name_preceding_first_block: list[str] | None = None,
+ batch_size: int = 1,
+ pad_token_id: int | None = None,
+ max_input_length: int | None = None,
+ cache_block_outputs: bool = True,
+ modules_in_block_to_quantize: list[list[str]] | None = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.GPTQ
+ self.bits = bits
+ self.tokenizer = tokenizer
+ self.dataset = dataset
+ self.group_size = group_size
+ self.damp_percent = damp_percent
+ self.desc_act = desc_act
+ self.act_group_aware = act_group_aware
+ self.sym = sym
+ self.true_sequential = true_sequential
+ self.format = format.lower()
+ # Compatible with legacy field: checkpoint_format
+ if kwargs.get("checkpoint_format") is not None:
+ self.format = kwargs.pop("checkpoint_format").lower()
+ self.meta = meta
+ self.backend = backend.lower() if isinstance(backend, str) else backend
+ self.model_seqlen = model_seqlen
+ self.block_name_to_quantize = block_name_to_quantize
+ self.module_name_preceding_first_block = module_name_preceding_first_block
+ self.batch_size = batch_size
+ self.pad_token_id = pad_token_id
+ self.max_input_length = max_input_length
+ self.cache_block_outputs = cache_block_outputs
+ self.modules_in_block_to_quantize = modules_in_block_to_quantize
+ self.post_init()
+
+ def get_loading_attributes(self):
+ attributes_dict = copy.deepcopy(self.__dict__)
+ loading_attributes = ["max_input_length", "backend"]
+ loading_attributes_dict = {i: j for i, j in attributes_dict.items() if i in loading_attributes}
+ return loading_attributes_dict
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ if self.bits not in [2, 3, 4, 8]:
+ raise ValueError(f"Only support quantization to [2,3,4,8] bits but found {self.bits}")
+ if self.group_size != -1 and self.group_size <= 0:
+ raise ValueError("group_size must be greater than 0 or equal to -1")
+ if not (0 < self.damp_percent < 1):
+ raise ValueError("damp_percent must between 0 and 1.")
+ if self.dataset is not None:
+ if isinstance(self.dataset, str):
+ if self.dataset not in ["wikitext2", "c4", "c4-new"]:
+ raise ValueError(
+ f"""You have entered a string value for dataset. You can only choose between
+ ['wikitext2','c4','c4-new'], but we found {self.dataset}"""
+ )
+ elif not isinstance(self.dataset, list):
+ raise ValueError(
+ f"""dataset needs to be either a list of string or a value in
+ ['wikitext2','c4','c4-new'], but we found {self.dataset}"""
+ )
+
+ # act_group_order is only applicable when `desc_act = False`
+ if self.desc_act and self.act_group_aware:
+ self.act_group_aware = False
+ logger.warning("`act_group_aware` has been auto-disabled as it is not compatible with `desc_act = True`.")
+
+ # make sure backend default stays consistent with gptqmodel expectations
+ if self.backend is None:
+ self.backend = "auto"
+ if self.modules_in_block_to_quantize is not None:
+ optimum_version = version.parse(importlib.metadata.version("optimum"))
+ if optimum_version < version.parse("1.15.0"):
+ raise ValueError(
+ "You current version of `optimum` does not support `modules_in_block_to_quantize` quantization argument, please upgrade `optimum` package to a version superior than 1.15.0 ."
+ )
+
+ def to_dict(self) -> dict[str, Any]:
+ config_dict = super().to_dict()
+ # Compatible with legacy field: checkpoint_format
+ config_dict["checkpoint_format"] = self.format
+ return config_dict
+
+ def to_dict_optimum(self):
+ """
+ Get compatible dict for optimum gptq config
+ """
+ return self.to_dict()
+
+ @classmethod
+ def from_dict_optimum(cls, config_dict):
+ """
+ Get compatible class with optimum gptq config dict
+ """
+
+ config = cls(**config_dict)
+ return config
+
+
+@dataclass
+class AwqConfig(GPTQConfig):
+ """
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded using `auto-awq` library awq quantization relying on auto_awq backend.
+
+ Args:
+ bits (`int`, *optional*, defaults to 4):
+ The number of bits to quantize to.
+ group_size (`int`, *optional*, defaults to 128):
+ The group size to use for quantization. Recommended value is 128 and -1 uses per-column quantization.
+ zero_point (`bool`, *optional*, defaults to `True`):
+ Whether to use zero point quantization.
+ backend (`AwqBackend`, *optional*, defaults to `AwqBackend.AUTO`):
+ The quantization backend.
+ modules_to_not_convert (`list`, *optional*, default to `None`):
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have
+ some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers).
+ Note you cannot quantize directly with transformers, please refer to `AutoAWQ` documentation for quantizing HF models.
+ """
+
+ def __init__(
+ self,
+ bits: int = 4,
+ group_size: int = 128,
+ zero_point: bool = True,
+ backend: AwqBackend = AwqBackend.AUTO,
+ modules_to_not_convert: list | None = None,
+ **kwargs,
+ ):
+ format = kwargs.pop("format", AwqFormat.GEMM)
+ # Compatible with legacy field: version
+ if kwargs.get("version") is not None:
+ format = kwargs.pop("version").lower()
+ # Compatible with legacy backend
+ if backend == AwqBackend.LEGACY_AWQ:
+ backend = AwqBackend.AUTO
+ self.zero_point = zero_point
+ self.modules_to_not_convert = modules_to_not_convert
+
+ super().__init__(bits=bits, group_size=group_size, backend=backend, format=format, **kwargs)
+ self.quant_method = QuantizationMethod.AWQ
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+
+ if self.backend == "llm-awq":
+ self.format = AwqFormat.LLM_AWQ
+ self.backend = AwqBackend.AUTO
+
+ if self.format not in AwqFormat.__members__.values():
+ raise ValueError(f"Invalid format '{self.format}'. Must be one of: {[b.value for b in AwqFormat]}")
+
+ if self.backend not in AwqBackend.__members__.values():
+ raise ValueError(f"Invalid backend '{self.backend}'. Must be one of: {[b.value for b in AwqBackend]}")
+
+ def to_dict(self) -> dict[str, Any]:
+ config_dict = super().to_dict()
+ config_dict.pop("checkpoint_format")
+ # Compatible with legacy field: version
+ config_dict["version"] = self.format
+ return config_dict
+
+
+@dataclass
+class AqlmConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about `aqlm` parameters.
+
+ Args:
+ in_group_size (`int`, *optional*, defaults to 8):
+ The group size along the input dimension.
+ out_group_size (`int`, *optional*, defaults to 1):
+ The group size along the output dimension. It's recommended to always use 1.
+ num_codebooks (`int`, *optional*, defaults to 1):
+ Number of codebooks for the Additive Quantization procedure.
+ nbits_per_codebook (`int`, *optional*, defaults to 16):
+ Number of bits encoding a single codebook vector. Codebooks size is 2**nbits_per_codebook.
+ linear_weights_not_to_quantize (`Optional[list[str]]`, *optional*):
+ List of full paths of `nn.Linear` weight parameters that shall not be quantized.
+ kwargs (`dict[str, Any]`, *optional*):
+ Additional parameters from which to initialize the configuration object.
+ """
+
+ def __init__(
+ self,
+ in_group_size: int = 8,
+ out_group_size: int = 1,
+ num_codebooks: int = 1,
+ nbits_per_codebook: int = 16,
+ linear_weights_not_to_quantize: list[str] | None = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.AQLM
+ self.in_group_size = in_group_size
+ self.out_group_size = out_group_size
+ self.num_codebooks = num_codebooks
+ self.nbits_per_codebook = nbits_per_codebook
+ self.linear_weights_not_to_quantize = linear_weights_not_to_quantize
+
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
+ """
+ if not isinstance(self.in_group_size, int):
+ raise TypeError("in_group_size must be a float")
+ if not isinstance(self.out_group_size, int):
+ raise TypeError("out_group_size must be a float")
+ if not isinstance(self.num_codebooks, int):
+ raise TypeError("num_codebooks must be a float")
+ if not isinstance(self.nbits_per_codebook, int):
+ raise TypeError("nbits_per_codebook must be a float")
+
+ if self.linear_weights_not_to_quantize is not None and not isinstance(
+ self.linear_weights_not_to_quantize, list
+ ):
+ raise ValueError("linear_weights_not_to_quantize must be a list of strings")
+
+ if self.linear_weights_not_to_quantize is None:
+ self.linear_weights_not_to_quantize = []
+
+
+@dataclass
+class VptqLayerConfig(QuantizationConfigMixin):
+ """
+ This is used to explain vptq config params for each layer
+ Args:
+ enable_norm (`bool`, *optional*, defaults to `True`): to control if we have scale/bias for fp-weight
+ enable_perm (`bool`, *optional*, defaults to `True`): to perm input_channel or not
+ group_num (`int`, *optional*, defaults to `1`): how many single groups for vector-quantization
+ group_size (`int`, *optional*, defaults to `-1`): depends on out-features
+ indices_as_float (`bool`, *optional*, defaults to `False`): for Finetuning
+ is_indice_packed (`bool`, *optional*, defaults to `True`): should always be True
+ num_centroids (`list`, *optional*, defaults to `[-1, -1]`): centroid numbers of clusters
+ num_res_centroids (`list`, *optional*, defaults to `[-1, -1]`): ditto for residual
+ outlier_size (`int`, *optional*, defaults to `1`): outliers
+ vector_lens (`list`, *optional*, defaults to `[-1, -1]`): centroid vector length in quantization
+ """
+
+ def __init__(
+ self,
+ enable_norm: bool = True,
+ enable_perm: bool = True,
+ group_num: int = 1,
+ group_size: int = -1,
+ in_features: int = -1,
+ indices_as_float: bool = False,
+ is_indice_packed: bool = True,
+ num_centroids: list = [-1, -1],
+ num_res_centroids: list = [-1, -1],
+ out_features: int = -1,
+ outlier_size: int = 0,
+ vector_lens: list = [-1, -1],
+ **kwargs,
+ ):
+ self.enable_norm = enable_norm
+ self.enable_perm = enable_perm
+ self.group_num = group_num
+ self.group_size = group_size
+ self.in_features = in_features
+ self.indices_as_float = indices_as_float
+ self.is_indice_packed = is_indice_packed
+ self.num_centroids = num_centroids
+ self.num_res_centroids = num_res_centroids
+ self.out_features = out_features
+ self.outlier_size = outlier_size
+ self.vector_lens = vector_lens
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ if self.is_indice_packed is False:
+ raise ValueError("is_indice_packed should always be True")
+
+
+@dataclass
+class VptqConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about `vptq` parameters.
+
+ Args:
+ enable_proxy_error (`bool`, *optional*, defaults to `False`): calculate proxy error for each layer
+ config_for_layers (`Dict`, *optional*, defaults to `{}`): quantization params for each layer
+ shared_layer_config (`Dict`, *optional*, defaults to `{}`): shared quantization params among layers
+ modules_to_not_convert (`list`, *optional*, default to `None`):
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have
+ some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers).
+ kwargs (`dict[str, Any]`, *optional*):
+ Additional parameters from which to initialize the configuration object.
+ """
+
+ def __init__(
+ self,
+ enable_proxy_error: bool = False,
+ config_for_layers: dict[str, Any] = {},
+ shared_layer_config: dict[str, Any] = {},
+ modules_to_not_convert: list | None = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.VPTQ
+ self.enable_proxy_error = enable_proxy_error
+ self.config_for_layers: dict[str, Any] = config_for_layers
+ self.shared_layer_config: dict[str, Any] = shared_layer_config
+ self.modules_to_not_convert = modules_to_not_convert
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ for layer_param in self.config_for_layers.values():
+ VptqLayerConfig(**layer_param)
+ if self.enable_proxy_error is True:
+ raise ValueError("enable_proxy_error should always be False until we support training")
+
+
+@dataclass
+class QuantoConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded using `quanto`.
+
+ Args:
+ weights (`str`, *optional*, defaults to `"int8"`):
+ The target dtype for the weights after quantization. Supported values are ("float8","int8","int4","int2")
+ activations (`str`, *optional*):
+ The target dtype for the activations after quantization. Supported values are (None,"int8","float8")
+ modules_to_not_convert (`list`, *optional*, default to `None`):
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have
+ some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers).
+ """
+
+ def __init__(
+ self,
+ weights="int8",
+ activations=None,
+ modules_to_not_convert: list | None = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.QUANTO
+ self.weights = weights
+ self.activations = activations
+ self.modules_to_not_convert = modules_to_not_convert
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ accepted_weights = ["float8", "int8", "int4", "int2"]
+ accepted_activations = [None, "int8", "float8"]
+ if self.weights not in accepted_weights:
+ raise ValueError(f"Only support weights in {accepted_weights} but found {self.weights}")
+ if self.activations not in accepted_activations:
+ raise ValueError(f"Only support weights in {accepted_activations} but found {self.activations}")
+
+
+@dataclass
+class EetqConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded using `eetq`.
+
+ Args:
+ weights (`str`, *optional*, defaults to `"int8"`):
+ The target dtype for the weights. Supported value is only "int8"
+ modules_to_not_convert (`list`, *optional*, default to `None`):
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have
+ some modules left in their original precision.
+ """
+
+ def __init__(
+ self,
+ weights: str = "int8",
+ modules_to_not_convert: list | None = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.EETQ
+ self.weights = weights
+ self.modules_to_not_convert = modules_to_not_convert
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ accepted_weights = ["int8"]
+ if self.weights not in accepted_weights:
+ raise ValueError(f"Only support weights in {accepted_weights} but found {self.weights}")
+
+
+class CompressedTensorsConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class that handles compressed-tensors quantization config options.
+ It is a wrapper around `compressed_tensors.QuantizationConfig`
+ Args:
+ config_groups (`typing.dict[str, typing.Union[ForwardRef('QuantizationScheme'), typing.list[str]]]`, *optional*):
+ dictionary mapping group name to a quantization scheme definition
+ format (`str`, *optional*, defaults to `"dense"`):
+ format the model is represented as. Set `run_compressed` True to execute model as the
+ compressed format if not `dense`
+ quantization_status (`QuantizationStatus`, *optional*, defaults to `"initialized"`):
+ status of model in the quantization lifecycle, ie 'initialized', 'calibration', 'frozen'
+ kv_cache_scheme (`typing.Union[QuantizationArgs, NoneType]`, *optional*):
+ specifies quantization of the kv cache. If None, kv cache is not quantized.
+ global_compression_ratio (`typing.Union[float, NoneType]`, *optional*):
+ 0-1 float percentage of model compression
+ ignore (`typing.Union[typing.list[str], NoneType]`, *optional*):
+ layer names or types to not quantize, supports regex prefixed by 're:'
+ sparsity_config (`typing.dict[str, typing.Any]`, *optional*):
+ configuration for sparsity compression
+ quant_method (`str`, *optional*, defaults to `"compressed-tensors"`):
+ do not override, should be compressed-tensors
+ run_compressed (`bool`, *optional*, defaults to `True`): alter submodules (usually linear) in order to
+ emulate compressed model execution if True, otherwise use default submodule
+ """
+
+ def __init__(
+ self,
+ config_groups: dict[str, Union["QuantizationScheme", list[str]]] | None = None, # noqa: F821
+ format: str = "dense",
+ quantization_status: "QuantizationStatus" = "initialized", # noqa: F821
+ kv_cache_scheme: Optional["QuantizationArgs"] = None, # noqa: F821
+ global_compression_ratio: float | None = None,
+ ignore: list[str] | None = None,
+ sparsity_config: dict[str, Any] | None = None,
+ quant_method: str = "compressed-tensors",
+ run_compressed: bool = True,
+ **kwargs,
+ ):
+ if is_compressed_tensors_available():
+ from compressed_tensors.config import SparsityCompressionConfig
+ from compressed_tensors.quantization import QuantizationConfig
+ else:
+ raise ImportError(
+ "compressed_tensors is not installed and is required for compressed-tensors quantization. Please install it with `pip install compressed-tensors`."
+ )
+ self.quantization_config = None
+ self.sparsity_config = None
+
+ self.run_compressed = run_compressed
+
+ # parse from dict to load nested QuantizationScheme objects
+ if config_groups or kv_cache_scheme:
+ self.quantization_config = QuantizationConfig.model_validate(
+ {
+ "config_groups": config_groups,
+ "quant_method": quant_method,
+ "format": format,
+ "quantization_status": quantization_status,
+ "kv_cache_scheme": kv_cache_scheme,
+ "global_compression_ratio": global_compression_ratio,
+ "ignore": ignore,
+ **kwargs,
+ }
+ )
+
+ if sparsity_config:
+ self.sparsity_config = SparsityCompressionConfig.load_from_registry(
+ sparsity_config.get("format"), **sparsity_config
+ )
+
+ self.quant_method = QuantizationMethod.COMPRESSED_TENSORS
+
+ def post_init(self):
+ if self.run_compressed:
+ if self.is_sparsification_compressed:
+ logger.warning(
+ "`run_compressed` is only supported for quantized_compressed models"
+ " and not for sparsified models. Setting `run_compressed=False`"
+ )
+ self.run_compressed = False
+ elif not self.is_quantization_compressed:
+ logger.warning(
+ "`run_compressed` is only supported for compressed models. Setting `run_compressed=False`"
+ )
+ self.run_compressed = False
+
+ @classmethod
+ def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs):
+ """
+ Instantiates a [`CompressedTensorsConfig`] from a Python dictionary of parameters.
+ Optionally unwraps any args from the nested quantization_config
+
+ Args:
+ config_dict (`dict[str, Any]`):
+ Dictionary that will be used to instantiate the configuration object.
+ return_unused_kwargs (`bool`,*optional*, defaults to `False`):
+ Whether or not to return a list of unused keyword arguments. Used for `from_pretrained` method in
+ `PreTrainedModel`.
+ kwargs (`dict[str, Any]`):
+ Additional parameters from which to initialize the configuration object.
+
+ Returns:
+ [`QuantizationConfigMixin`]: The configuration object instantiated from those parameters.
+
+ """
+
+ if "quantization_config" in config_dict:
+ config_dict = dict(
+ sparsity_config=config_dict.get("sparsity_config"),
+ **config_dict["quantization_config"],
+ )
+
+ return super().from_dict(config_dict, return_unused_kwargs=return_unused_kwargs, **kwargs)
+
+ def to_dict(self) -> dict[str, Any]:
+ """
+ Quantization config to be added to config.json
+
+ Serializes this instance to a Python dictionary. Returns:
+ `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
+ """
+ quantization_config = {}
+ if self.quantization_config is not None:
+ quantization_config = self.quantization_config.model_dump()
+ else:
+ quantization_config["quant_method"] = QuantizationMethod.COMPRESSED_TENSORS
+
+ if self.sparsity_config is not None:
+ quantization_config["sparsity_config"] = self.sparsity_config.model_dump()
+ else:
+ quantization_config["sparsity_config"] = {}
+
+ return quantization_config
+
+ def to_diff_dict(self) -> dict[str, Any]:
+ """
+ Removes all attributes from config which correspond to the default config attributes for better readability and
+ serializes to a Python dictionary.
+ Returns:
+ `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
+ """
+ config_dict = self.to_dict()
+
+ # get the default config dict
+ default_config_dict = CompressedTensorsConfig().to_dict()
+
+ serializable_config_dict = {}
+
+ # only serialize values that differ from the default config
+ for key, value in config_dict.items():
+ if key not in default_config_dict or value != default_config_dict[key]:
+ serializable_config_dict[key] = value
+
+ return serializable_config_dict
+
+ def get_loading_attributes(self):
+ return {"run_compressed": self.run_compressed}
+
+ @property
+ def is_quantized(self):
+ return bool(self.quantization_config) and bool(self.quantization_config.config_groups)
+
+ @property
+ def is_quantization_compressed(self):
+ from compressed_tensors.quantization import QuantizationStatus
+
+ qc = self.quantization_config
+ return self.is_quantized and (qc is not None and qc.quantization_status == QuantizationStatus.COMPRESSED)
+
+ @property
+ def is_sparsification_compressed(self):
+ from compressed_tensors.config import (
+ CompressionFormat,
+ SparsityCompressionConfig,
+ )
+
+ return (
+ isinstance(self.sparsity_config, SparsityCompressionConfig)
+ and self.sparsity_config.format != CompressionFormat.dense.value
+ )
+
+
+@dataclass
+class FbgemmFp8Config(QuantizationConfigMixin):
+ """
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded using fbgemm fp8 quantization.
+
+ Args:
+ activation_scale_ub (`float`, *optional*, defaults to 1200.0):
+ The activation scale upper bound. This is used when quantizing the input activation.
+ modules_to_not_convert (`list`, *optional*, default to `None`):
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have
+ some modules left in their original precision.
+ """
+
+ def __init__(
+ self,
+ activation_scale_ub: float = 1200.0,
+ modules_to_not_convert: list | None = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.FBGEMM_FP8
+ self.activation_scale_ub = activation_scale_ub
+ self.modules_to_not_convert = modules_to_not_convert
+
+ def get_loading_attributes(self):
+ attributes_dict = copy.deepcopy(self.__dict__)
+ loading_attributes = ["activation_scale_ub"]
+ loading_attributes_dict = {i: j for i, j in attributes_dict.items() if i in loading_attributes}
+ return loading_attributes_dict
+
+
+@dataclass
+class HiggsConfig(QuantizationConfigMixin):
+ """
+ HiggsConfig is a configuration class for quantization using the HIGGS method.
+
+ Args:
+ bits (int, *optional*, defaults to 4):
+ Number of bits to use for quantization. Can be 2, 3 or 4. Default is 4.
+ p (int, *optional*, defaults to 2):
+ Quantization grid dimension. 1 and 2 are supported. 2 is always better in practice. Default is 2.
+ modules_to_not_convert (`list`, *optional*, default to ["lm_head"]):
+ List of linear layers that should not be quantized.
+ hadamard_size (int, *optional*, defaults to 512):
+ Hadamard size for the HIGGS method. Default is 512. Input dimension of matrices is padded to this value. Decreasing this below 512 will reduce the quality of the quantization.
+ group_size (int, *optional*, defaults to 256):
+ Group size for the HIGGS method. Can be 64, 128 or 256. Decreasing it barely affects the performance. Default is 256. Must be a divisor of hadamard_size.
+ tune_metadata ('dict', *optional*, defaults to {}):
+ Module-wise metadata (gemm block shapes, GPU metadata, etc.) for saving the kernel tuning results. Default is an empty dictionary. Is set automatically during tuning.
+ """
+
+ def __init__(
+ self,
+ bits: int = 4,
+ p: int = 2,
+ modules_to_not_convert: list[str] | None = None,
+ hadamard_size: int = 512,
+ group_size: int = 256,
+ tune_metadata: dict[str, Any] | None = None,
+ **kwargs,
+ ):
+ if tune_metadata is None:
+ tune_metadata = {}
+ self.quant_method = QuantizationMethod.HIGGS
+ self.bits = bits
+ self.p = p
+ self.modules_to_not_convert = modules_to_not_convert
+ self.hadamard_size = hadamard_size
+ self.group_size = group_size
+ self.tune_metadata = tune_metadata
+
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
+ """
+ if self.bits not in [2, 3, 4]:
+ raise ValueError("bits must be 2, 3, or 4")
+ if self.p not in [1, 2]:
+ raise ValueError("p must be 1 or 2. 2 is always better in practice")
+ if self.group_size not in [64, 128, 256]:
+ raise ValueError("group_size must be 64, 128, or 256")
+ if self.hadamard_size % self.group_size != 0:
+ raise ValueError("hadamard_size must be divisible by group_size")
+
+
+@dataclass
+class FPQuantConfig(QuantizationConfigMixin):
+ """
+ FPQuantConfig is a configuration class for quantization using the FPQuant method.
+
+ Args:
+ forward_dtype (`str`, *optional*, defaults to `"nvfp4"`):
+ The dtype to use for the forward pass.
+ forward_method (`str`, *optional*, defaults to `"abs_max"`):
+ The scaling to use for the forward pass. Can be `"abs_max"` or `"quest"`. `"abs_max"` is better for PTQ, `"quest"` is better for QAT.
+ backward_dtype (`str`, *optional*, defaults to `"bf16"`):
+ The dtype to use for the backward pass.
+ store_master_weights (`bool`, *optional*, defaults to `False`):
+ Whether to store the master weights. Needed for QAT over layer weights.
+ hadamard_group_size (`int`, *optional*):
+ The group size for the hadamard transform before quantization for `"quest"` it matches the MXFP4 group size (32). If `None`, it will be set to 16 for `"nvfp4"` and 32 for `"mxfp4"`.
+ pseudoquantization (`bool`, *optional*, defaults to `False`):
+ Whether to use Triton-based pseudo-quantization. Is mandatory for non-Blackwell GPUs. Doesn't provide any speedup. For debugging purposes.
+ transform_init (`str`, *optional*, defaults to `"hadamard"`): a method to initialize the pre-processing matrix with. Can be `"hadamard"`, `"identity"` or `"gsr"`.
+ modules_to_not_convert (`list`, *optional*):
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have
+ some modules left in their original precision.
+ """
+
+ def __init__(
+ self,
+ forward_dtype: str = "nvfp4",
+ forward_method: str = "abs_max",
+ backward_dtype: str = "bf16",
+ store_master_weights: bool = False,
+ hadamard_group_size: int | None = None,
+ pseudoquantization: bool = False,
+ transform_init: str = "hadamard",
+ modules_to_not_convert: list[str] | None = None,
+ **kwargs,
+ ):
+ self.forward_dtype = forward_dtype
+ self.forward_method = forward_method
+ self.backward_dtype = backward_dtype
+ self.store_master_weights = store_master_weights
+ self.hadamard_group_size = hadamard_group_size
+ self.pseudoquantization = pseudoquantization
+ self.transform_init = transform_init
+ self.modules_to_not_convert = modules_to_not_convert
+
+ self.quant_method = QuantizationMethod.FPQUANT
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
+ """
+
+ if self.hadamard_group_size is None:
+ if self.forward_dtype == "nvfp4":
+ self.hadamard_group_size = 16
+ else:
+ self.hadamard_group_size = 32
+
+ if self.forward_dtype == "mxfp4":
+ if self.forward_method not in ["abs_max", "quest"]:
+ raise ValueError("Only 'abs_max' and 'quest' are supported for forward_method for 'mxfp4'.")
+ if self.hadamard_group_size is None:
+ self.hadamard_group_size = 32
+ if self.hadamard_group_size not in [32, 64, 128]:
+ raise ValueError("Only a `hadamard_group_size` of [32, 64, 128] is supported for 'mxfp4'.")
+ elif self.forward_dtype == "nvfp4":
+ if self.forward_method != "abs_max":
+ raise ValueError("Only 'abs_max' is supported for forward_method for 'nvfp4'.")
+ if self.hadamard_group_size is None:
+ self.hadamard_group_size = 16
+ if self.hadamard_group_size not in [16, 32, 64, 128]:
+ raise ValueError("Only a `hadamard_group_size` of [16, 32, 64, 128] is supported for 'nvfp4'.")
+ else:
+ raise ValueError("Only 'mxfp4' and 'nvfp4' are supported for forward_dtype for now.")
+
+ if self.backward_dtype not in ["bf16", "mxfp8", "mxfp4"]:
+ raise ValueError("Only 'bf16', 'mxfp8' and 'mxfp4' are supported for backward_dtype for now.")
+
+ if self.backward_dtype != "bf16" and self.forward_dtype != "mxfp4":
+ raise ValueError("Only 'mxfp4' forward is compatible with non-bf16 backwards for now.")
+
+ if self.transform_init not in ["hadamard", "identity", "gsr"]:
+ raise ValueError("Only 'hadamard', 'identity' and 'gsr' are supported for transform_init.")
+
+ if self.modules_to_not_convert is None:
+ self.modules_to_not_convert = ["lm_head"]
+
+
+@dataclass
+class TorchAoConfig(QuantizationConfigMixin):
+ quant_method: QuantizationMethod
+ quant_type: Union[str, "AOBaseConfig"] # noqa: F821
+ modules_to_not_convert: list | None
+ quant_type_kwargs: dict[str, Any]
+ include_input_output_embeddings: bool
+ untie_embedding_weights: bool
+
+ """This is a config class for torchao quantization/sparsity techniques.
+
+ Args:
+ quant_type (`Union[str, AOBaseConfig]`):
+ The type of quantization we want to use. Can be either:
+ - A string: currently supporting: `int4_weight_only`, `int8_weight_only` and `int8_dynamic_activation_int8_weight`.
+ - An AOBaseConfig instance: for more advanced configuration options.
+ modules_to_not_convert (`list`, *optional*, default to `None`):
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have
+ some modules left in their original precision.
+ include_input_output_embeddings (`bool`, default to `False`):
+ Whether to include embedding in quantization or not, input embedding will be removed from
+ the module_not_to_convert list as well if this flag is set.
+ untie_embedding_weights (`bool`, default to `False`):
+ Whether to untie the weights when we are quantizing input embedding weights that is tied
+ to other weights.
+ kwargs (`dict[str, Any]`, *optional*):
+ The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments
+ `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in
+ https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques
+
+ Example:
+
+ ```python
+ # AOBaseConfig-based configuration
+ config = Int4WeightOnlyConfig(group_size=32)
+ quantization_config = TorchAoConfig(config)
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cuda", dtype=torch.bfloat16, quantization_config=quantization_config)
+
+ # String-based configuration
+ quantization_config = TorchAoConfig("int4_weight_only", group_size=32)
+ # int4_weight_only quant is only working with *torch.bfloat16* dtype right now
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cuda", dtype=torch.bfloat16, quantization_config=quantization_config)
+
+ ```
+ """
+
+ def __init__(
+ self,
+ quant_type: Union[str, "AOBaseConfig"], # noqa: F821
+ modules_to_not_convert: list | None = None,
+ include_input_output_embeddings: bool = False,
+ untie_embedding_weights: bool = False,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.TORCHAO
+ self.quant_type = quant_type
+ self.modules_to_not_convert = modules_to_not_convert
+ self.quant_type_kwargs = kwargs.get("quant_type_kwargs", kwargs)
+ self.include_input_output_embeddings = include_input_output_embeddings
+ self.untie_embedding_weights = untie_embedding_weights
+ self.post_init()
+
+ @staticmethod
+ def _get_ao_version() -> version.Version:
+ """Centralized check for TorchAO availability and version requirements."""
+ if not is_torchao_available():
+ raise ValueError("TorchAoConfig requires torchao to be installed. Install with `pip install torchao`")
+
+ return version.parse(importlib.metadata.version("torchao"))
+
+ def post_init(self):
+ """Validate configuration and set defaults."""
+ ao_version = self._get_ao_version()
+
+ # Handle quant_type based on type and version
+ if isinstance(self.quant_type, str):
+ self._validate_string_quant_type()
+ elif ao_version > version.parse("0.9.0"):
+ from torchao.quantization.quant_api import AOBaseConfig
+
+ if not isinstance(self.quant_type, AOBaseConfig):
+ raise TypeError(
+ f"quant_type must be either a string or an AOBaseConfig instance, got {type(self.quant_type)}"
+ )
+ else:
+ raise ValueError(
+ f"In torchao <= 0.9.0, quant_type must be a string. Got {type(self.quant_type)}. "
+ f"Please upgrade to torchao > 0.9.0 to use AOBaseConfig instances."
+ )
+
+ def _validate_string_quant_type(self):
+ """Validate string quant_type and its kwargs."""
+ methods = self._get_torchao_quant_type_to_method()
+
+ if self.quant_type not in methods:
+ raise ValueError(
+ f"Unsupported string quantization type: {self.quant_type}. "
+ f"Supported types: {', '.join(methods.keys())}"
+ )
+
+ # Validate kwargs against method signature
+ method = methods[self.quant_type]
+ sig = signature(method)
+ valid_kwargs = {
+ param.name
+ for param in sig.parameters.values()
+ if param.kind in [Parameter.KEYWORD_ONLY, Parameter.POSITIONAL_OR_KEYWORD]
+ }
+
+ invalid_kwargs = set(self.quant_type_kwargs) - valid_kwargs
+ if invalid_kwargs:
+ raise ValueError(
+ f"Unexpected keyword arg for {self.quant_type}: {', '.join(invalid_kwargs)}. "
+ f"Valid kwargs: {', '.join(valid_kwargs)}"
+ )
+
+ def _get_torchao_quant_type_to_method(self):
+ """Get mapping of quant_type strings to their corresponding methods."""
+ from torchao.quantization import (
+ int4_weight_only,
+ int8_dynamic_activation_int8_weight,
+ int8_weight_only,
+ )
+
+ return {
+ "int4_weight_only": int4_weight_only,
+ "int8_weight_only": int8_weight_only,
+ "int8_dynamic_activation_int8_weight": int8_dynamic_activation_int8_weight,
+ }
+
+ def get_apply_tensor_subclass(self):
+ """Create the appropriate quantization method based on configuration."""
+ if isinstance(self.quant_type, str):
+ methods = self._get_torchao_quant_type_to_method()
+ quant_type_kwargs = self.quant_type_kwargs.copy()
+ if (
+ not torch.cuda.is_available()
+ and is_torchao_available()
+ and self.quant_type == "int4_weight_only"
+ and version.parse(importlib.metadata.version("torchao")) >= version.parse("0.8.0")
+ and quant_type_kwargs.get("layout", None) is None
+ ):
+ if torch.xpu.is_available():
+ if version.parse(importlib.metadata.version("torchao")) >= version.parse(
+ "0.11.0"
+ ) and version.parse(importlib.metadata.version("torch")) > version.parse("2.7.9"):
+ from torchao.dtypes import Int4XPULayout
+ from torchao.quantization.quant_primitives import ZeroPointDomain
+
+ quant_type_kwargs["layout"] = Int4XPULayout()
+ quant_type_kwargs["zero_point_domain"] = ZeroPointDomain.INT
+ else:
+ raise ValueError(
+ "TorchAoConfig requires torchao >= 0.11.0 and torch >= 2.8.0 for XPU support. Please upgrade the version or use run on CPU with the cpu version pytorch."
+ )
+ else:
+ from torchao.dtypes import Int4CPULayout
+
+ quant_type_kwargs["layout"] = Int4CPULayout()
+
+ return methods[self.quant_type](**quant_type_kwargs)
+ else:
+ return self.quant_type
+
+ def to_dict(self):
+ """Convert configuration to a dictionary."""
+ d = super().to_dict()
+
+ if isinstance(self.quant_type, str):
+ # Handle layout serialization if present
+ if "quant_type_kwargs" in d and "layout" in d["quant_type_kwargs"]:
+ if is_dataclass(d["quant_type_kwargs"]["layout"]):
+ d["quant_type_kwargs"]["layout"] = [
+ d["quant_type_kwargs"]["layout"].__class__.__name__,
+ dataclasses.asdict(d["quant_type_kwargs"]["layout"]),
+ ]
+ if isinstance(d["quant_type_kwargs"]["layout"], list):
+ assert len(d["quant_type_kwargs"]["layout"]) == 2, "layout saves layout name and layout kwargs"
+ assert isinstance(d["quant_type_kwargs"]["layout"][0], str), "layout name must be a string"
+ assert isinstance(d["quant_type_kwargs"]["layout"][1], dict), "layout kwargs must be a dict"
+ else:
+ raise ValueError("layout must be a list")
+ else:
+ # Handle AOBaseConfig serialization
+ from torchao.core.config import config_to_dict
+
+ # For now we assume there is 1 config per Transformer, however in the future
+ # We may want to support a config per fqn.
+ d["quant_type"] = {"default": config_to_dict(self.quant_type)}
+
+ return d
+
+ @classmethod
+ def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs):
+ """Create configuration from a dictionary."""
+ ao_version = cls._get_ao_version()
+ assert ao_version > version.parse("0.9.0"), "TorchAoConfig requires torchao > 0.9.0 for construction from dict"
+ config_dict = config_dict.copy()
+ quant_type = config_dict.pop("quant_type")
+
+ if isinstance(quant_type, str):
+ return cls(quant_type=quant_type, **config_dict)
+ # Check if we only have one key which is "default"
+ # In the future we may update this
+ assert len(quant_type) == 1 and "default" in quant_type, (
+ "Expected only one key 'default' in quant_type dictionary"
+ )
+ quant_type = quant_type["default"]
+
+ # Deserialize quant_type if needed
+ from torchao.core.config import config_from_dict
+
+ quant_type = config_from_dict(quant_type)
+
+ return cls(quant_type=quant_type, **config_dict)
+
+
+@dataclass
+class BitNetQuantConfig(QuantizationConfigMixin):
+ """
+ Configuration class for applying BitNet quantization.
+
+ Args:
+ modules_to_not_convert (`Optional[List]`, *optional*):
+ Optionally, provides a list of full paths of `nn.Linear` weight parameters
+ that shall not be quantized. Defaults to None.
+ linear_class (`str`, *optional*, defaults to `"bitlinear"`):
+ The type of linear class to use. Can be either `bitlinear` or `autobitlinear`.
+ quantization_mode (`str`, *optional*, defaults to `"offline"`):
+ The quantization mode to use. Can be either `online` or `offline`.
+ In `online` mode, the weight quantization parameters are calculated dynamically
+ during each forward pass (e.g., based on the current weight values). This can
+ adapt to weight changes during training (Quantization-Aware Training - QAT).
+ In `offline` mode, quantization parameters are pre-calculated *before* inference.
+ These parameters are then fixed and loaded into the quantized model. This
+ generally results in lower runtime overhead compared to online quantization.
+ use_rms_norm (`bool`, *optional*, defaults to `False`):
+ Whether to apply RMSNorm on the activations before quantization. This matches the original BitNet paper's approach
+ of normalizing activations before quantization/packing.
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
+ The epsilon value used in the RMSNorm layer for numerical stability.
+ kwargs (`dict[str, Any]`, *optional*):
+ Additional keyword arguments that may be used by specific quantization
+ backends or future versions.
+ """
+
+ def __init__(
+ self,
+ modules_to_not_convert: list | None = None,
+ linear_class: str = "bitlinear",
+ quantization_mode: str = "offline",
+ use_rms_norm: bool = False,
+ rms_norm_eps: float | None = 1e-6,
+ **kwargs,
+ ):
+ if linear_class not in ["bitlinear", "autobitlinear"]:
+ raise ValueError(f"linear_class must be either 'bitlinear' or 'autobitlinear', but got {linear_class}")
+ if quantization_mode not in ["online", "offline"]:
+ raise ValueError(f"quantization_mode must be either 'online' or 'offline', but got {quantization_mode}")
+ self.quant_method = QuantizationMethod.BITNET
+ self.modules_to_not_convert = modules_to_not_convert
+ self.linear_class = linear_class
+ self.quantization_mode = quantization_mode
+ self.use_rms_norm = use_rms_norm
+ self.rms_norm_eps = rms_norm_eps
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+
+
+@dataclass
+class SpQRConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about `spqr` parameters. Refer to the original publication for more details.
+
+ Args:
+ bits (`int`, *optional*, defaults to 3):
+ Specifies the bit count for the weights and first order zero-points and scales.
+ Currently only bits = 3 is supported.
+ beta1 (`int`, *optional*, defaults to 16):
+ SpQR tile width. Currently only beta1 = 16 is supported.
+ beta2 (`int`, *optional*, defaults to 16):
+ SpQR tile height. Currently only beta2 = 16 is supported.
+ shapes (`Optional`, *optional*):
+ A dictionary holding the shape of each object. We need this because it's impossible
+ to deduce the exact size of the parameters just from bits, beta1, beta2.
+ modules_to_not_convert (`Optional[list[str]]`, *optional*):
+ Optionally, provides a list of full paths of `nn.Linear` weight parameters that shall not be quantized.
+ Defaults to None.
+ kwargs (`dict[str, Any]`, *optional*):
+ Additional parameters from which to initialize the configuration object.
+ """
+
+ def __init__(
+ self,
+ bits: int = 3,
+ beta1: int = 16,
+ beta2: int = 16,
+ shapes: dict[str, int] | None = None,
+ modules_to_not_convert: list[str] | None = None,
+ **kwargs,
+ ):
+ if shapes is None:
+ shapes = {}
+ self.shapes = shapes
+ self.quant_method = QuantizationMethod.SPQR
+ self.bits = bits
+ self.beta1 = beta1
+ self.beta2 = beta2
+ self.modules_to_not_convert = modules_to_not_convert
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
+ """
+ if not isinstance(self.bits, int):
+ raise TypeError("bits must be an int")
+ if not isinstance(self.beta1, int):
+ raise TypeError("beta1 must be an int")
+ if not isinstance(self.beta2, int):
+ raise TypeError("beta2 must be an int")
+
+ if self.bits != 3:
+ raise ValueError("SpQR currently only supports bits = 3")
+ if self.beta1 != 16:
+ raise ValueError("SpQR currently only supports beta1 = 16")
+ if self.beta2 != 16:
+ raise ValueError("SpQR currently only supports beta2 = 16")
+ if not isinstance(self.shapes, dict):
+ raise TypeError("shapes must be a dict")
+
+
+@dataclass
+class FineGrainedFP8Config(QuantizationConfigMixin):
+ """
+ FineGrainedFP8Config is a configuration class for fine-grained FP8 quantization used mainly for deepseek models.
+
+ Args:
+ activation_scheme (`str`, *optional*, defaults to `"dynamic"`):
+ The scheme used for activation, the defaults and only support scheme for now is "dynamic".
+ weight_block_size (`typing.tuple[int, int]`, *optional*, defaults to `(128, 128)`):
+ The size of the weight blocks for quantization, default is (128, 128).
+ dequantize (`bool`, *optional*, defaults to `False`):
+ Whether to dequantize the model during loading.
+ modules_to_not_convert (`list`, *optional*):
+ A list of module names that should not be converted during quantization.
+ """
+
+ def __init__(
+ self,
+ activation_scheme: str = "dynamic",
+ weight_block_size: tuple[int, int] = (128, 128),
+ dequantize: bool = False,
+ modules_to_not_convert: list | None = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.FP8
+ self.modules_to_not_convert = modules_to_not_convert
+ self.activation_scheme = activation_scheme
+ self.weight_block_size = weight_block_size
+ self.dequantize = dequantize
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ self.activation_scheme = self.activation_scheme.lower()
+ if self.activation_scheme not in ["dynamic", "static"]:
+ raise ValueError(f"Activation scheme {self.activation_scheme} not supported")
+ if self.weight_block_size is not None and len(self.weight_block_size) != 2:
+ raise ValueError("weight_block_size must be a tuple of two integers")
+ if self.weight_block_size is not None and (self.weight_block_size[0] <= 0 or self.weight_block_size[1] <= 0):
+ raise ValueError("weight_block_size must be a tuple of two positive integers")
+
+ def get_loading_attributes(self):
+ return {"dequantize": self.dequantize}
+
+
+class QuarkConfig(QuantizationConfigMixin):
+ def __init__(
+ self,
+ **kwargs,
+ ):
+ if is_torch_available() and is_quark_available():
+ from quark import __version__ as quark_version
+ from quark.torch.export.config.config import JsonExporterConfig
+ from quark.torch.export.main_export.quant_config_parser import QuantConfigParser
+ from quark.torch.quantization.config.config import Config
+ else:
+ raise ImportError(
+ "Quark is not installed. Please refer to https://quark.docs.amd.com/latest/install.html."
+ )
+ # This might be e.g. `"fp8"` or `"awq"`.
+ self.custom_mode = kwargs["quant_method"]
+ self.legacy = "export" not in kwargs
+
+ if self.custom_mode in ["awq", "fp8"]:
+ # Legacy (quark<1.0) or custom export.
+ self.quant_config = QuantConfigParser.from_custom_config(kwargs, is_bias_quantized=False)
+ self.json_export_config = JsonExporterConfig()
+ else:
+ self.quant_config = Config.from_dict(kwargs)
+
+ if "export" in kwargs:
+ # TODO: Remove this check once configuration version is handled natively by Quark.
+ if "min_kv_scale" in kwargs["export"] and version.parse(quark_version) < version.parse("0.8"):
+ min_kv_scale = kwargs["export"].pop("min_kv_scale")
+ logger.warning(
+ f"The parameter `min_kv_scale={min_kv_scale}` was found in the model config.json's `quantization_config.export` configuration, but this parameter is supported only for quark>=0.8. Ignoring this configuration parameter. Please update the `amd-quark` package."
+ )
+
+ self.json_export_config = JsonExporterConfig(**kwargs["export"])
+ else:
+ # Legacy (quark<1.0) or custom export.
+ self.json_export_config = JsonExporterConfig()
+
+ self.quant_method = QuantizationMethod.QUARK
+
+
+@dataclass
+class Mxfp4Config(QuantizationConfigMixin):
+ """
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded using mxfp4 quantization.
+
+ Args:
+ modules_to_not_convert (`list`, *optional*, default to `None`):
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have
+ some modules left in their original precision.
+ dequantize (`bool`, *optional*, default to `False`):
+ Whether we dequantize the model to bf16 precision or not
+ """
+
+ def __init__(
+ self,
+ modules_to_not_convert: list | None = None,
+ dequantize: bool = False,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.MXFP4
+ self.modules_to_not_convert = modules_to_not_convert
+ self.dequantize = dequantize
+
+ def get_loading_attributes(self):
+ return {"dequantize": self.dequantize}
+
+ def to_dict(self) -> dict[str, Any]:
+ """
+ Serializes this instance to a Python dictionary. Returns:
+ `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
+ """
+ return {"quant_method": self.quant_method, "modules_to_not_convert": self.modules_to_not_convert}
+
+
+class MetalConfig(QuantizationConfigMixin):
+ """
+ Configuration class for Metal affine quantization targeting Apple Silicon (MPS) devices.
+
+ This quantization method uses the ``mlx-quantization-metal-kernels`` Metal kernels from the Hugging Face Hub
+ to perform affine quantization (scales + qbiases) with configurable bit-width and group size.
+ The quantized weights are packed into ``uint32`` tensors and the forward pass uses fused
+ dequantization + matmul Metal kernels.
+ """
+
+ def __init__(
+ self,
+ bits: int = 4,
+ group_size: int = 64,
+ modules_to_not_convert: list | None = None,
+ dequantize: bool = False,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.METAL
+ self.bits = bits
+ self.group_size = group_size
+ self.modules_to_not_convert = modules_to_not_convert
+ self.dequantize = dequantize
+ self.post_init()
+
+ def post_init(self):
+ if self.bits not in (2, 4, 8):
+ raise ValueError(f"Metal quantization only supports bits in {{2, 4, 8}}, got {self.bits}")
+ if self.group_size <= 0:
+ raise ValueError(f"group_size must be positive, got {self.group_size}")
+
+ def get_loading_attributes(self):
+ return {"dequantize": self.dequantize}
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "quant_method": self.quant_method,
+ "bits": self.bits,
+ "group_size": self.group_size,
+ "modules_to_not_convert": self.modules_to_not_convert,
+ }
+
+
+@dataclass
+class FourOverSixConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class containing all options for quantization with `fouroversix`. In brief,
+ Four Over Six is a modification to NVFP4 quantization which adaptively scales the largest value
+ in each block of 16 FP4 values to either 4 or 6. Selecting a scale of 6 uses the full range of
+ FP4 values, but selecting a scale of 4 allows for a more uniform distribution of quantization
+ error. Refer to the original publication for more details: https://arxiv.org/abs/2512.02010.
+
+ Args:
+ activation_scale_rule (`str`, *optional*):
+ Scaling rule to use when selecting a scale for blocks in activation tensors. If not
+ provided, `scale_rule` is used.
+ dtype (`str`, default "nvfp4", *optional*, defaults to `"nvfp4"`):
+ The data type to use for the layer's weights, activations, and tensors. Can be
+ `"nvfp4"` or `"mxfp4"`.
+ gradient_scale_rule (`str`, *optional*):
+ Scaling rule to use when selecting a scale for blocks in gradient tensors. If not
+ provided, `scale_rule` is used.
+ keep_master_weights (`bool`, default False, *optional*, defaults to `False`):
+ Whether to keep the master weights. If `True`, high-precision weights are kept at all
+ times and weights are quantized online in each forward pass. This is useful for
+ quantized training.
+ matmul_backend (`str`, *optional*):
+ The backend to use for matrix multiplications. Can be `"cutlass"` or `"pytorch"`. If
+ not provided, CUTLASS will be used if available and PyTorch will be used otherwise.
+ output_dtype (`str`, *optional*, defaults to `"bfloat16"`):
+ The data type to use for the output of the layer. Can be `"bfloat16"` or `"float16"`.
+ quantize_backend (`str`, *optional*):
+ The backend to use for quantization. Can be `"cuda"`, `"triton"`, or `"pytorch"`. If
+ not provided, the fastest backend will be selected based on your environment, and based
+ on the options supported by each backend. Typically, `"cuda"` will be used for
+ inference, `"triton"` will be used for training, and `"pytorch"` will be used on
+ non-CUDA devices.
+ scale_rule (`str`, default "mse", *optional*, defaults to `"mse"`):
+ Rule to use when selecting block scales. Can be `"mse"`, `"mae"`, or `"abs_max"` for
+ Four Over Six, `"static_6"` for default NVFP4 quantization, or `"static_4"` to scale
+ all blocks to a maximum value of 4.
+ weight_scale_2d (`bool`, default False, *optional*, defaults to `False`):
+ Whether to compute scale factors on weight tensors in 2D blocks. This should be done
+ during training.
+ weight_scale_rule (`str`, *optional*):
+ Scaling rule to use when selecting a scale for blocks in weight tensors. If not
+ provided, `scale_rule` is used.
+ module_config_overrides (`dict[str, dict[str, Any]]`, *optional*):
+ A dictionary of module-specific configuration overrides. Keys should be module names, and
+ values should be dictionaries containing the quantization configuration for that module.
+ This can be used to override the default configuration for specific modules.
+ modules_to_not_convert (`list[str]`, *optional*, defaults to `['lm_head']`):
+ The list of modules to exclude from quantization. By default, the `lm_head` is excluded.
+ """
+
+ def __init__(
+ self,
+ activation_scale_rule: str | None = None,
+ dtype: str = "nvfp4",
+ gradient_scale_rule: str | None = None,
+ keep_master_weights: bool = False,
+ matmul_backend: str | None = None,
+ output_dtype: str | None = "bfloat16",
+ quantize_backend: str | None = None,
+ scale_rule: str = "mse",
+ weight_scale_2d: bool = False,
+ weight_scale_rule: str | None = None,
+ module_config_overrides: dict[str, dict[str, Any]] | None = None,
+ modules_to_not_convert: list[str] | None = ["lm_head"],
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.FOUR_OVER_SIX
+
+ self.activation_scale_rule = activation_scale_rule
+ self.dtype = dtype
+ self.gradient_scale_rule = gradient_scale_rule
+ self.keep_master_weights = keep_master_weights
+ self.matmul_backend = matmul_backend
+ self.quantize_backend = quantize_backend
+ self.output_dtype = output_dtype
+ self.scale_rule = scale_rule
+ self.weight_scale_2d = weight_scale_2d
+ self.weight_scale_rule = weight_scale_rule
+ self.module_config_overrides = module_config_overrides
+ self.modules_to_not_convert = modules_to_not_convert
+
+
+class SinqConfig(QuantizationConfigMixin):
+ """
+ Quantization config for SINQ / A-SINQ.
+
+ Pass this to:
+
+ AutoModel.from_pretrained(..., quantization_config=SinqConfig(...))
+
+ Args:
+ nbits (`int`, default 4):
+ Quantization bits for weights.
+ group_size (`int`, default 64):
+ Group size used in SINQ weight quantization (must be multiple of 8).
+ tiling_mode (`str`, default "1D"):
+ Tiling mode for SINQ (typically "1D"; "2D" if supported in your backend).
+ method (`str`, default "sinq"):
+ "sinq" – calibration-free weight-only SINQ
+ "asinq" – A-SINQ (activation-aware), not supported in Hugging Face. Please refer to the official SINQ repository.
+ modules_to_not_convert (`list[str]`, *optional*):
+ List of module names/prefixes to keep in full precision.
+
+ **kwargs:
+ Extra user arguments (kept in `_extra_kwargs` for round-tripping).
+ """
+
+ def __init__(
+ self,
+ nbits: int = 4,
+ group_size: int = 64,
+ tiling_mode: str = "1D",
+ method: str = "sinq", # "sinq" | "asinq"
+ modules_to_not_convert: list[str] | None = None,
+ **kwargs: Any,
+ ):
+ self.quant_method = QuantizationMethod.SINQ
+
+ self.nbits = nbits
+ self.group_size = group_size
+ self.tiling_mode = tiling_mode
+ self.method = method
+
+ self.modules_to_not_convert = modules_to_not_convert
+
+ self._extra_kwargs: dict[str, Any] = dict(kwargs)
+
+ self.post_init()
+
+ def post_init(self):
+ self.nbits = int(self.nbits)
+ self.group_size = int(self.group_size)
+ self.tiling_mode = str(self.tiling_mode)
+ self.method = str(self.method).lower()
+
+ # Validation
+ if not isinstance(self.nbits, int):
+ raise TypeError("`nbits` must be convertible to an int")
+ if not isinstance(self.group_size, int):
+ raise TypeError("`group_size` must be convertible to an int")
+ if not isinstance(self.tiling_mode, str):
+ raise TypeError("`tiling_mode` must be convertible to a string")
+ if self.method not in {"sinq", "asinq"}:
+ raise ValueError(f"`method` must be either 'sinq' or 'asinq', got {self.method}")
+ if self.group_size is not None and self.group_size % 8 != 0:
+ logger.warning(
+ f"SINQ: group_size={self.group_size} is not a multiple of 8; this may be rejected by the backend."
+ )
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/sentencepiece_model_pb2.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/sentencepiece_model_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f063575fd7af2ae65d3d55b054b856ca8b77fe8
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/sentencepiece_model_pb2.py
@@ -0,0 +1,1511 @@
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: sentencepiece_model.proto
+
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import message as _message
+from google.protobuf import reflection as _reflection
+from google.protobuf import symbol_database as _symbol_database
+
+
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+DESCRIPTOR = _descriptor.FileDescriptor(
+ name="sentencepiece_model.proto",
+ package="sentencepiece",
+ syntax="proto2",
+ serialized_options=b"H\003",
+ create_key=_descriptor._internal_create_key,
+ serialized_pb=(
+ b'\n\x19sentencepiece_model.proto\x12\rsentencepiece"\xa1\n\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01'
+ b" \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02"
+ b" \x01(\t\x12\x41\n\nmodel_type\x18\x03"
+ b" \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04"
+ b" \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12"
+ b' \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12"\n\x12\x63haracter_coverage\x18\n'
+ b" \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b"
+ b" \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12"
+ b' \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12"\n\x16training_sentence_size\x18\r'
+ b" \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e"
+ b" \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f"
+ b" \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12"
+ b" \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10"
+ b" \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11"
+ b" \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14"
+ b" \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15"
+ b" \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17"
+ b" \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16"
+ b" \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18"
+ b" \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19"
+ b" \x01(\x08:\x05\x66\x61lse\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e"
+ b" \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$"
+ b" \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18"
+ b' \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18"'
+ b" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18)"
+ b" \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+"
+ b" \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05\x12\x16\n\tbos_piece\x18."
+ b" \x01(\t:\x03\x12\x17\n\teos_piece\x18/ \x01(\t:\x04\x12\x18\n\tpad_piece\x18\x30"
+ b" \x01(\t:\x05\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87"
+ b" \x12+\n\x1ctrain_extremely_large_corpus\x18\x31"
+ b' \x01(\x08:\x05\x66\x61lse"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01'
+ b" \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03"
+ b" \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12"
+ b" \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06"
+ b' \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01'
+ b' \x03(\x0b\x32".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01'
+ b" \x01(\t\x12\x10\n\x08\x65xpected\x18\x02"
+ b' \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01'
+ b" \x03(\x0b\x32'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02"
+ b" \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03"
+ b" \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04"
+ b" \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05"
+ b" \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01"
+ b" \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03"
+ b' \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03'
+ ),
+)
+
+
+_TRAINERSPEC_MODELTYPE = _descriptor.EnumDescriptor(
+ name="ModelType",
+ full_name="sentencepiece.TrainerSpec.ModelType",
+ filename=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ values=[
+ _descriptor.EnumValueDescriptor(
+ name="UNIGRAM",
+ index=0,
+ number=1,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.EnumValueDescriptor(
+ name="BPE",
+ index=1,
+ number=2,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.EnumValueDescriptor(
+ name="WORD",
+ index=2,
+ number=3,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.EnumValueDescriptor(
+ name="CHAR",
+ index=3,
+ number=4,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ ],
+ containing_type=None,
+ serialized_options=None,
+ serialized_start=1294,
+ serialized_end=1347,
+)
+_sym_db.RegisterEnumDescriptor(_TRAINERSPEC_MODELTYPE)
+
+_MODELPROTO_SENTENCEPIECE_TYPE = _descriptor.EnumDescriptor(
+ name="Type",
+ full_name="sentencepiece.ModelProto.SentencePiece.Type",
+ filename=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ values=[
+ _descriptor.EnumValueDescriptor(
+ name="NORMAL",
+ index=0,
+ number=1,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.EnumValueDescriptor(
+ name="UNKNOWN",
+ index=1,
+ number=2,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.EnumValueDescriptor(
+ name="CONTROL",
+ index=2,
+ number=3,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.EnumValueDescriptor(
+ name="USER_DEFINED",
+ index=3,
+ number=4,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.EnumValueDescriptor(
+ name="BYTE",
+ index=4,
+ number=6,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.EnumValueDescriptor(
+ name="UNUSED",
+ index=5,
+ number=5,
+ serialized_options=None,
+ type=None,
+ create_key=_descriptor._internal_create_key,
+ ),
+ ],
+ containing_type=None,
+ serialized_options=None,
+ serialized_start=2100,
+ serialized_end=2184,
+)
+_sym_db.RegisterEnumDescriptor(_MODELPROTO_SENTENCEPIECE_TYPE)
+
+
+_TRAINERSPEC = _descriptor.Descriptor(
+ name="TrainerSpec",
+ full_name="sentencepiece.TrainerSpec",
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ create_key=_descriptor._internal_create_key,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name="input",
+ full_name="sentencepiece.TrainerSpec.input",
+ index=0,
+ number=1,
+ type=9,
+ cpp_type=9,
+ label=3,
+ has_default_value=False,
+ default_value=[],
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="input_format",
+ full_name="sentencepiece.TrainerSpec.input_format",
+ index=1,
+ number=7,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="model_prefix",
+ full_name="sentencepiece.TrainerSpec.model_prefix",
+ index=2,
+ number=2,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="model_type",
+ full_name="sentencepiece.TrainerSpec.model_type",
+ index=3,
+ number=3,
+ type=14,
+ cpp_type=8,
+ label=1,
+ has_default_value=True,
+ default_value=1,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="vocab_size",
+ full_name="sentencepiece.TrainerSpec.vocab_size",
+ index=4,
+ number=4,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=8000,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="accept_language",
+ full_name="sentencepiece.TrainerSpec.accept_language",
+ index=5,
+ number=5,
+ type=9,
+ cpp_type=9,
+ label=3,
+ has_default_value=False,
+ default_value=[],
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="self_test_sample_size",
+ full_name="sentencepiece.TrainerSpec.self_test_sample_size",
+ index=6,
+ number=6,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=0,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="character_coverage",
+ full_name="sentencepiece.TrainerSpec.character_coverage",
+ index=7,
+ number=10,
+ type=2,
+ cpp_type=6,
+ label=1,
+ has_default_value=True,
+ default_value=0.9995,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="input_sentence_size",
+ full_name="sentencepiece.TrainerSpec.input_sentence_size",
+ index=8,
+ number=11,
+ type=4,
+ cpp_type=4,
+ label=1,
+ has_default_value=True,
+ default_value=0,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="shuffle_input_sentence",
+ full_name="sentencepiece.TrainerSpec.shuffle_input_sentence",
+ index=9,
+ number=19,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="mining_sentence_size",
+ full_name="sentencepiece.TrainerSpec.mining_sentence_size",
+ index=10,
+ number=12,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=False,
+ default_value=0,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=b"\030\001",
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="training_sentence_size",
+ full_name="sentencepiece.TrainerSpec.training_sentence_size",
+ index=11,
+ number=13,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=False,
+ default_value=0,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=b"\030\001",
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="seed_sentencepiece_size",
+ full_name="sentencepiece.TrainerSpec.seed_sentencepiece_size",
+ index=12,
+ number=14,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=1000000,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="shrinking_factor",
+ full_name="sentencepiece.TrainerSpec.shrinking_factor",
+ index=13,
+ number=15,
+ type=2,
+ cpp_type=6,
+ label=1,
+ has_default_value=True,
+ default_value=0.75,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="max_sentence_length",
+ full_name="sentencepiece.TrainerSpec.max_sentence_length",
+ index=14,
+ number=18,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=4192,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="num_threads",
+ full_name="sentencepiece.TrainerSpec.num_threads",
+ index=15,
+ number=16,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=16,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="num_sub_iterations",
+ full_name="sentencepiece.TrainerSpec.num_sub_iterations",
+ index=16,
+ number=17,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=2,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="max_sentencepiece_length",
+ full_name="sentencepiece.TrainerSpec.max_sentencepiece_length",
+ index=17,
+ number=20,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=16,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="split_by_unicode_script",
+ full_name="sentencepiece.TrainerSpec.split_by_unicode_script",
+ index=18,
+ number=21,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="split_by_number",
+ full_name="sentencepiece.TrainerSpec.split_by_number",
+ index=19,
+ number=23,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="split_by_whitespace",
+ full_name="sentencepiece.TrainerSpec.split_by_whitespace",
+ index=20,
+ number=22,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="treat_whitespace_as_suffix",
+ full_name="sentencepiece.TrainerSpec.treat_whitespace_as_suffix",
+ index=21,
+ number=24,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=False,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="split_digits",
+ full_name="sentencepiece.TrainerSpec.split_digits",
+ index=22,
+ number=25,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=False,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="control_symbols",
+ full_name="sentencepiece.TrainerSpec.control_symbols",
+ index=23,
+ number=30,
+ type=9,
+ cpp_type=9,
+ label=3,
+ has_default_value=False,
+ default_value=[],
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="user_defined_symbols",
+ full_name="sentencepiece.TrainerSpec.user_defined_symbols",
+ index=24,
+ number=31,
+ type=9,
+ cpp_type=9,
+ label=3,
+ has_default_value=False,
+ default_value=[],
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="required_chars",
+ full_name="sentencepiece.TrainerSpec.required_chars",
+ index=25,
+ number=36,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="byte_fallback",
+ full_name="sentencepiece.TrainerSpec.byte_fallback",
+ index=26,
+ number=35,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=False,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="vocabulary_output_piece_score",
+ full_name="sentencepiece.TrainerSpec.vocabulary_output_piece_score",
+ index=27,
+ number=32,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="hard_vocab_limit",
+ full_name="sentencepiece.TrainerSpec.hard_vocab_limit",
+ index=28,
+ number=33,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="use_all_vocab",
+ full_name="sentencepiece.TrainerSpec.use_all_vocab",
+ index=29,
+ number=34,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=False,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="unk_id",
+ full_name="sentencepiece.TrainerSpec.unk_id",
+ index=30,
+ number=40,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=0,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="bos_id",
+ full_name="sentencepiece.TrainerSpec.bos_id",
+ index=31,
+ number=41,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=1,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="eos_id",
+ full_name="sentencepiece.TrainerSpec.eos_id",
+ index=32,
+ number=42,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=2,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="pad_id",
+ full_name="sentencepiece.TrainerSpec.pad_id",
+ index=33,
+ number=43,
+ type=5,
+ cpp_type=1,
+ label=1,
+ has_default_value=True,
+ default_value=-1,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="unk_piece",
+ full_name="sentencepiece.TrainerSpec.unk_piece",
+ index=34,
+ number=45,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=True,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="bos_piece",
+ full_name="sentencepiece.TrainerSpec.bos_piece",
+ index=35,
+ number=46,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=True,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="eos_piece",
+ full_name="sentencepiece.TrainerSpec.eos_piece",
+ index=36,
+ number=47,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=True,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="pad_piece",
+ full_name="sentencepiece.TrainerSpec.pad_piece",
+ index=37,
+ number=48,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=True,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="unk_surface",
+ full_name="sentencepiece.TrainerSpec.unk_surface",
+ index=38,
+ number=44,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=True,
+ default_value=b" \342\201\207 ".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="train_extremely_large_corpus",
+ full_name="sentencepiece.TrainerSpec.train_extremely_large_corpus",
+ index=39,
+ number=49,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=False,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ ],
+ extensions=[],
+ nested_types=[],
+ enum_types=[
+ _TRAINERSPEC_MODELTYPE,
+ ],
+ serialized_options=None,
+ is_extendable=True,
+ syntax="proto2",
+ extension_ranges=[
+ (200, 536870912),
+ ],
+ oneofs=[],
+ serialized_start=45,
+ serialized_end=1358,
+)
+
+
+_NORMALIZERSPEC = _descriptor.Descriptor(
+ name="NormalizerSpec",
+ full_name="sentencepiece.NormalizerSpec",
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ create_key=_descriptor._internal_create_key,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name="name",
+ full_name="sentencepiece.NormalizerSpec.name",
+ index=0,
+ number=1,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="precompiled_charsmap",
+ full_name="sentencepiece.NormalizerSpec.precompiled_charsmap",
+ index=1,
+ number=2,
+ type=12,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"",
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="add_dummy_prefix",
+ full_name="sentencepiece.NormalizerSpec.add_dummy_prefix",
+ index=2,
+ number=3,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="remove_extra_whitespaces",
+ full_name="sentencepiece.NormalizerSpec.remove_extra_whitespaces",
+ index=3,
+ number=4,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="escape_whitespaces",
+ full_name="sentencepiece.NormalizerSpec.escape_whitespaces",
+ index=4,
+ number=5,
+ type=8,
+ cpp_type=7,
+ label=1,
+ has_default_value=True,
+ default_value=True,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="normalization_rule_tsv",
+ full_name="sentencepiece.NormalizerSpec.normalization_rule_tsv",
+ index=5,
+ number=6,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ ],
+ extensions=[],
+ nested_types=[],
+ enum_types=[],
+ serialized_options=None,
+ is_extendable=True,
+ syntax="proto2",
+ extension_ranges=[
+ (200, 536870912),
+ ],
+ oneofs=[],
+ serialized_start=1361,
+ serialized_end=1570,
+)
+
+
+_SELFTESTDATA_SAMPLE = _descriptor.Descriptor(
+ name="Sample",
+ full_name="sentencepiece.SelfTestData.Sample",
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ create_key=_descriptor._internal_create_key,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name="input",
+ full_name="sentencepiece.SelfTestData.Sample.input",
+ index=0,
+ number=1,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="expected",
+ full_name="sentencepiece.SelfTestData.Sample.expected",
+ index=1,
+ number=2,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ ],
+ extensions=[],
+ nested_types=[],
+ enum_types=[],
+ serialized_options=None,
+ is_extendable=False,
+ syntax="proto2",
+ extension_ranges=[],
+ oneofs=[],
+ serialized_start=1641,
+ serialized_end=1682,
+)
+
+_SELFTESTDATA = _descriptor.Descriptor(
+ name="SelfTestData",
+ full_name="sentencepiece.SelfTestData",
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ create_key=_descriptor._internal_create_key,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name="samples",
+ full_name="sentencepiece.SelfTestData.samples",
+ index=0,
+ number=1,
+ type=11,
+ cpp_type=10,
+ label=3,
+ has_default_value=False,
+ default_value=[],
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ ],
+ extensions=[],
+ nested_types=[
+ _SELFTESTDATA_SAMPLE,
+ ],
+ enum_types=[],
+ serialized_options=None,
+ is_extendable=True,
+ syntax="proto2",
+ extension_ranges=[
+ (200, 536870912),
+ ],
+ oneofs=[],
+ serialized_start=1572,
+ serialized_end=1693,
+)
+
+
+_MODELPROTO_SENTENCEPIECE = _descriptor.Descriptor(
+ name="SentencePiece",
+ full_name="sentencepiece.ModelProto.SentencePiece",
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ create_key=_descriptor._internal_create_key,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name="piece",
+ full_name="sentencepiece.ModelProto.SentencePiece.piece",
+ index=0,
+ number=1,
+ type=9,
+ cpp_type=9,
+ label=1,
+ has_default_value=False,
+ default_value=b"".decode("utf-8"),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="score",
+ full_name="sentencepiece.ModelProto.SentencePiece.score",
+ index=1,
+ number=2,
+ type=2,
+ cpp_type=6,
+ label=1,
+ has_default_value=False,
+ default_value=float(0),
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="type",
+ full_name="sentencepiece.ModelProto.SentencePiece.type",
+ index=2,
+ number=3,
+ type=14,
+ cpp_type=8,
+ label=1,
+ has_default_value=True,
+ default_value=1,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ ],
+ extensions=[],
+ nested_types=[],
+ enum_types=[
+ _MODELPROTO_SENTENCEPIECE_TYPE,
+ ],
+ serialized_options=None,
+ is_extendable=True,
+ syntax="proto2",
+ extension_ranges=[
+ (200, 536870912),
+ ],
+ oneofs=[],
+ serialized_start=1985,
+ serialized_end=2195,
+)
+
+_MODELPROTO = _descriptor.Descriptor(
+ name="ModelProto",
+ full_name="sentencepiece.ModelProto",
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ create_key=_descriptor._internal_create_key,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name="pieces",
+ full_name="sentencepiece.ModelProto.pieces",
+ index=0,
+ number=1,
+ type=11,
+ cpp_type=10,
+ label=3,
+ has_default_value=False,
+ default_value=[],
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="trainer_spec",
+ full_name="sentencepiece.ModelProto.trainer_spec",
+ index=1,
+ number=2,
+ type=11,
+ cpp_type=10,
+ label=1,
+ has_default_value=False,
+ default_value=None,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="normalizer_spec",
+ full_name="sentencepiece.ModelProto.normalizer_spec",
+ index=2,
+ number=3,
+ type=11,
+ cpp_type=10,
+ label=1,
+ has_default_value=False,
+ default_value=None,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="self_test_data",
+ full_name="sentencepiece.ModelProto.self_test_data",
+ index=3,
+ number=4,
+ type=11,
+ cpp_type=10,
+ label=1,
+ has_default_value=False,
+ default_value=None,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ _descriptor.FieldDescriptor(
+ name="denormalizer_spec",
+ full_name="sentencepiece.ModelProto.denormalizer_spec",
+ index=4,
+ number=5,
+ type=11,
+ cpp_type=10,
+ label=1,
+ has_default_value=False,
+ default_value=None,
+ message_type=None,
+ enum_type=None,
+ containing_type=None,
+ is_extension=False,
+ extension_scope=None,
+ serialized_options=None,
+ file=DESCRIPTOR,
+ create_key=_descriptor._internal_create_key,
+ ),
+ ],
+ extensions=[],
+ nested_types=[
+ _MODELPROTO_SENTENCEPIECE,
+ ],
+ enum_types=[],
+ serialized_options=None,
+ is_extendable=True,
+ syntax="proto2",
+ extension_ranges=[
+ (200, 536870912),
+ ],
+ oneofs=[],
+ serialized_start=1696,
+ serialized_end=2206,
+)
+
+_TRAINERSPEC.fields_by_name["model_type"].enum_type = _TRAINERSPEC_MODELTYPE
+_TRAINERSPEC_MODELTYPE.containing_type = _TRAINERSPEC
+_SELFTESTDATA_SAMPLE.containing_type = _SELFTESTDATA
+_SELFTESTDATA.fields_by_name["samples"].message_type = _SELFTESTDATA_SAMPLE
+_MODELPROTO_SENTENCEPIECE.fields_by_name["type"].enum_type = _MODELPROTO_SENTENCEPIECE_TYPE
+_MODELPROTO_SENTENCEPIECE.containing_type = _MODELPROTO
+_MODELPROTO_SENTENCEPIECE_TYPE.containing_type = _MODELPROTO_SENTENCEPIECE
+_MODELPROTO.fields_by_name["pieces"].message_type = _MODELPROTO_SENTENCEPIECE
+_MODELPROTO.fields_by_name["trainer_spec"].message_type = _TRAINERSPEC
+_MODELPROTO.fields_by_name["normalizer_spec"].message_type = _NORMALIZERSPEC
+_MODELPROTO.fields_by_name["self_test_data"].message_type = _SELFTESTDATA
+_MODELPROTO.fields_by_name["denormalizer_spec"].message_type = _NORMALIZERSPEC
+DESCRIPTOR.message_types_by_name["TrainerSpec"] = _TRAINERSPEC
+DESCRIPTOR.message_types_by_name["NormalizerSpec"] = _NORMALIZERSPEC
+DESCRIPTOR.message_types_by_name["SelfTestData"] = _SELFTESTDATA
+DESCRIPTOR.message_types_by_name["ModelProto"] = _MODELPROTO
+_sym_db.RegisterFileDescriptor(DESCRIPTOR)
+
+TrainerSpec = _reflection.GeneratedProtocolMessageType(
+ "TrainerSpec",
+ (_message.Message,),
+ {
+ "DESCRIPTOR": _TRAINERSPEC,
+ "__module__": "sentencepiece_model_pb2",
+ # @@protoc_insertion_point(class_scope:sentencepiece.TrainerSpec)
+ },
+)
+_sym_db.RegisterMessage(TrainerSpec)
+
+NormalizerSpec = _reflection.GeneratedProtocolMessageType(
+ "NormalizerSpec",
+ (_message.Message,),
+ {
+ "DESCRIPTOR": _NORMALIZERSPEC,
+ "__module__": "sentencepiece_model_pb2",
+ # @@protoc_insertion_point(class_scope:sentencepiece.NormalizerSpec)
+ },
+)
+_sym_db.RegisterMessage(NormalizerSpec)
+
+SelfTestData = _reflection.GeneratedProtocolMessageType(
+ "SelfTestData",
+ (_message.Message,),
+ {
+ "Sample": _reflection.GeneratedProtocolMessageType(
+ "Sample",
+ (_message.Message,),
+ {
+ "DESCRIPTOR": _SELFTESTDATA_SAMPLE,
+ "__module__": "sentencepiece_model_pb2",
+ # @@protoc_insertion_point(class_scope:sentencepiece.SelfTestData.Sample)
+ },
+ ),
+ "DESCRIPTOR": _SELFTESTDATA,
+ "__module__": "sentencepiece_model_pb2",
+ # @@protoc_insertion_point(class_scope:sentencepiece.SelfTestData)
+ },
+)
+_sym_db.RegisterMessage(SelfTestData)
+_sym_db.RegisterMessage(SelfTestData.Sample)
+
+ModelProto = _reflection.GeneratedProtocolMessageType(
+ "ModelProto",
+ (_message.Message,),
+ {
+ "SentencePiece": _reflection.GeneratedProtocolMessageType(
+ "SentencePiece",
+ (_message.Message,),
+ {
+ "DESCRIPTOR": _MODELPROTO_SENTENCEPIECE,
+ "__module__": "sentencepiece_model_pb2",
+ # @@protoc_insertion_point(class_scope:sentencepiece.ModelProto.SentencePiece)
+ },
+ ),
+ "DESCRIPTOR": _MODELPROTO,
+ "__module__": "sentencepiece_model_pb2",
+ # @@protoc_insertion_point(class_scope:sentencepiece.ModelProto)
+ },
+)
+_sym_db.RegisterMessage(ModelProto)
+_sym_db.RegisterMessage(ModelProto.SentencePiece)
+
+
+DESCRIPTOR._options = None
+_TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None
+_TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None
+# @@protoc_insertion_point(module_scope)
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/sentencepiece_model_pb2_new.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/sentencepiece_model_pb2_new.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ea4f4d64ce660b3d59d60c0650f5849e4fd2251
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/sentencepiece_model_pb2_new.py
@@ -0,0 +1,47 @@
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: sentencepiece_model.proto
+"""Generated protocol buffer code."""
+
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+
+
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(
+ b'\n\x19sentencepiece_model.proto\x12\rsentencepiece"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05\x12\x16\n\tbos_piece\x18. \x01(\t:\x03\x12\x17\n\teos_piece\x18/ \x01(\t:\x04\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03'
+)
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "sentencepiece_model_pb2", _globals)
+if _descriptor._USE_C_DESCRIPTORS is False:
+ DESCRIPTOR._options = None
+ DESCRIPTOR._serialized_options = b"H\003"
+ # (generated by protobuf compiler, but `_TRAINERSPEC` is not defined)
+ # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None
+ # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001"
+ # _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None
+ # _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001"
+ _globals["_TRAINERSPEC"]._serialized_start = 45
+ _globals["_TRAINERSPEC"]._serialized_end = 1581
+ _globals["_TRAINERSPEC_MODELTYPE"]._serialized_start = 1517
+ _globals["_TRAINERSPEC_MODELTYPE"]._serialized_end = 1570
+ _globals["_NORMALIZERSPEC"]._serialized_start = 1584
+ _globals["_NORMALIZERSPEC"]._serialized_end = 1793
+ _globals["_SELFTESTDATA"]._serialized_start = 1795
+ _globals["_SELFTESTDATA"]._serialized_end = 1916
+ _globals["_SELFTESTDATA_SAMPLE"]._serialized_start = 1864
+ _globals["_SELFTESTDATA_SAMPLE"]._serialized_end = 1905
+ _globals["_MODELPROTO"]._serialized_start = 1919
+ _globals["_MODELPROTO"]._serialized_end = 2429
+ _globals["_MODELPROTO_SENTENCEPIECE"]._serialized_start = 2208
+ _globals["_MODELPROTO_SENTENCEPIECE"]._serialized_end = 2418
+ _globals["_MODELPROTO_SENTENCEPIECE_TYPE"]._serialized_start = 2323
+ _globals["_MODELPROTO_SENTENCEPIECE_TYPE"]._serialized_end = 2407
+# @@protoc_insertion_point(module_scope)
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/type_validators.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/type_validators.py
new file mode 100644
index 0000000000000000000000000000000000000000..2600998277a6e41bcf5b4eb0a0c6693f85c3a31a
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/type_validators.py
@@ -0,0 +1,125 @@
+from collections.abc import Sequence
+from typing import Any, Union, cast
+
+from ..tokenization_utils_base import PaddingStrategy, TruncationStrategy
+from ..video_utils import VideoMetadataType
+from .generic import TensorType
+from .import_utils import is_torch_available, is_vision_available
+
+
+if is_vision_available():
+ from ..image_utils import PILImageResampling
+
+if is_torch_available():
+ import torch
+
+
+def positive_any_number(value: int | float | None = None):
+ if value is not None and (not isinstance(value, (int, float)) or not value >= 0):
+ raise ValueError(f"Value must be a positive integer or floating number, got {value}")
+
+
+def positive_int(value: int | None = None):
+ if value is not None and (not isinstance(value, int) or not value >= 0):
+ raise ValueError(f"Value must be a positive integer, got {value}")
+
+
+def padding_validator(value: bool | str | PaddingStrategy | None = None):
+ possible_names = ["longest", "max_length", "do_not_pad"]
+ if value is None:
+ pass
+ elif not isinstance(value, (bool, str, PaddingStrategy)):
+ raise ValueError("Value for padding must be either a boolean, a string or a `PaddingStrategy`")
+ elif isinstance(value, str) and value not in possible_names:
+ raise ValueError(f"If padding is a string, the value must be one of {possible_names}")
+
+
+def truncation_validator(value: bool | str | TruncationStrategy | None = None):
+ possible_names = ["only_first", "only_second", "longest_first", "do_not_truncate"]
+ if value is None:
+ pass
+ elif not isinstance(value, (bool, str, TruncationStrategy)):
+ raise ValueError("Value for truncation must be either a boolean, a string or a `TruncationStrategy`")
+ elif isinstance(value, str) and value not in possible_names:
+ raise ValueError(f"If truncation is a string, value must be one of {possible_names}")
+
+
+def image_size_validator(value: int | Sequence[int] | dict[str, int] | None = None):
+ possible_keys = ["height", "width", "longest_edge", "shortest_edge", "max_height", "max_width"]
+ if value is None:
+ pass
+ elif isinstance(value, dict) and any(k not in possible_keys for k in value.keys()):
+ raise ValueError(f"Value for size must be a dict with keys {possible_keys} but got size={value}")
+
+
+def device_validator(value: str | int | None = None):
+ possible_names = ["cpu", "cuda", "xla", "xpu", "mps", "meta"]
+ if value is None:
+ pass
+ elif is_torch_available() and isinstance(value, torch.device):
+ # Convert torch.device to string for validation
+ device_str = str(value)
+ if device_str.split(":")[0] not in possible_names:
+ raise ValueError(
+ f"If device is a torch.device, the value must be one of {possible_names} but got device={value}"
+ )
+ elif isinstance(value, int) and value < 0:
+ raise ValueError(
+ f"If device is an integer, the value must be a strictly positive integer but got device={value}"
+ )
+ elif isinstance(value, str) and value.split(":")[0] not in possible_names:
+ raise ValueError(f"If device is an string, the value must be one of {possible_names} but got device={value}")
+ elif not isinstance(value, (int, str)):
+ raise ValueError(
+ f"Device must be either an integer device ID, a string (e.g., 'cpu', 'cuda:0'), or a torch.device object, but got device={value}"
+ )
+
+
+def resampling_validator(value: Union[int, "PILImageResampling"] | None = None):
+ if value is None:
+ pass
+ elif isinstance(value, int) and value not in list(range(6)):
+ raise ValueError(
+ f"The resampling should be one of {list(range(6))} when provided as integer, but got resampling={value}"
+ )
+ elif is_vision_available() and not isinstance(value, (PILImageResampling, int)):
+ raise ValueError(f"The resampling should an integer or `PIL.Image.Resampling`, but got resampling={value}")
+
+
+def video_metadata_validator(value: VideoMetadataType | None = None):
+ if value is None:
+ return
+
+ valid_keys = ["total_num_frames", "fps", "width", "height", "duration", "video_backend", "frames_indices"]
+
+ def check_dict_keys(d: dict[str, Any]) -> bool:
+ return all(key in valid_keys for key in d.keys())
+
+ if isinstance(value, Sequence) and isinstance(value[0], Sequence) and isinstance(value[0][0], dict):
+ for sublist in value:
+ for item in sublist:
+ if not check_dict_keys(item):
+ raise ValueError(
+ f"Invalid keys found in video metadata. Valid keys: {valid_keys} got: {list(item.keys())}"
+ )
+
+ elif isinstance(value, Sequence) and isinstance(value[0], dict):
+ for item in value:
+ if not check_dict_keys(item):
+ raise ValueError(
+ f"Invalid keys found in video metadata. Valid keys: {valid_keys} got: {list(cast(dict, item).keys())}"
+ )
+
+ elif isinstance(value, dict):
+ if not check_dict_keys(value):
+ raise ValueError(
+ f"Invalid keys found in video metadata. Valid keys: {valid_keys}, got: {list(value.keys())}"
+ )
+
+
+def tensor_type_validator(value: str | TensorType | None = None):
+ possible_names = ["pt", "np", "mlx"]
+ if value is None:
+ pass
+ elif not isinstance(value, str) or value not in possible_names:
+ raise ValueError(f"The tensor type should be one of {possible_names} but got tensor_type={value}")
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/versions.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/versions.py
new file mode 100644
index 0000000000000000000000000000000000000000..452f0d48a8e279c6e16fba74d9d565b59da1cfc5
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/transformers/utils/versions.py
@@ -0,0 +1,116 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Utilities for working with package versions
+"""
+
+import importlib.metadata
+import operator
+import re
+import sys
+
+from packaging import version
+
+
+ops = {
+ "<": operator.lt,
+ "<=": operator.le,
+ "==": operator.eq,
+ "!=": operator.ne,
+ ">=": operator.ge,
+ ">": operator.gt,
+}
+
+
+def _compare_versions(op, got_ver, want_ver, requirement, pkg, hint):
+ if got_ver is None or want_ver is None:
+ raise ValueError(
+ f"Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider"
+ f" reinstalling {pkg}."
+ )
+ if not ops[op](version.parse(got_ver), version.parse(want_ver)):
+ raise ImportError(
+ f"{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}"
+ )
+
+
+def require_version(requirement: str, hint: str | None = None) -> None:
+ """
+ Perform a runtime check of the dependency versions, using the exact same syntax used by pip.
+
+ The installed module version comes from the *site-packages* dir via *importlib.metadata*.
+
+ Args:
+ requirement (`str`): pip style definition, e.g., "tokenizers==0.9.4", "tqdm>=4.27", "numpy"
+ hint (`str`, *optional*): what suggestion to print in case of requirements not being met
+
+ Example:
+
+ ```python
+ require_version("pandas>1.1.2")
+ require_version("numpy>1.18.5", "this is important to have for whatever reason")
+ ```"""
+
+ hint = f"\n{hint}" if hint is not None else ""
+
+ # non-versioned check
+ if re.match(r"^[\w_\-\d]+$", requirement):
+ pkg, op, want_ver = requirement, None, None
+ else:
+ match = re.findall(r"^([^!=<>\s]+)([\s!=<>]{1,2}.+)", requirement)
+ if not match:
+ raise ValueError(
+ "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but"
+ f" got {requirement}"
+ )
+ pkg, want_full = match[0]
+ want_range = want_full.split(",") # there could be multiple requirements
+ wanted = {}
+ for w in want_range:
+ match = re.findall(r"^([\s!=<>]{1,2})(.+)", w)
+ if not match:
+ raise ValueError(
+ "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,"
+ f" but got {requirement}"
+ )
+ op, want_ver = match[0]
+ wanted[op] = want_ver
+ if op not in ops:
+ raise ValueError(f"{requirement}: need one of {list(ops.keys())}, but got {op}")
+
+ # special case
+ if pkg == "python":
+ got_ver = ".".join([str(x) for x in sys.version_info[:3]])
+ for op, want_ver in wanted.items():
+ _compare_versions(op, got_ver, want_ver, requirement, pkg, hint)
+ return
+
+ # check if any version is installed
+ try:
+ got_ver = importlib.metadata.version(pkg)
+ except importlib.metadata.PackageNotFoundError:
+ raise importlib.metadata.PackageNotFoundError(
+ f"The '{requirement}' distribution was not found and is required by this application. {hint}"
+ )
+
+ # check that the right version is installed if version number or a range was provided
+ if want_ver is not None:
+ for op, want_ver in wanted.items():
+ _compare_versions(op, got_ver, want_ver, requirement, pkg, hint)
+
+
+def require_version_core(requirement):
+ """require_version wrapper which emits a core-specific hint on failure"""
+ hint = "Try: `pip install transformers -U` or `pip install -e '.[dev]'` if you're working with git main"
+ return require_version(requirement, hint)
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/_C/libtriton/linear_layout.pyi b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/_C/libtriton/linear_layout.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..e1b4599dd024fb96de12cb14b3eecd16bf1dbf64
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/_C/libtriton/linear_layout.pyi
@@ -0,0 +1,80 @@
+from __future__ import annotations
+
+from typing import List, Optional, Sequence, Tuple
+
+
+class LinearLayout:
+ def __init__(self) -> None: ...
+
+ @staticmethod
+ def identity_1d(size: int, inDim: str, outDim: str) -> LinearLayout: ...
+
+ @staticmethod
+ def strided_1d(
+ size: int, stride: int, inDim: str, outDim: str
+ ) -> LinearLayout: ...
+
+ @staticmethod
+ def zeros_1d(
+ size: int, inDim: str, outDim: str, outDimSize: int
+ ) -> LinearLayout: ...
+
+ @staticmethod
+ def from_bases(
+ bases: Sequence[Tuple[str, Sequence[Sequence[int]]]],
+ out_dim_names: Sequence[str],
+ out_dim_sizes: Optional[Sequence[int]] = ...,
+ require_surjective: bool = ...,
+ ) -> LinearLayout: ...
+
+ def compose(self, other: LinearLayout) -> LinearLayout: ...
+
+ def invert_and_compose(self, other: LinearLayout) -> LinearLayout: ...
+
+ def invert(self) -> LinearLayout: ...
+
+ def pseudoinvert(self) -> LinearLayout: ...
+
+ def is_surjective(self) -> bool: ...
+
+ def is_injective(self) -> bool: ...
+
+ def is_invertible(self) -> bool: ...
+
+ def get_in_dim_names(self) -> List[str]: ...
+
+ def get_out_dim_names(self) -> List[str]: ...
+
+ @property
+ def bases(self) -> List[Tuple[str, List[List[int]]]]: ...
+
+ @property
+ def out_dims(self) -> List[Tuple[str, int]]: ...
+
+ @property
+ def num_in_dims(self) -> int: ...
+
+ @property
+ def num_out_dims(self) -> int: ...
+
+ def __mul__(self, other: LinearLayout) -> LinearLayout: ...
+
+ def __imul__(self, other: LinearLayout) -> LinearLayout: ...
+
+ def get_shared_view(self, useHWPointOfView: bool) -> str: ...
+
+ def get_distributed_view(self, useHWPointOfView: bool) -> str: ...
+
+ def get_matrix_view(self) -> List[List[int]]: ...
+
+ def apply(
+ self, inputs: Sequence[Tuple[str, int]]
+ ) -> List[Tuple[str, int]]: ...
+
+ def __eq__(self, other: object) -> bool: ...
+
+ def __ne__(self, other: object) -> bool: ...
+
+ def __repr__(self) -> str: ...
+
+ def __str__(self) -> str: ...
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d637cf0b25c543046eb6a62ee6d5f11f1f2c1d4
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/__init__.py
@@ -0,0 +1,82 @@
+"""isort:skip_file"""
+__version__ = '3.6.0'
+
+# ---------------------------------------
+# Note: import order is significant here.
+
+# submodules
+from .runtime import (
+ autotune,
+ Config,
+ heuristics,
+ JITFunction,
+ KernelInterface,
+ reinterpret,
+ TensorWrapper,
+ OutOfResources,
+ InterpreterError,
+ MockTensor,
+)
+from .runtime.jit import constexpr_function, jit
+from .runtime._async_compile import AsyncCompileMode, FutureKernel
+from .compiler import compile, CompilationError
+from .errors import TritonError
+from .runtime._allocation import set_allocator
+
+from . import language
+from . import testing
+from . import tools
+
+must_use_result = language.core.must_use_result
+
+__all__ = [
+ "AsyncCompileMode",
+ "autotune",
+ "cdiv",
+ "CompilationError",
+ "compile",
+ "Config",
+ "constexpr_function",
+ "FutureKernel",
+ "heuristics",
+ "InterpreterError",
+ "jit",
+ "JITFunction",
+ "KernelInterface",
+ "language",
+ "MockTensor",
+ "must_use_result",
+ "next_power_of_2",
+ "OutOfResources",
+ "reinterpret",
+ "runtime",
+ "set_allocator",
+ "TensorWrapper",
+ "TritonError",
+ "testing",
+ "tools",
+]
+
+# -------------------------------------
+# misc. utilities that don't fit well
+# into any specific module
+# -------------------------------------
+
+
+@constexpr_function
+def cdiv(x: int, y: int):
+ return (x + y - 1) // y
+
+
+@constexpr_function
+def next_power_of_2(n: int):
+ """Return the smallest power of 2 greater than or equal to n"""
+ n -= 1
+ n |= n >> 1
+ n |= n >> 2
+ n |= n >> 4
+ n |= n >> 8
+ n |= n >> 16
+ n |= n >> 32
+ n += 1
+ return n
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/_filecheck.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/_filecheck.py
new file mode 100644
index 0000000000000000000000000000000000000000..d96eb3cca718dd10eb097314aae3209aed100139
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/_filecheck.py
@@ -0,0 +1,96 @@
+import functools
+import os
+import inspect
+import subprocess
+import tempfile
+
+import triton
+from triton.compiler import ASTSource, make_backend
+from triton.backends.compiler import GPUTarget
+from triton.experimental.gluon._runtime import GluonASTSource
+from triton.runtime.jit import create_function_from_signature
+from triton._C.libtriton import ir
+
+# ===-----------------------------------------------------------------------===#
+# filecheck_test
+# ===-----------------------------------------------------------------------===#
+
+# Stub target for testing the frontend.
+stub_target = GPUTarget("cuda", 100, 32)
+
+triton_dir = os.path.dirname(__file__)
+filecheck_path = os.path.join(triton_dir, "FileCheck")
+
+
+class MatchError(ValueError):
+
+ def __init__(self, message, module_str):
+ super().__init__(message)
+ self.module_str = module_str
+
+ def __str__(self):
+ return f"{super().__str__()}\n{self.module_str}"
+
+
+def run_filecheck(name, module_str, check_template):
+ with tempfile.TemporaryDirectory() as tempdir:
+ temp_module = os.path.join(tempdir, "module")
+ with open(temp_module, "w") as temp:
+ temp.write(module_str)
+
+ temp_expected = os.path.join(tempdir, "expected")
+ with open(temp_expected, "w") as temp:
+ temp.write(check_template)
+
+ try:
+ subprocess.check_output(
+ [filecheck_path, temp_expected, "--input-file", temp_module, "--dump-input-context=50"],
+ stderr=subprocess.STDOUT)
+ except subprocess.CalledProcessError as error:
+ decoded = error.output.decode('unicode_escape')
+ raise ValueError(decoded)
+
+
+def run_parser(kernel_fn, args=(), kwargs={}, target=stub_target):
+ if "sanitize_overflow" not in kwargs:
+ kwargs = dict(kwargs)
+ kwargs["sanitize_overflow"] = False
+ backend = make_backend(target)
+ binder = create_function_from_signature(
+ kernel_fn.signature,
+ kernel_fn.params,
+ backend,
+ )
+
+ bound_args, specialization, options = binder(*args, **kwargs)
+ options, signature, constexprs, attrs = kernel_fn._pack_args(backend, kwargs, bound_args, specialization, options)
+ source_cls = GluonASTSource if kernel_fn.is_gluon() else ASTSource
+ src = source_cls(kernel_fn, signature, constexprs, attrs)
+
+ context = ir.context()
+ ir.load_dialects(context)
+ backend.load_dialects(context)
+
+ codegen_fns = backend.get_codegen_implementation(options)
+ module_map = backend.get_module_map()
+ module = src.make_ir(target, options, codegen_fns, module_map, context)
+ return module
+
+
+def run_filecheck_test(kernel_fn):
+ assert isinstance(kernel_fn, triton.runtime.JITFunction)
+ check_template = inspect.getsource(kernel_fn.fn)
+ if check_template is None:
+ raise ValueError("kernel function must have a docstring with FileCheck template")
+ mlir_module = run_parser(kernel_fn)
+
+ run_filecheck("placeholder", mlir_module.str_nodebug(), check_template)
+
+
+def filecheck_test(fn):
+
+ @functools.wraps(fn)
+ def test_fn():
+ run_filecheck_test(fn)
+
+ return test_fn
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/_internal_testing.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/_internal_testing.py
new file mode 100644
index 0000000000000000000000000000000000000000..562e8df721ea7e025101429fb5ca25c9702ebf92
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/_internal_testing.py
@@ -0,0 +1,272 @@
+import os
+import re
+import numpy as np
+import torch
+import triton
+import triton.language as tl
+from triton import knobs
+from typing import Optional, Set, Union
+import pytest
+
+from numpy.random import RandomState
+from triton.runtime.jit import TensorWrapper, reinterpret, type_canonicalisation_dict
+
+int_dtypes = ['int8', 'int16', 'int32', 'int64']
+uint_dtypes = ['uint8', 'uint16', 'uint32', 'uint64']
+integral_dtypes = int_dtypes + uint_dtypes
+float_dtypes = ['float16', 'float32', 'float64']
+float_dtypes_with_bfloat16 = float_dtypes + ['bfloat16']
+dtypes = integral_dtypes + float_dtypes
+dtypes_with_bfloat16 = dtypes + ['bfloat16']
+torch_float8_dtypes = ['float8_e4m3fn', 'float8_e5m2']
+torch_dtypes = ['bool'] + int_dtypes + ['uint8'] + float_dtypes + ['bfloat16']
+tma_dtypes = sorted(set(dtypes_with_bfloat16) - {"int64", "uint64", "float64"})
+
+
+def is_interpreter():
+ return os.environ.get('TRITON_INTERPRET', '0') == '1'
+
+
+def get_current_target():
+ if is_interpreter():
+ return None
+ return triton.runtime.driver.active.get_current_target()
+
+
+def is_cuda():
+ target = get_current_target()
+ return False if target is None else target.backend == "cuda"
+
+
+def is_ampere_or_newer():
+ return is_cuda() and torch.cuda.get_device_capability()[0] >= 8
+
+
+def is_blackwell():
+ return is_cuda() and torch.cuda.get_device_capability()[0] == 10
+
+
+def is_hopper_or_newer():
+ return is_cuda() and torch.cuda.get_device_capability()[0] >= 9
+
+
+def is_hopper():
+ return is_cuda() and torch.cuda.get_device_capability()[0] == 9
+
+
+def is_sm12x():
+ return is_cuda() and torch.cuda.get_device_capability()[0] == 12
+
+
+def is_hip():
+ target = get_current_target()
+ return False if target is None else target.backend == "hip"
+
+
+def is_hip_cdna2():
+ target = get_current_target()
+ return target is not None and target.backend == 'hip' and target.arch == 'gfx90a'
+
+
+def is_hip_cdna3():
+ target = get_current_target()
+ return target is not None and target.backend == 'hip' and target.arch == 'gfx942'
+
+
+def is_hip_cdna4():
+ target = get_current_target()
+ return target is not None and target.backend == 'hip' and target.arch == 'gfx950'
+
+
+def is_hip_gfx11():
+ target = get_current_target()
+ return target is not None and target.backend == 'hip' and 'gfx11' in target.arch
+
+
+def is_hip_gfx12():
+ target = get_current_target()
+ return target is not None and target.backend == 'hip' and 'gfx12' in target.arch
+
+
+def is_hip_gfx1250():
+ target = get_current_target()
+ return target is not None and target.backend == 'hip' and 'gfx1250' in target.arch
+
+
+def is_hip_cdna():
+ return is_hip_cdna2() or is_hip_cdna3() or is_hip_cdna4()
+
+
+def get_hip_lds_size():
+ return 163840 if is_hip_cdna4() else 65536
+
+
+def is_xpu():
+ target = get_current_target()
+ return False if target is None else target.backend == "xpu"
+
+
+def get_arch():
+ target = get_current_target()
+ return "" if target is None else str(target.arch)
+
+
+def numpy_random(shape, dtype_str, rs: Optional[RandomState] = None, low=None, high=None):
+ """
+ Override `rs` if you're calling this function twice and don't want the same
+ result for both calls.
+ """
+ if isinstance(shape, int):
+ shape = (shape, )
+ if rs is None:
+ rs = RandomState(seed=17)
+ if dtype_str in int_dtypes + uint_dtypes:
+ iinfo = np.iinfo(getattr(np, dtype_str))
+ low = iinfo.min if low is None else max(low, iinfo.min)
+ high = iinfo.max if high is None else min(high, iinfo.max)
+ dtype = getattr(np, dtype_str)
+ x = rs.randint(low, high, shape, dtype=dtype)
+ x[x == 0] = 1 # Workaround. Never return zero so tests of division don't error out.
+ return x
+ elif dtype_str and 'float8' in dtype_str:
+ x = rs.randint(20, 40, shape, dtype=np.int8)
+ return x
+ elif dtype_str in float_dtypes:
+ return rs.normal(0, 1, shape).astype(dtype_str)
+ elif dtype_str == 'bfloat16':
+ return (rs.normal(0, 1, shape).astype('float32').view('uint32') & np.uint32(0xffff0000)).view('float32')
+ elif dtype_str in ['bool', 'int1', 'bool_']:
+ return rs.normal(0, 1, shape) > 0.0
+ else:
+ raise RuntimeError(f'Unknown dtype {dtype_str}')
+
+
+def to_triton(x: np.ndarray, device, dst_type=None) -> Union[TensorWrapper, torch.Tensor]:
+ '''
+ Note: We need dst_type because the type of x can be different from dst_type.
+ For example: x is of type `float32`, dst_type is `bfloat16`.
+ If dst_type is None, we infer dst_type from x.
+ '''
+ t = x.dtype.name
+ if t in uint_dtypes:
+ signed_type_name = t.lstrip('u') # e.g. "uint16" -> "int16"
+ x_signed = x.astype(getattr(np, signed_type_name))
+ return reinterpret(torch.tensor(x_signed, device=device), getattr(tl, t))
+ else:
+ if dst_type and 'float8' in dst_type:
+ return reinterpret(torch.tensor(x, device=device), getattr(tl, dst_type))
+ if t == 'float32' and dst_type == 'bfloat16':
+ return torch.tensor(x, device=device).bfloat16()
+ return torch.tensor(x, device=device)
+
+
+def str_to_triton_dtype(x: str) -> tl.dtype:
+ return tl.str_to_ty(type_canonicalisation_dict[x], None)
+
+
+def torch_dtype_name(dtype) -> str:
+ if isinstance(dtype, triton.language.dtype):
+ return dtype.name
+ elif isinstance(dtype, torch.dtype):
+ # 'torch.int64' -> 'int64'
+ m = re.match(r'^torch\.(\w+)$', str(dtype))
+ return m.group(1)
+ else:
+ raise TypeError(f'not a triton or torch dtype: {type(dtype)}')
+
+
+def to_numpy(x):
+ if isinstance(x, TensorWrapper):
+ return x.base.cpu().numpy().astype(getattr(np, torch_dtype_name(x.dtype)))
+ elif isinstance(x, torch.Tensor):
+ if x.dtype is torch.bfloat16:
+ return x.cpu().float().numpy()
+ return x.cpu().numpy()
+ else:
+ raise ValueError(f"Not a triton-compatible tensor: {x}")
+
+
+def supports_tma(byval_only=False):
+ if is_interpreter():
+ return True
+ if not is_cuda():
+ return False
+ cuda_version = knobs.nvidia.ptxas.version
+ min_cuda_version = (12, 0) if byval_only else (12, 3)
+ cuda_version_tuple = tuple(map(int, cuda_version.split(".")))
+ assert len(cuda_version_tuple) == 2, cuda_version_tuple
+ return torch.cuda.get_device_capability()[0] >= 9 and cuda_version_tuple >= min_cuda_version
+
+
+def supports_ws():
+ if is_interpreter():
+ return True
+ if not is_cuda():
+ return False
+ return torch.cuda.get_device_capability()[0] >= 9
+
+
+def tma_skip_msg(byval_only=False):
+ if byval_only:
+ return "Requires __grid_constant__ TMA support (NVIDIA Hopper or higher, CUDA 12.0 or higher)"
+ else:
+ return "Requires advanced TMA support (NVIDIA Hopper or higher, CUDA 12.3 or higher)"
+
+
+requires_tma = pytest.mark.skipif(not supports_tma(), reason=tma_skip_msg())
+
+
+def default_alloc_fn(size: int, align: int, _):
+ return torch.empty(size, dtype=torch.int8, device="cuda")
+
+
+def unwrap_tensor(t: Union[torch.Tensor, triton.runtime.jit.TensorWrapper]) -> torch.Tensor:
+ if isinstance(t, triton.runtime.jit.TensorWrapper):
+ return t.base
+ return t
+
+
+def _fresh_knobs_impl(skipped_attr: Optional[Set[str]] = None):
+ from triton import knobs
+
+ if skipped_attr is None:
+ skipped_attr = set()
+
+ monkeypatch = pytest.MonkeyPatch()
+
+ knobs_map = {
+ name: knobset
+ for name, knobset in knobs.__dict__.items()
+ if isinstance(knobset, knobs.base_knobs) and knobset != knobs.base_knobs and name not in skipped_attr
+ }
+
+ # We store which variables we need to unset below in finally because
+ # monkeypatch doesn't appear to reset variables that were never set
+ # before the monkeypatch.delenv call below.
+ env_to_unset = []
+ prev_propagate_env = knobs.propagate_env
+
+ def fresh_function():
+ nonlocal env_to_unset
+ for name, knobset in knobs_map.items():
+ setattr(knobs, name, knobset.copy().reset())
+ for knob in knobset.knob_descriptors.values():
+ if knob.key in os.environ:
+ monkeypatch.delenv(knob.key, raising=False)
+ else:
+ env_to_unset.append(knob.key)
+ knobs.propagate_env = True
+ return knobs
+
+ def reset_function():
+ for name, knobset in knobs_map.items():
+ setattr(knobs, name, knobset)
+ # `undo` should be placed before `del os.environ`
+ # Otherwise, it may restore environment variables that monkeypatch deleted
+ monkeypatch.undo()
+ for k in env_to_unset:
+ if k in os.environ:
+ del os.environ[k]
+ knobs.propagate_env = prev_propagate_env
+
+ return fresh_function, reset_function
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/_utils.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3cf0ff0cbdb6047e9379cbc38cc44e5c2b52a62
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/_utils.py
@@ -0,0 +1,134 @@
+from __future__ import annotations
+
+from functools import reduce
+from typing import Any, Callable, TYPE_CHECKING, Union, List, Dict
+
+if TYPE_CHECKING:
+ from .language import core
+ IterableType = Union[list[Any], tuple[Any, ...], core.tuple, core.tuple_type]
+ ObjPath = tuple[int, ...]
+
+TRITON_MAX_TENSOR_NUMEL = 1048576
+
+
+def get_iterable_path(iterable: IterableType, path: ObjPath) -> Any:
+ return reduce(lambda a, idx: a[idx], path, iterable) # type: ignore[index]
+
+
+def set_iterable_path(iterable: IterableType, path: tuple[int, ...], val: Any):
+ from .language import core
+ assert len(path) != 0
+ prev = iterable if len(path) == 1 else get_iterable_path(iterable, path[:-1])
+ assert isinstance(prev, core.tuple)
+ prev._setitem(path[-1], val)
+
+
+def find_paths_if(iterable: Union[IterableType, Any], pred: Callable[[ObjPath, Any], bool]) -> list[ObjPath]:
+ from .language import core
+ is_iterable: Callable[[Any], bool] = lambda x: isinstance(x, (list, tuple, core.tuple, core.tuple_type))
+ # We need to use dict so that ordering is maintained, while set doesn't guarantee order
+ ret: dict[ObjPath, None] = {}
+
+ def _impl(path: tuple[int, ...], current: Any):
+ if is_iterable(current):
+ for idx, item in enumerate(current):
+ _impl((*path, idx), item)
+ elif pred(path, current):
+ ret[path] = None
+
+ _impl((), iterable)
+
+ return list(ret.keys())
+
+
+def is_power_of_two(x):
+ return (x & (x - 1)) == 0
+
+
+def validate_block_shape(shape: List[int]):
+ numel = 1
+ for i, d in enumerate(shape):
+ if not isinstance(d, int):
+ raise TypeError(f"Shape element {i} must have type `constexpr[int]`, got `constexpr[{type(d)}]")
+ if not is_power_of_two(d):
+ raise ValueError(f"Shape element {i} must be a power of 2")
+ numel *= d
+
+ if numel > TRITON_MAX_TENSOR_NUMEL:
+ raise ValueError(f"numel ({numel}) exceeds triton maximum tensor numel ({TRITON_MAX_TENSOR_NUMEL})")
+ return numel
+
+
+type_canonicalisation_dict = {
+ # we canonicalise all bools to be unsigned:
+ "bool": "u1",
+ "int1": "u1",
+ "uint1": "u1",
+ "i1": "u1",
+ # floating-point dtypes:
+ "float8e4nv": "fp8e4nv",
+ "float8e5": "fp8e5",
+ "float8e4b15": "fp8e4b15",
+ "float8_e4m3fn": "fp8e4nv",
+ "float8e4b8": "fp8e4b8",
+ "float8_e4m3fnuz": "fp8e4b8",
+ "float8_e5m2": "fp8e5",
+ "float8e5b16": "fp8e5b16",
+ "float8_e5m2fnuz": "fp8e5b16",
+ "half": "fp16",
+ "float16": "fp16",
+ "bfloat16": "bf16",
+ "float": "fp32",
+ "float32": "fp32",
+ "double": "fp64",
+ "float64": "fp64",
+ # signed integers:
+ "int8": "i8",
+ "int16": "i16",
+ "int": "i32",
+ "int32": "i32",
+ "int64": "i64",
+ # unsigned integers:
+ "uint8": "u8",
+ "uint16": "u16",
+ "uint32": "u32",
+ "uint64": "u64",
+ "void": "void",
+}
+
+for v in list(type_canonicalisation_dict.values()):
+ type_canonicalisation_dict[v] = v
+
+
+def canonicalize_dtype(dtype):
+ dtype_str = str(dtype).split(".")[-1]
+ return type_canonicalisation_dict[dtype_str]
+
+
+def canonicalize_ptr_dtype(dtype, is_const):
+ return f"{'*k' if is_const else '*'}{canonicalize_dtype(dtype)}"
+
+
+BITWIDTH_DICT: Dict[str, int] = {
+ **{f"u{n}": n
+ for n in (1, 8, 16, 32, 64)},
+ **{f"i{n}": n
+ for n in (1, 8, 16, 32, 64)},
+ **{f"fp{n}": n
+ for n in (16, 32, 64)},
+ **{f"fp8{suffix}": 8
+ for suffix in ("e4nv", "e4b15", "e4b8", "e5", "e5b16")},
+ "bf16": 16,
+ "void": 0,
+}
+
+for k, v in type_canonicalisation_dict.items():
+ BITWIDTH_DICT[k] = BITWIDTH_DICT[v]
+
+
+def get_primitive_bitwidth(dtype: str) -> int:
+ return BITWIDTH_DICT[dtype]
+
+
+def is_namedtuple(val):
+ return isinstance(val, type) and issubclass(val, tuple) and hasattr(val, "_fields")
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..97092379e02dfd25611fc049744ecfc493d76c3d
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/__init__.py
@@ -0,0 +1,66 @@
+import importlib
+import os
+import inspect
+import sys
+from dataclasses import dataclass
+from typing import Type, TypeVar, Union
+from types import ModuleType
+from .driver import DriverBase
+from .compiler import BaseBackend
+
+if sys.version_info >= (3, 10):
+ from importlib.metadata import entry_points
+else:
+ from importlib_metadata import entry_points
+
+T = TypeVar("T", bound=Union[BaseBackend, DriverBase])
+
+
+def _find_concrete_subclasses(module: ModuleType, base_class: Type[T]) -> Type[T]:
+ ret: list[Type[T]] = []
+ for attr_name in dir(module):
+ attr = getattr(module, attr_name)
+ if isinstance(attr, type) and issubclass(attr, base_class) and not inspect.isabstract(attr):
+ ret.append(attr)
+ if len(ret) == 0:
+ raise RuntimeError(f"Found 0 concrete subclasses of {base_class} in {module}: {ret}")
+ if len(ret) > 1:
+ raise RuntimeError(f"Found >1 concrete subclasses of {base_class} in {module}: {ret}")
+ return ret[0]
+
+
+@dataclass(frozen=True)
+class Backend:
+ compiler: Type[BaseBackend]
+ driver: Type[DriverBase]
+
+
+def _discover_backends() -> dict[str, Backend]:
+ backends = dict()
+ # Fast path: optionally skip entry point discovery (which can be slow) and
+ # discover only in-tree backends under the `triton.backends` namespace.
+ skip_entrypoints_env = os.environ.get("TRITON_BACKENDS_IN_TREE", "")
+
+ if skip_entrypoints_env == "1":
+ root = os.path.dirname(__file__)
+ for name in os.listdir(root):
+ if not os.path.isdir(os.path.join(root, name)):
+ continue
+ if name.startswith('__'):
+ continue
+ compiler = importlib.import_module(f"triton.backends.{name}.compiler")
+ driver = importlib.import_module(f"triton.backends.{name}.driver")
+ backends[name] = Backend(_find_concrete_subclasses(compiler, BaseBackend),
+ _find_concrete_subclasses(driver, DriverBase))
+ return backends
+
+ # Default path: discover via entry points for out-of-tree/downstream plugins.
+ for ep in entry_points().select(group="triton.backends"):
+ compiler = importlib.import_module(f"{ep.value}.compiler")
+ driver = importlib.import_module(f"{ep.value}.driver")
+ backends[ep.name] = Backend(_find_concrete_subclasses(compiler, BaseBackend), # type: ignore
+ _find_concrete_subclasses(driver, DriverBase)) # type: ignore
+ return backends
+
+
+backends: dict[str, Backend] = _discover_backends()
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/amd/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/amd/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/amd/compiler.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/amd/compiler.py
new file mode 100644
index 0000000000000000000000000000000000000000..887802333d8d385c2ba42e5a2753e61bcb6e9b59
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/amd/compiler.py
@@ -0,0 +1,495 @@
+from triton.backends.compiler import BaseBackend, GPUTarget, Language
+from triton._C.libtriton import ir, passes, llvm, amd
+from triton import knobs
+from dataclasses import dataclass
+from typing import Any, Dict, Tuple
+from types import ModuleType
+import hashlib
+import tempfile
+import re
+import functools
+import warnings
+from pathlib import Path
+
+
+def get_min_dot_size(target: GPUTarget):
+ # We fallback to use FMA and cast arguments if certain configurations is
+ # not supported natively by matrix core units.
+ return lambda lhs_type, rhs_type: (1, 1, 1)
+
+
+def is_pingpong_schedule_enabled(arch, use_async_copy):
+ return (arch == "gfx942" or (arch == "gfx950" and use_async_copy is True)
+ ) if knobs.amd.use_block_pingpong is None else knobs.amd.use_block_pingpong
+
+
+def is_in_thread_transpose_enabled(arch):
+ return (arch == "gfx942") if knobs.amd.use_in_thread_transpose is None else knobs.amd.use_in_thread_transpose
+
+
+@dataclass(frozen=True)
+class HIPOptions:
+ num_warps: int = 4
+ waves_per_eu: int = 0
+ num_stages: int = 2
+ num_ctas: int = 1
+ extern_libs: dict = None
+ debug: bool = False
+ sanitize_overflow: bool = True
+ arch: str = None
+ # We have native support for OCP fp8 variants since CDNA4/RDNA4. For earlier generations,
+ # we software emulate the support for them.
+ # UZ fp8 variants (fp8e4b8 and fp8e5b16) are natively supported for CDNA3. For other
+ # architectures they are software emulated.
+ supported_fp8_dtypes: Tuple[str] = ("fp8e4nv", "fp8e5", "fp8e5b16", "fp8e4b8")
+ deprecated_fp8_dot_operand_dtypes: Tuple[str] = ()
+ default_dot_input_precision: str = "ieee"
+ allowed_dot_input_precisions: Tuple[str] = ("ieee", 'bf16x3', 'bf16x6')
+ enable_fp_fusion: bool = True
+ launch_cooperative_grid: bool = False
+ matrix_instr_nonkdim: int = 0
+ kpack: int = 1
+ allow_flush_denorm: bool = False
+ max_num_imprecise_acc_default: int = 0
+ backend_name: str = 'hip'
+ instrumentation_mode: str = ""
+
+ # The following option provides hints to the AMDGPU backend regarding instruction scheduling
+ # for all `tt.dot` operations in a kernel. The "none" variant preserves the default
+ # instruction scheduling of the AMDGPU backend which aims at maximizing occupancy.
+ # The option is experimental and may change at any time regarding its semantics and/or may
+ # be gone entirely anytime.
+ #
+ # Current experimental scheduling variants:
+ #
+ # attention: enables a bunch of optimizations for attention kernels, including:
+ # - iglp 2 and sched.barrier around it
+ # - sink-insts-to-avoid-spills flag to avoid register spills
+ # memory-bound-attention: enables custom scheduling strategy in llvm backend,
+ # This option targets special FA variant, which is memory bound and
+ # has a lot of elementwise operations from fused operand dequantizations.
+ # Note that this option is highly experimental,
+ # and will be removed as soon as default sceduler algorithm is fixed.
+ #
+ # Option allows to set multiple variants divided by commas:
+ # schedule_hint="attention,memory-bound-attention"
+ schedule_hint: str = 'none'
+
+ def __post_init__(self):
+ gfx_major = int(self.arch[3:-2]) # Drop "gfx" prefix and minor/patch number
+ warp_size = 32 if gfx_major >= 10 else 64
+ object.__setattr__(self, 'warp_size', warp_size)
+ assert self.num_warps > 0 and (self.num_warps & (self.num_warps - 1)) == 0, \
+ "num_warps must be a power of 2"
+
+ if (self.arch == 'gfx950') and (self.kpack != 1):
+ warnings.warn(
+ f"kpack is deprecated starting from gfx950 and will be removed in later releases. So for now kpack = {self.kpack} will be overwritten to 1 to make transitioning easier."
+ )
+ object.__setattr__(self, 'kpack', 1)
+
+ default_libdir = Path(__file__).parent / 'lib'
+ extern_libs = {} if self.extern_libs is None else dict(self.extern_libs)
+ for lib in ["ocml", "ockl"]:
+ extern_libs[lib] = str(default_libdir / f'{lib}.bc')
+ object.__setattr__(self, 'extern_libs', tuple(extern_libs.items()))
+
+ def hash(self):
+ key = '_'.join([f'{name}-{val}' for name, val in self.__dict__.items()])
+ return hashlib.sha256(key.encode("utf-8")).hexdigest()
+
+
+class HIPBackend(BaseBackend):
+ instrumentation = None
+ supports_native_tensor_specialization = False
+
+ @staticmethod
+ def supports_target(target: GPUTarget):
+ return target.backend == 'hip'
+
+ def __init__(self, target: GPUTarget) -> None:
+ super().__init__(target)
+ assert isinstance(target.arch, str)
+ self.binary_ext = "hsaco"
+
+ def get_target_name(self, options) -> str:
+ return f"hip:{options.arch}"
+
+ def parse_options(self, opts) -> Any:
+ args = {'arch': knobs.runtime.override_arch or self.target.arch}
+
+ if opts.get("num_ctas", 1) > 1 and not amd.supports_multi_cta_launch(self.target.arch):
+ raise ValueError(f"num_ctas > 1 not supported on {self.target.arch}")
+
+ # Enable XF32 (TF32) for CDNA3 GPUs
+ if self.target.arch == 'gfx942':
+ allowed_dot_input_precisions = set(HIPOptions.allowed_dot_input_precisions)
+ allowed_dot_input_precisions.update({'tf32'})
+ args["allowed_dot_input_precisions"] = tuple(sorted(allowed_dot_input_precisions))
+
+ if "supported_fp8_dtypes" not in opts:
+ args["supported_fp8_dtypes"] = tuple(sorted(HIPOptions.supported_fp8_dtypes))
+
+ if self.target.arch == 'gfx950':
+ deprecated_fp8_dot_operand_dtypes = set(HIPOptions.deprecated_fp8_dot_operand_dtypes)
+ deprecated_fp8_dot_operand_dtypes.update({"fp8e5b16", "fp8e4b8"})
+ args["deprecated_fp8_dot_operand_dtypes"] = tuple(sorted(deprecated_fp8_dot_operand_dtypes))
+
+ if "enable_fp_fusion" not in opts:
+ args["enable_fp_fusion"] = knobs.language.default_fp_fusion
+ args.update({k: opts[k] for k in HIPOptions.__dataclass_fields__.keys() if k in opts and opts[k] is not None})
+ return HIPOptions(**args)
+
+ def pack_metadata(self, metadata):
+ return (
+ metadata.num_warps,
+ metadata.num_ctas,
+ metadata.shared,
+ )
+
+ def get_codegen_implementation(self, options):
+ return {"min_dot_size": get_min_dot_size(self.target)}
+
+ def get_module_map(self) -> Dict[str, ModuleType]:
+ from triton.language.extra.hip import libdevice
+
+ return {"triton.language.extra.libdevice": libdevice}
+
+ def load_dialects(self, ctx):
+ amd.load_dialects(ctx)
+ if HIPBackend.instrumentation:
+ HIPBackend.instrumentation.load_dialects(ctx)
+
+ @staticmethod
+ def is_within_2gb(arg):
+ import torch
+
+ MAX_INT_32 = 2**31 - 1
+ if hasattr(arg, "ptr_range"):
+ return arg.ptr_range() <= MAX_INT_32
+ if isinstance(arg, torch.Tensor) and hasattr(arg, "untyped_storage"):
+ return arg.untyped_storage().size() <= MAX_INT_32
+ return False
+
+ @staticmethod
+ def parse_attr(desc):
+ ret = BaseBackend.parse_attr(desc)
+ if "S" in desc:
+ ret += [["tt.pointer_range", 32]]
+ return ret
+
+ @staticmethod
+ def get_tensor_specialization(arg, **kwargs):
+ ret = BaseBackend.get_tensor_specialization(arg, **kwargs)
+ if knobs.amd.use_buffer_ops and HIPBackend.is_within_2gb(arg):
+ ret += "S"
+ return ret
+
+ @staticmethod
+ def make_ttir(mod, metadata, options):
+ pm = ir.pass_manager(mod.context)
+ pm.enable_debug()
+ passes.common.add_inliner(pm)
+ passes.ttir.add_rewrite_tensor_pointer(pm)
+ passes.ttir.add_rewrite_tensor_descriptor_to_pointer(pm)
+ passes.common.add_canonicalizer(pm)
+ passes.ttir.add_combine(pm)
+ passes.ttir.add_reorder_broadcast(pm)
+ passes.common.add_cse(pm)
+ passes.ttir.add_triton_licm(pm)
+ passes.common.add_symbol_dce(pm)
+ passes.ttir.add_loop_unroll(pm)
+ pm.run(mod, 'make_ttir')
+ return mod
+
+ @staticmethod
+ def make_ttgir(mod, metadata, options):
+ pm = ir.pass_manager(mod.context)
+ pm.enable_debug()
+ passes.ttir.add_convert_to_ttgpuir(pm, f"hip:{options.arch}", options.num_warps, options.warp_size,
+ options.num_ctas)
+ pm.run(mod, 'make_ttgir_early')
+ pm = ir.pass_manager(mod.context)
+ pm.enable_debug()
+ emuTF32 = False
+ passes.ttgpuir.add_coalesce(pm)
+ passes.ttgpuir.add_f32_dot_tc(pm, emuTF32)
+ passes.ttgpuir.add_remove_layout_conversions(pm)
+ passes.ttgpuir.add_optimize_thread_locality(pm)
+ amd.passes.ttgpuir.add_accelerate_matmul(pm, options.arch, options.matrix_instr_nonkdim, options.kpack)
+ passes.ttgpuir.add_remove_layout_conversions(pm)
+ amd.passes.ttgpuir.add_optimize_epilogue(pm)
+ amd.passes.ttgpuir.add_optimize_dot_operands(pm, options.arch)
+ amd.passes.ttgpuir.add_hoist_layout_conversions(pm)
+
+ passes.ttgpuir.add_fuse_nested_loops(pm)
+ passes.common.add_canonicalizer(pm)
+ passes.ttir.add_triton_licm(pm)
+ passes.common.add_canonicalizer(pm)
+
+ use_async_copy = knobs.amd.use_async_copy
+ use_block_pingpong = is_pingpong_schedule_enabled(options.arch, use_async_copy)
+
+ amd.passes.ttgpuir.add_schedule_loops(pm, options.num_stages)
+ amd.passes.ttgpuir.add_pipeline(pm, use_async_copy, use_block_pingpong)
+ if use_async_copy:
+ amd.passes.ttgpuir.add_coalesce_async_copy(pm, options.arch)
+ passes.common.add_canonicalizer(pm)
+ if options.schedule_hint.lower() != "none":
+ for hint in options.schedule_hint.split(","):
+ amd.passes.ttgpuir.insert_instruction_sched_hints(pm, hint)
+ passes.ttgpuir.add_remove_layout_conversions(pm)
+ passes.ttgpuir.add_reduce_data_duplication(pm)
+ if is_in_thread_transpose_enabled(options.arch):
+ amd.passes.ttgpuir.add_in_thread_transpose(pm)
+ passes.ttgpuir.add_remove_layout_conversions(pm)
+ amd.passes.ttgpuir.add_reorder_instructions(pm)
+ if use_block_pingpong and options.num_stages > 1:
+ amd.passes.ttgpuir.add_block_pingpong(pm, options.num_stages)
+
+ if knobs.amd.use_buffer_ops:
+ amd.passes.ttgpuir.add_canonicalize_pointers(pm)
+ passes.common.add_canonicalizer(pm)
+ amd.passes.ttgpuir.add_convert_to_buffer_ops(
+ pm,
+ options.arch,
+ knobs.amd.use_buffer_atomics,
+ knobs.amd.buffer_ops_analyze_small_tensor_range,
+ )
+
+ amd.passes.ttgpuir.add_fold_true_cmpi(pm)
+ passes.common.add_canonicalizer(pm)
+ passes.common.add_cse(pm)
+ passes.common.add_symbol_dce(pm)
+ pm.run(mod, 'make_ttgir')
+ metadata["tensordesc_meta"] = mod.get_tensordesc_metadata()
+ return mod
+
+ @staticmethod
+ def gluon_to_ttgir(src, metadata, options):
+ mod = src
+ pm = ir.pass_manager(mod.context)
+ pm.enable_debug()
+
+ passes.gluon.add_inliner(pm)
+ passes.gluon.add_resolve_auto_encodings(pm)
+ passes.common.add_sccp(pm)
+ passes.ttir.add_loop_aware_cse(pm)
+ passes.gluon.add_canonicalizer(pm)
+ passes.ttgpuir.add_combine_tensor_select_and_if(pm)
+
+ pm.run(mod, 'gluon_to_ttgir')
+ metadata["tensordesc_meta"] = mod.get_tensordesc_metadata()
+ return mod
+
+ @staticmethod
+ def make_llir(src, metadata, options):
+ mod = src
+ # TritonGPU -> LLVM-IR (MLIR)
+ pm = ir.pass_manager(mod.context)
+ pm.enable_debug()
+ amd.passes.ttgpuir.add_update_async_wait_count(pm, options.arch)
+ # custom_lds_size is an experimental parameter that defines amount of LDS available
+ # for one thread block. Measured in bytes.
+ #
+ # If custom_lds_size = 0, pass will consider all LDS is available for one threads block,
+ # LDS size is determined by provided arch name.
+ custom_lds_size = 0
+ amd.passes.ttgpuir.add_optimize_lds_usage(pm, options.arch, custom_lds_size)
+ passes.convert.add_scf_to_cf(pm)
+ passes.gluon.add_inliner(pm)
+ passes.convert.add_index_to_llvmir(pm)
+
+ amd.passes.ttgpuir.add_allocate_shared_memory(pm)
+ # instrumentation point here so we can override IRs above (e.g., ttir and ttgir)
+ if HIPBackend.instrumentation:
+ HIPBackend.instrumentation.patch("ttgpuir_to_llvmir", pm, mod.context)
+ ## __HIP_FTZ is used to control the denorm flushing behavior of exp2 op as follows:
+ ## 1. If __HIP_FTZ = 1, exp2 flushes denorms in input and output regardless
+ ## of the value of kernel arg `allow_flush_denorm`.
+ ## 2. If __HIP_FTZ = 0, whether exp2 flushes denorms in input and output
+ ## depends on the value of kernel arg `allow_flush_denorm`.
+ ## 3. __HIP_FTZ is default to 1 and not exposed as a kernel argument.
+ ## For now it is used as a controller for developers only.
+ __HIP_FTZ = True
+ amd.passes.ttgpuir.add_to_llvmir(pm, options.arch, __HIP_FTZ)
+ passes.common.add_canonicalizer(pm)
+ passes.common.add_cse(pm)
+
+ passes.convert.add_cf_to_llvmir(pm)
+ passes.convert.add_arith_to_llvmir(pm)
+ passes.common.add_canonicalizer(pm)
+ passes.common.add_cse(pm)
+ passes.common.add_symbol_dce(pm)
+
+ if options.schedule_hint.lower() != "none":
+ amd.passes.ttgpuir.lower_instruction_sched_hints(pm, options.arch, options.num_stages)
+
+ # This can not be moved below the di_scope pass
+ if HIPBackend.instrumentation:
+ HIPBackend.instrumentation.patch("llvmir_to_llvm", pm, mod.context)
+
+ if not knobs.compilation.disable_line_info and not knobs.compilation.dump_ir_extract_di_local_variables:
+ passes.llvmir.add_di_scope(pm)
+
+ amd.passes.ttgpuir.add_builtin_func_to_llvmir(pm, __HIP_FTZ)
+ pm.run(mod, 'make_llir')
+
+ if knobs.compilation.dump_ir_extract_di_local_variables:
+ # comments below on why separate it
+ if not knobs.compilation.disable_line_info:
+ pm = ir.pass_manager(mod.context)
+ pm.enable_debug()
+ passes.llvmir.add_di_scope(pm)
+ pm.run(mod, 'make_llir.disable_line_info')
+
+ # insert dbg intrinsic with several DI Attribute including source
+ # var name and type info note: unknown reason for now, but this
+ # pass and add_di_scope has to be run separately, otherwise if we
+ # put them into previous pipline, it trigger a segmentfault without
+ # any error message; could be due to a bug in mlir or pybind11
+ pm = ir.pass_manager(mod.context)
+ pm.enable_debug()
+ passes.llvmir.add_di_local_variable(pm)
+ pm.run(mod, 'make_llir.dump_ir_extract_di_local_variables')
+
+ # LLVM-IR (MLIR) -> LLVM-IR (LLVM)
+ llvm.init_targets()
+ context = llvm.context()
+ llvm_mod = llvm.to_module(mod, context)
+ amd.attach_target_triple(llvm_mod)
+ target_features = ''
+ if knobs.compilation.enable_asan:
+ target_features = '+xnack'
+ llvm.attach_datalayout(llvm_mod, amd.TARGET_TRIPLE, options.arch, target_features)
+
+ # Set various control constants on the LLVM module so that device
+ # libraries can resolve references to them.
+ amd.set_isa_version(llvm_mod, options.arch)
+ amd.set_abi_version(llvm_mod, 500)
+ amd.set_bool_control_constant(llvm_mod, "__oclc_finite_only_opt", False)
+ amd.set_bool_control_constant(llvm_mod, "__oclc_correctly_rounded_sqrt32", True)
+ amd.set_bool_control_constant(llvm_mod, "__oclc_unsafe_math_opt", False)
+ amd.set_bool_control_constant(llvm_mod, "__oclc_wavefrontsize64", options.warp_size == 64)
+
+ # Set kernel attributes first given this may affect later optimizations.
+ fns = [fn for fn in llvm_mod.get_functions() if not fn.is_declaration()]
+ # The public kernel should be kernel 0.
+ fns[0].set_calling_conv(amd.CALLING_CONV_AMDGPU_KERNEL)
+ fns[0].add_fn_attr("amdgpu-flat-work-group-size", f"1,{options.num_warps*options.warp_size}")
+ if "memory-bound-attention" in options.schedule_hint.split(','):
+ fns[0].add_fn_attr("amdgpu-sched-strategy", "iterative-ilp")
+ fns[0].add_fn_attr("uniform-work-group-size", "true")
+ # LLVM AMDGPU backend supports the attribute "amdgpu-waves-per-eu"="[, ]".
+ # This attribute may be attached to a kernel function definition and is an optimization hint.
+ # parameter specifies the requested minimum number of waves per EU, and optional parameter
+ # specifies the requested maximum number of waves per EU (must be >= if specified).
+ # If is omitted, then there is no restriction on the maximum number of waves per EU other than
+ # the one dictated by the hardware for which the kernel is compiled. Passing 0, 0 as ,
+ # implies the default behavior (no limits).
+ # Specifying N, N forces LLVM to focus on a single register count, simplifies some heuristics
+ # and may improve scheduling.
+ fns[0].add_fn_attr("amdgpu-waves-per-eu", f"{options.waves_per_eu}, {options.waves_per_eu}")
+ denormal_mode = "preserve-sign" if options.allow_flush_denorm else "ieee"
+ fns[0].add_fn_attr("denormal-fp-math-f32", denormal_mode)
+ if knobs.compilation.enable_asan:
+ fns[0].add_fn_target_feature("+xnack")
+ fns[0].add_fn_asan_attr()
+
+ # Hint the compiler that we'd like the firmware to set the kernel arguments
+ # to user SGPRs so that the kernel does not need to s_load its arguments
+ # from memory.
+ amd.set_all_fn_arg_inreg(fns[0])
+
+ if knobs.compilation.enable_asan:
+ default_libdir = Path(__file__).parent / 'lib'
+ paths = [
+ str(default_libdir / 'asanrtl.bc'),
+ str(default_libdir / "ocml.bc"),
+ str(default_libdir / "ockl.bc")
+ ]
+ llvm.link_extern_libs(llvm_mod, paths)
+ elif options.extern_libs:
+ paths = [path for (name, path) in options.extern_libs if amd.need_extern_lib(llvm_mod, name)]
+ if len(paths) > 0:
+ llvm.link_extern_libs(llvm_mod, paths)
+
+ llvm.optimize_module(llvm_mod, llvm.OPTIMIZE_O3, options.arch, '', [], options.enable_fp_fusion)
+
+ # Architectures with architected SGPRs store the workgroup id in ttmp9 (X) and ttmp7 (Y[15:0], Z[31:16]).
+ # These attributes are used to determine if Z should be masked out when loading Y. They are inferred during
+ # optimize_module from calls to @llvm.amdgcn.workgroup.id.x/y/z(). We cannot rely on this because a
+ # dispatch dimensions might be used even if there is no program_id() call for it.
+ if amd.has_architected_sgprs(options.arch):
+ fns[0].remove_fn_attr("amdgpu-no-workgroup-id-x")
+ fns[0].remove_fn_attr("amdgpu-no-workgroup-id-y")
+ fns[0].remove_fn_attr("amdgpu-no-workgroup-id-z")
+
+ if knobs.amd.scalarize_packed_fops:
+ amd.add_scalarize_packed_fops_llvm_pass(fns[0])
+
+ # Get some metadata
+ metadata["shared"] = src.get_int_attr("ttg.shared")
+ metadata["profile_scratch_size"] = src.get_int_attr("ttg.profile_scratch_memory_size") or 0
+ metadata["profile_scratch_align"] = src.get_int_attr("ttg.profile_scratch_memory_alignment") or 1
+
+ amd.cleanup_bitcode_metadata(llvm_mod)
+ # Disable inlining of print related functions,
+ # because inlining of these function could slow down compilation significantly
+ amd.disable_print_inline(llvm_mod)
+ return str(llvm_mod)
+
+ @staticmethod
+ def make_amdgcn(src, metadata, options):
+ # Find kernel names (there should only be one)
+ # We get the name at the last possible step to accommodate `triton.compile`
+ # on user-provided LLVM
+ names = re.findall(r"define amdgpu_kernel void @([a-zA-Z_][a-zA-Z0-9_]*)", src)
+ assert len(names) == 1
+ metadata["name"] = names[0]
+ # llvm -> hsaco
+ flags = []
+ features = '-real-true16' if 'gfx11' in options.arch else ''
+ ir_hash = hashlib.sha256(src.encode("utf-8")).hexdigest()
+ dump_file_id = names[0] + '_' + ir_hash
+ _ = llvm.translate_to_mir(src, amd.TARGET_TRIPLE, options.arch, features, flags, options.enable_fp_fusion,
+ dump_file_id)
+ llvm.dump_sched_dag(src, amd.TARGET_TRIPLE, options.arch, features, flags, options.enable_fp_fusion,
+ dump_file_id)
+ amdgcn = llvm.translate_to_asm(src, amd.TARGET_TRIPLE, options.arch, features, flags, options.enable_fp_fusion,
+ False)
+ if knobs.amd.dump_amdgcn:
+ print("// -----// AMDGCN Dump //----- //")
+ print(amdgcn)
+ return amdgcn
+
+ @staticmethod
+ def make_hsaco(src, metadata, options):
+ target_features = ''
+ if knobs.compilation.enable_asan:
+ target_features = '+xnack'
+ hsaco = amd.assemble_amdgcn(src, options.arch, target_features)
+ with tempfile.NamedTemporaryFile() as tmp_out:
+ with tempfile.NamedTemporaryFile() as tmp_in:
+ with open(tmp_in.name, "wb") as fd_in:
+ fd_in.write(hsaco)
+ amd.link_hsaco(tmp_in.name, tmp_out.name)
+ with open(tmp_out.name, "rb") as fd_out:
+ ret = fd_out.read()
+ return ret
+
+ def add_stages(self, stages, options, language):
+ if language == Language.TRITON:
+ stages["ttir"] = lambda src, metadata: self.make_ttir(src, metadata, options)
+ stages["ttgir"] = lambda src, metadata: self.make_ttgir(src, metadata, options)
+ elif language == Language.GLUON:
+ stages["ttgir"] = lambda src, metadata: self.gluon_to_ttgir(src, metadata, options)
+ stages["llir"] = lambda src, metadata: self.make_llir(src, metadata, options)
+ stages["amdgcn"] = lambda src, metadata: self.make_amdgcn(src, metadata, options)
+ stages["hsaco"] = lambda src, metadata: self.make_hsaco(src, metadata, options)
+ if knobs.runtime.add_stages_inspection_hook is not None:
+ knobs.runtime.add_stages_inspection_hook(self, stages, options, language, None)
+
+ @functools.lru_cache()
+ def hash(self):
+ return f'{self.target}'
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/amd/driver.c b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/amd/driver.c
new file mode 100644
index 0000000000000000000000000000000000000000..24178b54c319bb278bf014570128887315d35827
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/amd/driver.c
@@ -0,0 +1,504 @@
+#define __HIP_PLATFORM_AMD__
+#include
+#include
+#define PY_SSIZE_T_CLEAN
+#include
+#include
+#include
+#include
+#include
+
+typedef struct {
+ uint32_t group0_0;
+ uint32_t group0_1;
+ uint32_t group0_2;
+ uint32_t group0_3;
+ uint32_t group1_0;
+ uint32_t group1_1;
+ uint32_t group1_2;
+ uint32_t group1_3;
+ uint32_t group1_4;
+ uint32_t group1_5;
+ uint32_t group1_6;
+ uint32_t group1_7;
+} TDMDescriptor;
+
+typedef struct {
+ PyObject_HEAD;
+ TDMDescriptor desc;
+} PyTDMDescriptorObject;
+
+static PyObject *PyTDMDescriptor_new(PyTypeObject *type, PyObject *args,
+ PyObject *kw) {
+ PyTDMDescriptorObject *self =
+ (PyTDMDescriptorObject *)type->tp_alloc(type, 0);
+ if (!self)
+ return NULL;
+
+ memset(&self->desc, 0, sizeof(self->desc));
+ return (PyObject *)self;
+}
+
+static void PyTDMDescriptor_dealloc(PyTDMDescriptorObject *self) {
+ Py_TYPE(self)->tp_free((PyObject *)self);
+}
+
+static PyTypeObject PyTDMDescriptorType = {
+ PyVarObject_HEAD_INIT(NULL, 0).tp_name =
+ "triton.backends.amd.PyTDMDescriptor",
+ .tp_basicsize = sizeof(PyTDMDescriptorObject),
+ .tp_itemsize = 0,
+ .tp_flags = Py_TPFLAGS_DEFAULT,
+ .tp_doc = "PyObject for TDMDescriptor",
+ .tp_new = PyTDMDescriptor_new,
+ .tp_dealloc = (destructor)PyTDMDescriptor_dealloc,
+};
+
+// TODO: Both host-side and device-side TDM descriptor follow the same encoding
+// format. Consider to add a common utility to remove duplicate code.
+static bool encodeTDMDescriptor(TDMDescriptor *desc, int elementBitWidth,
+ uint32_t *blockSize, int numWarps,
+ int padInterval, int padAmount, uint32_t *shape,
+ uint32_t *strides, uint64_t globalAddress,
+ int rank) {
+ // NYI: TDM > 2D cases
+ if (rank != 2)
+ return false;
+
+ // Get warp distribution
+ uint32_t numWarpsDim0 = numWarps;
+ for (; numWarpsDim0 > blockSize[0]; numWarpsDim0 /= 2)
+ ;
+ uint32_t numWarpsDim1 = numWarps / numWarpsDim0;
+ if (!(numWarpsDim0 > 0 && blockSize[1] % numWarpsDim1 == 0))
+ return false;
+
+ uint32_t blockSize0 = (blockSize[0] + numWarpsDim0 - 1) / numWarpsDim0;
+ uint32_t blockSize1 = (blockSize[1] + numWarpsDim1 - 1) / numWarpsDim1;
+
+ // group0 (128 bits / 4 dwords) effective bit encoding:
+ // [120:64]: global address
+ // [127:126]: type - currently always set to 0x2
+ desc->group0_2 = (uint32_t)(globalAddress & 0xFFFFFFFF);
+ desc->group0_3 = (uint32_t)((globalAddress >> 32) & 0x01FFFFFF);
+ desc->group0_3 |= (0x1 << 31);
+
+ // group1 (256 bits / 8 dwords) effective bit encoding:
+ // [17:16]: data size - log2(element size in bytes)
+ // [20]: enable padding
+ // [24:22]: pad interval - log2(pad interval in dwords) - 1
+ // [31:25]: pad amount - pad amount in dwords - 1
+ // [79:48]: tensor shape dim inner
+ // [111:80]: tensor shape dim outer
+ // [127:112]: block shape dim inner
+ // [143:128]: block shape dim outer
+ // [207:160]: tensor stride dim outer (we only use 32 bits)
+ int elementSizeInBytes = elementBitWidth / 8;
+ int dataSize = log2(elementSizeInBytes);
+ desc->group1_0 = (dataSize << 16);
+ int dwordSize = 32;
+ int padIntervalInDwords = padInterval * elementBitWidth / dwordSize;
+ int padAmountInDwords = padAmount * elementBitWidth / dwordSize;
+ if (padIntervalInDwords > 0 && padAmountInDwords > 0) {
+ int log2PadInterval = log2(padIntervalInDwords);
+ desc->group1_0 |= (1 << 20);
+ desc->group1_0 |= ((log2PadInterval - 1) << 22);
+ desc->group1_0 |= ((padAmountInDwords - 1) << 25);
+ }
+ desc->group1_1 = (shape[1] << 16);
+ desc->group1_2 = (shape[1] >> 16);
+ desc->group1_2 |= (shape[0] << 16);
+ desc->group1_3 = (shape[0] >> 16);
+ desc->group1_3 |= (blockSize1 << 16);
+ desc->group1_4 = (blockSize0 & 0xFFFF);
+ desc->group1_5 = strides[0];
+
+ return true;
+}
+
+// The list of paths to search for the HIP runtime library. The caller Python
+// code should substitute the search path placeholder.
+static const char *hipLibSearchPaths[] = {"/*py_libhip_search_path*/"};
+
+// The list of HIP dynamic library symbols and their signature we are interested
+// in this file.
+// |FOR_EACH_ERR_FN| is a macro to process APIs that return hipError_t;
+// |FOR_EACH_STR_FN| is a macro to process APIs that return const char *.
+#define HIP_SYMBOL_LIST(FOR_EACH_ERR_FN, FOR_EACH_STR_FN) \
+ FOR_EACH_STR_FN(hipGetErrorString, hipError_t hipError) \
+ FOR_EACH_ERR_FN(hipGetDeviceProperties, hipDeviceProp_t *prop, int deviceId) \
+ FOR_EACH_ERR_FN(hipModuleLoadDataEx, hipModule_t *module, const void *image, \
+ unsigned int numOptions, hipJitOption *options, \
+ void **optionValues) \
+ FOR_EACH_ERR_FN(hipModuleGetFunction, hipFunction_t *function, \
+ hipModule_t module, const char *kname) \
+ FOR_EACH_ERR_FN(hipFuncGetAttribute, int *, hipFunction_attribute attr, \
+ hipFunction_t function)
+
+// HIP driver version format: HIP_VERSION_MAJOR * 10000000 + HIP_VERSION_MINOR *
+// 100000 + HIP_VERSION_PATCH.
+#define TRITON_HIP_DRIVER_EXTRACT_MAJOR_VERSION(version) ((version) / 10000000)
+#define TRITON_HIP_DRIVER_EXTRACT_MINOR_VERSION(version) \
+ (((version) % 10000000) / 100000)
+#define TRITON_HIP_DRIVER_EXTRACT_PATCH_VERSION(version) ((version) % 100000)
+#define TRITON_HIP_DRIVER_REQ_MAJOR_VERSION (6)
+
+// #define TRITON_HIP_DRIVER_DBG_VERSION
+#ifdef TRITON_HIP_DRIVER_DBG_VERSION
+#define TRITON_HIP_DRIVER_LOG_VERSION(version, msgBuff) \
+ do { \
+ snprintf(msgBuff, sizeof(msgBuff), "libamdhip64 version is: %d.%d.%d", \
+ TRITON_HIP_DRIVER_EXTRACT_MAJOR_VERSION(version), \
+ TRITON_HIP_DRIVER_EXTRACT_MINOR_VERSION(version), \
+ TRITON_HIP_DRIVER_EXTRACT_PATCH_VERSION(version)); \
+ printf("%s\n", msgBuff); \
+ } while (0);
+#else
+#define TRITON_HIP_DRIVER_LOG_VERSION(version, msgBuff) \
+ do { \
+ (void)msgBuff; \
+ (void)(version); \
+ } while (0);
+#endif
+
+#define TRITON_HIP_MSG_BUFF_SIZE (1024U)
+
+// The HIP symbol table for holding resolved dynamic library symbols.
+struct HIPSymbolTable {
+#define DEFINE_EACH_ERR_FIELD(hipSymbolName, ...) \
+ hipError_t (*hipSymbolName)(__VA_ARGS__);
+#define DEFINE_EACH_STR_FIELD(hipSymbolName, ...) \
+ const char *(*hipSymbolName)(__VA_ARGS__);
+
+ HIP_SYMBOL_LIST(DEFINE_EACH_ERR_FIELD, DEFINE_EACH_STR_FIELD)
+};
+
+static struct HIPSymbolTable hipSymbolTable;
+
+static int checkDriverVersion(void *lib) {
+ int hipVersion = -1;
+ const char *error = NULL;
+ typedef hipError_t (*hipDriverGetVersion_fn)(int *driverVersion);
+ hipDriverGetVersion_fn hipDriverGetVersion;
+ dlerror(); // Clear existing errors
+ hipDriverGetVersion =
+ (hipDriverGetVersion_fn)dlsym(lib, "hipDriverGetVersion");
+ error = dlerror();
+ if (error) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "cannot query 'hipDriverGetVersion' from libamdhip64.so");
+ dlclose(lib);
+ return -1;
+ }
+
+ (void)hipDriverGetVersion(&hipVersion);
+ char msgBuff[TRITON_HIP_MSG_BUFF_SIZE] = {0};
+
+ const int hipMajVersion = TRITON_HIP_DRIVER_EXTRACT_MAJOR_VERSION(hipVersion);
+ if (hipMajVersion < TRITON_HIP_DRIVER_REQ_MAJOR_VERSION) {
+ const int hipMinVersion =
+ TRITON_HIP_DRIVER_EXTRACT_MINOR_VERSION(hipVersion);
+ const int hipPatchVersion =
+ TRITON_HIP_DRIVER_EXTRACT_PATCH_VERSION(hipVersion);
+ snprintf(msgBuff, sizeof(msgBuff),
+ "libamdhip64 version %d.%d.%d is not supported! Required major "
+ "version is >=%d.",
+ hipMajVersion, hipMinVersion, hipPatchVersion,
+ TRITON_HIP_DRIVER_REQ_MAJOR_VERSION);
+ PyErr_SetString(PyExc_RuntimeError, msgBuff);
+ dlclose(lib);
+ return -1;
+ }
+
+ TRITON_HIP_DRIVER_LOG_VERSION(hipVersion, msgBuff);
+
+ return hipVersion;
+}
+
+bool initSymbolTable() {
+ void *lib;
+
+ // Go through the list of search paths to dlopen the first HIP driver library.
+ int n = sizeof(hipLibSearchPaths) / sizeof(hipLibSearchPaths[0]);
+ for (int i = 0; i < n; ++i) {
+ void *handle = dlopen(hipLibSearchPaths[i], RTLD_LAZY | RTLD_LOCAL);
+ if (handle) {
+ lib = handle;
+ // printf("[triton] chosen %s\n", hipLibSearchPaths[i]);
+ }
+ }
+
+ if (!lib) {
+ PyErr_SetString(PyExc_RuntimeError, "cannot open libamdhip64.so");
+ return false;
+ }
+
+ int hipVersion = checkDriverVersion(lib);
+ if (hipVersion == -1)
+ return false;
+
+ const char *error = NULL;
+ typedef hipError_t (*hipGetProcAddress_fn)(
+ const char *symbol, void **pfn, int hipVersion, uint64_t hipFlags,
+ hipDriverProcAddressQueryResult *symbolStatus);
+ hipGetProcAddress_fn hipGetProcAddress;
+ dlerror(); // Clear existing errors
+
+ *(void **)&hipGetProcAddress = dlsym(lib, "hipGetProcAddress");
+ error = dlerror();
+ if (error) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "cannot query 'hipGetProcAddress' from libamdhip64.so");
+ dlclose(lib);
+ return false;
+ }
+
+ // Resolve all symbols we are interested in.
+ uint64_t hipFlags = 0;
+ hipDriverProcAddressQueryResult symbolStatus;
+ hipError_t status = hipSuccess;
+#define QUERY_EACH_FN(hipSymbolName, ...) \
+ status = hipGetProcAddress(#hipSymbolName, \
+ (void **)&hipSymbolTable.hipSymbolName, \
+ hipVersion, hipFlags, &symbolStatus); \
+ if (status != hipSuccess) { \
+ PyErr_SetString(PyExc_RuntimeError, \
+ "cannot get address for '" #hipSymbolName \
+ "' from libamdhip64.so"); \
+ dlclose(lib); \
+ return false; \
+ }
+
+ HIP_SYMBOL_LIST(QUERY_EACH_FN, QUERY_EACH_FN)
+
+ return true;
+}
+
+static inline void gpuAssert(hipError_t code, const char *file, int line) {
+ {
+ if (code != HIP_SUCCESS) {
+ {
+ const char *prefix = "Triton Error [HIP]: ";
+ const char *str = hipSymbolTable.hipGetErrorString(code);
+ char err[TRITON_HIP_MSG_BUFF_SIZE] = {0};
+ snprintf(err, sizeof(err), "%s Code: %d, Messsage: %s", prefix, code,
+ str);
+ PyGILState_STATE gil_state;
+ gil_state = PyGILState_Ensure();
+ PyErr_SetString(PyExc_RuntimeError, err);
+ PyGILState_Release(gil_state);
+ }
+ }
+ }
+}
+
+#define HIP_CHECK(ans) \
+ { \
+ gpuAssert((ans), __FILE__, __LINE__); \
+ if (PyErr_Occurred()) \
+ return NULL; \
+ }
+
+static PyObject *getDeviceProperties(PyObject *self, PyObject *args) {
+ int device_id;
+ if (!PyArg_ParseTuple(args, "i", &device_id))
+ return NULL;
+
+ hipDeviceProp_t props;
+ HIP_CHECK(hipSymbolTable.hipGetDeviceProperties(&props, device_id));
+
+ // create a struct to hold device properties
+ return Py_BuildValue(
+ "{s:i, s:i, s:i, s:i, s:i, s:i, s:s, s:i, s:i}", "max_shared_mem",
+ props.sharedMemPerBlock, "max_num_regs", props.regsPerBlock,
+ "multiprocessor_count", props.multiProcessorCount, "sm_clock_rate",
+ props.clockRate, "mem_clock_rate", props.memoryClockRate, "mem_bus_width",
+ props.memoryBusWidth, "arch", props.gcnArchName, "warpSize",
+ props.warpSize, "max_threads_per_sm", props.maxThreadsPerMultiProcessor);
+}
+
+static PyObject *loadBinary(PyObject *self, PyObject *args) {
+ const char *name;
+ const char *data;
+ Py_ssize_t data_size;
+ int shared;
+ int device;
+ if (!PyArg_ParseTuple(args, "ss#ii", &name, &data, &data_size, &shared,
+ &device)) {
+ return NULL;
+ }
+
+ // set HIP options
+ hipJitOption opt[] = {hipJitOptionErrorLogBufferSizeBytes,
+ hipJitOptionErrorLogBuffer,
+ hipJitOptionInfoLogBufferSizeBytes,
+ hipJitOptionInfoLogBuffer, hipJitOptionLogVerbose};
+ const unsigned int errbufsize = 8192;
+ const unsigned int logbufsize = 8192;
+ char _err[errbufsize];
+ char _log[logbufsize];
+ void *optval[] = {(void *)(uintptr_t)errbufsize, (void *)_err,
+ (void *)(uintptr_t)logbufsize, (void *)_log, (void *)1};
+
+ // launch HIP Binary
+ hipModule_t mod;
+ hipFunction_t fun;
+ HIP_CHECK(hipSymbolTable.hipModuleLoadDataEx(&mod, data, 5, opt, optval))
+ HIP_CHECK(hipSymbolTable.hipModuleGetFunction(&fun, mod, name));
+
+ // get allocated registers and spilled registers from the function
+ int n_regs = 0;
+ int n_spills = 0;
+ int32_t n_max_threads = 0;
+ hipSymbolTable.hipFuncGetAttribute(&n_regs, HIP_FUNC_ATTRIBUTE_NUM_REGS, fun);
+ hipSymbolTable.hipFuncGetAttribute(&n_spills,
+ HIP_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES, fun);
+ hipSymbolTable.hipFuncGetAttribute(
+ &n_max_threads, HIP_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, fun);
+ n_spills /= 4;
+ if (PyErr_Occurred()) {
+ return NULL;
+ }
+ return Py_BuildValue("(KKiii)", (uint64_t)mod, (uint64_t)fun, n_regs,
+ n_spills, n_max_threads);
+}
+
+static PyObject *createTDMDescriptor(PyObject *self, PyObject *args) {
+ int elementBitWidth;
+ PyObject *blockSize;
+ int numWarps;
+ int padInterval;
+ int padAmount;
+ PyObject *shape;
+ PyObject *strides;
+ unsigned long long globalAddress;
+
+ if (!PyArg_ParseTuple(args, "iOiiiOOK", &elementBitWidth, &blockSize,
+ &numWarps, &padInterval, &padAmount, &shape, &strides,
+ &globalAddress)) {
+ return NULL;
+ }
+
+ PyTDMDescriptorObject *descObj = (PyTDMDescriptorObject *)PyObject_CallObject(
+ (PyObject *)&PyTDMDescriptorType, NULL);
+ if (!descObj)
+ return NULL;
+
+ PyObject *blockSizeFast = NULL;
+ PyObject *shapeFast = NULL;
+ PyObject *stridesFast = NULL;
+
+ uint32_t blockSizeInt[2];
+ uint32_t shapeInt[2];
+ uint32_t stridesInt[2];
+
+ blockSizeFast = PySequence_Fast(blockSize, "blockSize must be a sequence");
+ if (!blockSizeFast)
+ goto cleanup;
+ int rank = PySequence_Fast_GET_SIZE(blockSizeFast);
+ if (rank != 2) {
+ PyErr_SetString(PyExc_RuntimeError, "rank must be 2");
+ goto cleanup;
+ }
+
+ for (int i = 0; i < rank; ++i) {
+ PyObject *item = PySequence_Fast_GET_ITEM(blockSizeFast, i);
+ if (!PyLong_Check(item)) {
+ PyErr_SetString(PyExc_TypeError, "block size must be an int");
+ goto cleanup;
+ }
+ blockSizeInt[i] = PyLong_AsLong(item);
+ }
+
+ shapeFast = PySequence_Fast(shape, "shape must be a sequence");
+ if (!shapeFast)
+ goto cleanup;
+
+ if (rank != PySequence_Fast_GET_SIZE(shapeFast)) {
+ PyErr_SetString(PyExc_RuntimeError, "rank mismatch");
+ goto cleanup;
+ }
+ for (int i = 0; i < rank; ++i) {
+ PyObject *item = PySequence_Fast_GET_ITEM(shapeFast, i);
+ if (!PyLong_Check(item)) {
+ PyErr_SetString(PyExc_TypeError, "shape must be an int");
+ goto cleanup;
+ }
+ shapeInt[i] = PyLong_AsLong(item);
+ }
+
+ stridesFast = PySequence_Fast(strides, "strides must be a sequence");
+ if (!stridesFast)
+ goto cleanup;
+
+ if (rank != PySequence_Fast_GET_SIZE(stridesFast)) {
+ PyErr_SetString(PyExc_RuntimeError, "rank mismatch");
+ goto cleanup;
+ }
+ for (int i = 0; i < rank; ++i) {
+ PyObject *item = PySequence_Fast_GET_ITEM(stridesFast, i);
+ if (!PyLong_Check(item)) {
+ PyErr_SetString(PyExc_TypeError, "shape must be an int");
+ goto cleanup;
+ }
+ stridesInt[i] = PyLong_AsLong(item);
+ }
+
+ Py_DECREF(blockSizeFast);
+ blockSizeFast = NULL;
+ Py_DECREF(shapeFast);
+ shapeFast = NULL;
+ Py_DECREF(stridesFast);
+ stridesFast = NULL;
+
+ bool success = encodeTDMDescriptor(
+ &descObj->desc, elementBitWidth, blockSizeInt, numWarps, padInterval,
+ padAmount, shapeInt, stridesInt, globalAddress, rank);
+ if (!success) {
+ PyErr_SetString(PyExc_RuntimeError, "Failed to encode TDM descriptor");
+ goto cleanup;
+ }
+
+ return (PyObject *)descObj;
+
+cleanup:
+ Py_XDECREF(blockSizeFast);
+ Py_XDECREF(shapeFast);
+ Py_XDECREF(stridesFast);
+ Py_XDECREF(descObj);
+ return NULL;
+}
+
+static PyMethodDef ModuleMethods[] = {
+ {"load_binary", loadBinary, METH_VARARGS,
+ "Load provided hsaco into HIP driver"},
+ {"get_device_properties", getDeviceProperties, METH_VARARGS,
+ "Get the properties for a given device"},
+ {"create_tdm_descriptor", createTDMDescriptor, METH_VARARGS,
+ "create a host-side TDM descriptor"},
+ {NULL, NULL, 0, NULL} // sentinel
+};
+
+static struct PyModuleDef ModuleDef = {PyModuleDef_HEAD_INIT, "hip_utils",
+ NULL, // documentation
+ -1, // size
+ ModuleMethods};
+
+PyMODINIT_FUNC PyInit_hip_utils(void) {
+ if (!initSymbolTable()) {
+ return NULL;
+ }
+
+ PyObject *m = PyModule_Create(&ModuleDef);
+ if (m == NULL) {
+ return NULL;
+ }
+ PyModule_AddFunctions(m, ModuleMethods);
+
+ if (PyType_Ready(&PyTDMDescriptorType) < 0)
+ return NULL;
+ Py_INCREF(&PyTDMDescriptorType);
+ PyModule_AddObject(m, "PyTDMDescriptor", (PyObject *)&PyTDMDescriptorType);
+
+ return m;
+}
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/amd/driver.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/amd/driver.py
new file mode 100644
index 0000000000000000000000000000000000000000..24a0d84e8ab646c37f86fb5d3d462bd41c5a75ba
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/amd/driver.py
@@ -0,0 +1,877 @@
+import functools
+import os
+import subprocess
+import re
+import triton
+from pathlib import Path
+from triton import knobs
+from triton.backends.compiler import GPUTarget
+from triton.backends.driver import GPUDriver
+from triton.runtime import _allocation
+from triton.runtime.build import compile_module_from_src
+
+dirname = os.path.dirname(os.path.realpath(__file__))
+include_dirs = [os.path.join(dirname, "include")]
+PyTDMDescriptor = None
+
+
+def _find_already_mmapped_dylib_on_linux(lib_name):
+ import platform
+ if platform.system() != 'Linux':
+ return None
+
+ # Use dl_iterate_phdr to walk through the list of shared libraries at runtime.
+ # See https://www.man7.org/linux/man-pages/man3/dl_iterate_phdr.3.html for details.
+
+ import ctypes
+ from ctypes import c_char, c_int, c_size_t, c_void_p, c_char_p, POINTER
+
+ class DlPhdrInfo(ctypes.Structure):
+ _fields_ = [
+ ('dlpi_addr', c_void_p),
+ ('dlpi_name', c_char_p),
+ # We don't care about the remaining fields.
+ ]
+
+ # callback_t must use POINTER(c_char) to avoid copying.
+ callback_t = ctypes.CFUNCTYPE(c_int, POINTER(DlPhdrInfo), POINTER(c_size_t), POINTER(c_char))
+
+ # Load libc and get the dl_iterate_phdr symbol.
+ try:
+ dl_iterate_phdr = ctypes.CDLL('libc.so.6').dl_iterate_phdr
+ except Exception:
+ return None
+ # argtypes must use c_char_p to accept create_string_buffer.
+ dl_iterate_phdr.argtypes = [callback_t, c_char_p]
+ dl_iterate_phdr.restype = c_int
+
+ max_path_length = 4096
+ path = ctypes.create_string_buffer(max_path_length + 1)
+
+ # Define callback to get the loaded dylib path.
+ def callback(info, size, data):
+ dlpi_name = info.contents.dlpi_name
+ p = Path(os.fsdecode(dlpi_name))
+ if lib_name in p.name:
+ # Found the dylib; get its path.
+ ctypes.memmove(data, dlpi_name, min(max_path_length, len(dlpi_name)))
+ return 1
+ return 0
+
+ if dl_iterate_phdr(callback_t(callback), path):
+ return os.fsdecode(ctypes.string_at(path))
+ return None
+
+
+@functools.lru_cache()
+def _get_path_to_hip_runtime_dylib():
+ lib_name = "libamdhip64.so"
+
+ # If we are told explicitly what HIP runtime dynamic library to use, obey that.
+ if env_libhip_path := knobs.amd.libhip_path:
+ if env_libhip_path.endswith(lib_name) and os.path.exists(env_libhip_path):
+ return env_libhip_path
+ raise RuntimeError(f"TRITON_LIBHIP_PATH '{env_libhip_path}' does not point to a valid {lib_name}")
+
+ # If the shared object is already mmapped to address space, use it.
+ mmapped_path = _find_already_mmapped_dylib_on_linux(lib_name)
+ if mmapped_path:
+ if os.path.exists(mmapped_path):
+ return mmapped_path
+ raise RuntimeError(f"memory mapped '{mmapped_path}' in process does not point to a valid {lib_name}")
+
+ paths = []
+
+ # Check backend
+ local_lib = os.path.join(os.path.dirname(__file__), "lib", lib_name)
+ if os.path.exists(local_lib):
+ return local_lib
+ paths.append(local_lib)
+
+ import site
+ # First search the HIP runtime dynamic library packaged with PyTorch. It's very likely
+ # that we run Triton together with PyTorch. This makes sure we use the same dynamic
+ # library to avoid version mismatch.
+ site_packages = site.getsitepackages()
+ user_site = site.getusersitepackages()
+ if site.ENABLE_USER_SITE: # ENABLE_USER_SITE is initialized in getusersitepackages()
+ site_packages = [user_site] + site_packages
+ for path in site_packages:
+ path = os.path.join(path, "torch", "lib", lib_name)
+ if os.path.exists(path):
+ return path
+ paths.append(path)
+
+ # Then try to see if developer provides a HIP runtime dynamic library using LD_LIBARAY_PATH.
+ env_ld_library_path = os.getenv("LD_LIBRARY_PATH")
+ if env_ld_library_path:
+ for d in env_ld_library_path.split(":"):
+ f = os.path.join(d, lib_name)
+ if os.path.exists(f):
+ return f
+ paths.append(f)
+
+ # HIP_PATH should point to HIP SDK root if set
+ env_hip_path = os.getenv("HIP_PATH")
+ if env_hip_path:
+ hip_lib_path = os.path.join(env_hip_path, "lib", lib_name)
+ if os.path.exists(hip_lib_path):
+ return hip_lib_path
+ paths.append(hip_lib_path)
+
+ # if available, `hipconfig --path` prints the HIP SDK root
+ try:
+ hip_root = subprocess.check_output(["hipconfig", "--path"]).decode().strip()
+ if hip_root:
+ hip_lib_path = os.path.join(hip_root, "lib", lib_name)
+ if os.path.exists(hip_lib_path):
+ return hip_lib_path
+ paths.append(hip_lib_path)
+ except (subprocess.CalledProcessError, FileNotFoundError):
+ # hipconfig may not be available
+ pass
+
+ # ROCm lib dir based on env var
+ env_rocm_path = os.getenv("ROCM_PATH")
+ if env_rocm_path:
+ rocm_lib_path = os.path.join(env_rocm_path, "lib", lib_name)
+ if os.path.exists(rocm_lib_path):
+ return rocm_lib_path
+ paths.append(rocm_lib_path)
+
+ # Afterwards try to search the loader dynamic library resolution paths.
+ libs = subprocess.check_output(["/sbin/ldconfig", "-p"]).decode(errors="ignore")
+ # each line looks like the following:
+ # libamdhip64.so.6 (libc6,x86-64) => /opt/rocm-6.0.2/lib/libamdhip64.so.6
+ # libamdhip64.so (libc6,x86-64) => /opt/rocm-6.0.2/lib/libamdhip64.so
+ locs = [line.split()[-1] for line in libs.splitlines() if line.strip().endswith(lib_name)]
+ for loc in locs:
+ if os.path.exists(loc):
+ return loc
+ paths.append(loc)
+
+ # As a last resort, guess if we have it in some common installation path.
+ common_install_path = os.path.join('/opt/rocm/lib/', lib_name)
+ if os.path.exists(common_install_path):
+ return common_install_path
+ paths.append(common_install_path)
+
+ raise RuntimeError(f"cannot locate {lib_name} after attempted paths {paths}")
+
+
+class HIPUtils(object):
+
+ def __new__(cls):
+ if not hasattr(cls, "instance"):
+ cls.instance = super(HIPUtils, cls).__new__(cls)
+ return cls.instance
+
+ def __init__(self):
+ libhip_path = _get_path_to_hip_runtime_dylib()
+ src = Path(os.path.join(dirname, "driver.c")).read_text()
+ # Just do a simple search and replace here instead of templates or format strings.
+ # This way we don't need to escape-quote C code curly brackets and we can replace
+ # exactly once.
+ src = src.replace('/*py_libhip_search_path*/', libhip_path, 1)
+ mod = compile_module_from_src(src=src, name="hip_utils", include_dirs=include_dirs)
+ self.load_binary = mod.load_binary
+ self.get_device_properties = mod.get_device_properties
+ self.create_tdm_descriptor = mod.create_tdm_descriptor
+ global PyTDMDescriptor
+ PyTDMDescriptor = mod.PyTDMDescriptor
+
+
+# -------------------- Launcher ----------------------------
+def ty_to_cpp(ty):
+ if ty.startswith('*'):
+ return "hipDeviceptr_t"
+ if ty == "tensordesc":
+ return "TDMDescriptor"
+ return {
+ "i1": "int8_t",
+ "i8": "int8_t",
+ "i16": "int16_t",
+ "i32": "int32_t",
+ "i64": "int64_t",
+ "u1": "uint8_t",
+ "u8": "uint8_t",
+ "u16": "uint16_t",
+ "u32": "uint32_t",
+ "u64": "uint64_t",
+ "fp16": "double",
+ "bf16": "double",
+ "fp32": "double",
+ "f32": "double",
+ "fp64": "double",
+ }[ty]
+
+
+FLOAT_STORAGE_TYPE = {
+ "fp16": "uint16_t",
+ "bf16": "uint16_t",
+ "fp32": "uint32_t",
+ "f32": "uint32_t",
+ "fp64": "uint64_t",
+}
+FLOAT_PACK_FUNCTION = {
+ "fp16": "pack_fp16",
+ "bf16": "pack_bf16",
+ "fp32": "pack_fp32",
+ "f32": "pack_fp32",
+ "fp64": "pack_fp64",
+}
+
+_BASE_ARGS_FORMAT = "piiiKKOOOOO"
+
+
+def make_launcher(constants, signature, warp_size, tensordesc_meta):
+
+ def _expand_signature(signature):
+ output = []
+ tensordesc_idx = 0
+ for sig in signature:
+ if isinstance(sig, str) and sig.startswith("tensordesc"):
+ meta = tensordesc_meta[tensordesc_idx] if tensordesc_meta else None
+ tensordesc_idx += 1
+
+ match = re.match("tensordesc<([^[>]*)\\[([^]]*)\\]", sig)
+ dtype = match.group(1)
+ shape = match.group(2)
+ ndim = shape.count(",") + 1
+
+ # If there is no descriptor's metadata, the descriptor has been decomposed to base pointer, shape and strides
+ if meta is None:
+ output.append("*" + dtype)
+ for _ in range(2 * ndim):
+ output.append("i64")
+ output.append("i1")
+ else:
+ output.append("tensordesc")
+
+ for _ in range(ndim):
+ output.append("i32")
+ for _ in range(ndim):
+ output.append("i64")
+ else:
+ output.append(sig)
+
+ return output
+
+ def _serialize_signature(sig):
+ if isinstance(sig, tuple):
+ return ','.join(map(_serialize_signature, sig))
+ return sig
+
+ def _extracted_type(ty):
+ if isinstance(ty, tuple):
+ val = ','.join(map(_extracted_type, ty))
+ return f"[{val}]"
+ if ty.startswith("*") or ty.startswith("tensordesc"):
+ return "PyObject*"
+ if ty == "constexpr":
+ return "PyObject*"
+ return ty_to_cpp(ty)
+
+ def format_of(ty):
+ if isinstance(ty, tuple):
+ val = ''.join(map(format_of, ty))
+ return f"({val})"
+ if ty.startswith("*") or ty.startswith("tensordesc"):
+ return "O"
+ if ty == "constexpr":
+ return "O"
+ return {
+ "double": "d",
+ "long": "l",
+ "int8_t": "b",
+ "int16_t": "h",
+ "int32_t": "i",
+ "int64_t": "L",
+ "uint8_t": "B",
+ "uint16_t": "H",
+ "uint32_t": "I",
+ "uint64_t": "K",
+ }[ty_to_cpp(ty)]
+
+ signature = {idx: s for idx, s in enumerate(_expand_signature(signature.values()))}
+
+ args_format = ''.join([format_of(ty) for ty in signature.values()])
+ format = _BASE_ARGS_FORMAT + args_format
+ signature = ','.join(map(_serialize_signature, signature.values()))
+ signature = list(filter(bool, signature.split(',')))
+ signature = {i: s for i, s in enumerate(signature)}
+ args_list = ', ' + ', '.join(f"&_arg{i}" for i, ty in signature.items()) if len(signature) > 0 else ''
+ # Record the end of regular arguments;
+ # subsequent arguments are architecture-specific descriptors, such as tensor descriptors for CUDA.
+ arg_decl_list = []
+ for i, ty in signature.items():
+ if ty == "constexpr":
+ continue
+ if ty in FLOAT_STORAGE_TYPE:
+ arg_decl_list.append(f"{FLOAT_STORAGE_TYPE[ty]} arg{i}")
+ else:
+ arg_decl_list.append(f"{ty_to_cpp(ty)} arg{i}")
+ arg_decls = ', '.join(arg_decl_list)
+ internal_args_list = []
+ for i, ty in signature.items():
+ if ty.startswith("*"):
+ internal_args_list.append(f"ptr_info{i}.dev_ptr")
+ elif ty.startswith("tensordesc"):
+ internal_args_list.append(f"*desc{i}")
+ elif ty in FLOAT_STORAGE_TYPE:
+ internal_args_list.append(f"_arg{i}_storage")
+ elif ty != "constexpr":
+ internal_args_list.append(f"_arg{i}")
+
+ newline = '\n '
+ ptr_decls = [
+ f"DevicePtrInfo ptr_info{i} = getPointer(_arg{i}, {i}); if (!ptr_info{i}.valid) return NULL;"
+ for i, ty in signature.items()
+ if ty.startswith("*")
+ ]
+ tensor_desc_decls = [
+ f"TDMDescriptor* desc{i} = getTDMDescriptor(_arg{i}, {i});" for i, ty in signature.items()
+ if ty.startswith("tensordesc")
+ ]
+ float_storage_decls = [
+ f"{FLOAT_STORAGE_TYPE[ty]} _arg{i}_storage = {FLOAT_PACK_FUNCTION[ty]}(_arg{i});"
+ for i, ty in signature.items()
+ if ty in FLOAT_STORAGE_TYPE
+ ]
+
+ libhip_path = _get_path_to_hip_runtime_dylib()
+
+ # generate glue code
+ params = list(range(len(signature)))
+ params = [f"&arg{i}" for i, ty in signature.items() if ty != "constexpr"]
+ params.append("&global_scratch")
+ params.append("&profile_scratch")
+ src = f"""
+#define __HIP_PLATFORM_AMD__
+#include
+#include
+#include
+#include
+#include
+#include
+
+typedef struct {{
+ uint32_t group0_0;
+ uint32_t group0_1;
+ uint32_t group0_2;
+ uint32_t group0_3;
+ uint32_t group1_0;
+ uint32_t group1_1;
+ uint32_t group1_2;
+ uint32_t group1_3;
+ uint32_t group1_4;
+ uint32_t group1_5;
+ uint32_t group1_6;
+ uint32_t group1_7;
+}} TDMDescriptor;
+
+typedef struct {{
+ PyObject_HEAD;
+ TDMDescriptor desc;
+}} PyTDMDescriptorObject;
+
+// The list of paths to search for the HIP runtime library. The caller Python
+// code should substitute the search path placeholder.
+static const char *hipLibSearchPaths[] = {{"{libhip_path}"}};
+
+// The list of HIP dynamic library symbols and their signature we are interested
+// in this file.
+#define HIP_SYMBOL_LIST(FOR_EACH_ERR_FN, FOR_EACH_STR_FN) \\
+ FOR_EACH_STR_FN(hipGetLastError, true) \\
+ FOR_EACH_STR_FN(hipGetErrorString, true, hipError_t hipError) \\
+ FOR_EACH_ERR_FN(hipDrvLaunchKernelEx, false, \\
+ const HIP_LAUNCH_CONFIG *config, \\
+ hipFunction_t f, \\
+ void **kernelParams, \\
+ void **extra) \\
+ FOR_EACH_ERR_FN(hipModuleLaunchKernel, true, hipFunction_t f, \\
+ unsigned int gridDimX, unsigned int gridDimY, \\
+ unsigned int gridDimZ, unsigned int blockDimX, \\
+ unsigned int blockDimY, unsigned int blockDimZ, \\
+ unsigned int sharedMemBytes, hipStream_t stream, \\
+ void **kernelParams, void **extra) \\
+ FOR_EACH_ERR_FN(hipModuleLaunchCooperativeKernel, true, hipFunction_t f, \\
+ unsigned int gridDimX, unsigned int gridDimY, \\
+ unsigned int gridDimZ, unsigned int blockDimX, \\
+ unsigned int blockDimY, unsigned int blockDimZ, \\
+ unsigned int sharedMemBytes, hipStream_t stream, \\
+ void **kernelParams, void **extra) \\
+ FOR_EACH_ERR_FN(hipPointerGetAttribute, true, void *data, \\
+ hipPointer_attribute attribute, hipDeviceptr_t ptr)
+
+// The HIP symbol table for holding resolved dynamic library symbols.
+struct HIPSymbolTable {{
+#define DEFINE_EACH_ERR_FIELD(hipSymbolName, required, ...) \\
+ hipError_t (*hipSymbolName)(__VA_ARGS__);
+#define DEFINE_EACH_STR_FIELD(hipSymbolName, required, ...) \\
+ const char *(*hipSymbolName)(__VA_ARGS__);
+
+ HIP_SYMBOL_LIST(DEFINE_EACH_ERR_FIELD, DEFINE_EACH_STR_FIELD)
+}};
+
+static struct HIPSymbolTable hipSymbolTable;
+
+bool initSymbolTable() {{
+ // Use the HIP runtime library loaded into the existing process if it exits.
+ void *lib = dlopen("libamdhip64.so", RTLD_NOLOAD);
+
+ // Otherwise, go through the list of search paths to dlopen the first HIP
+ // driver library.
+ if (!lib) {{
+ int n = sizeof(hipLibSearchPaths) / sizeof(hipLibSearchPaths[0]);
+ for (int i = 0; i < n; ++i) {{
+ void *handle = dlopen(hipLibSearchPaths[i], RTLD_LAZY | RTLD_LOCAL);
+ if (handle) {{
+ lib = handle;
+ }}
+ }}
+ }}
+ if (!lib) {{
+ PyErr_SetString(PyExc_RuntimeError, "cannot open libamdhip64.so");
+ return false;
+ }}
+
+ typedef hipError_t (*hipGetProcAddress_fn)(
+ const char *symbol, void **pfn, int hipVersion, uint64_t hipFlags,
+ hipDriverProcAddressQueryResult *symbolStatus);
+ hipGetProcAddress_fn hipGetProcAddress;
+ dlerror(); // Clear existing errors
+ const char *error = NULL;
+ *(void **)&hipGetProcAddress = dlsym(lib, "hipGetProcAddress");
+ error = dlerror();
+ if (error) {{
+ PyErr_SetString(PyExc_RuntimeError,
+ "cannot query 'hipGetProcAddress' from libamdhip64.so");
+ dlclose(lib);
+ return false;
+ }}
+
+ // Resolve all symbols we are interested in.
+ int hipVersion = HIP_VERSION;
+ uint64_t hipFlags = 0;
+ hipDriverProcAddressQueryResult symbolStatus;
+ hipError_t status = hipSuccess;
+#define QUERY_EACH_FN(hipSymbolName, required, ...) \
+ status = hipGetProcAddress(#hipSymbolName, \
+ (void **)&hipSymbolTable.hipSymbolName, \
+ hipVersion, hipFlags, &symbolStatus); \
+ if (required && status != hipSuccess) {{ \
+ PyErr_SetString(PyExc_RuntimeError, \
+ "cannot get address for '" #hipSymbolName \
+ "' from libamdhip64.so"); \
+ dlclose(lib); \
+ return false; \
+ }}
+
+ HIP_SYMBOL_LIST(QUERY_EACH_FN, QUERY_EACH_FN)
+
+ return true;
+}}
+
+static inline void gpuAssert(hipError_t code, const char *file, int line)
+{{
+ if (code != HIP_SUCCESS)
+ {{
+ const char* prefix = "Triton Error [HIP]: ";
+ const char* str = hipSymbolTable.hipGetErrorString(code);
+ char err[1024] = {{0}};
+ snprintf(err, 1024, "%s Code: %d, Messsage: %s", prefix, code, str );
+ PyErr_SetString(PyExc_RuntimeError, err);
+ }}
+}}
+
+#define HIP_CHECK(ans) {{ gpuAssert((ans), __FILE__, __LINE__); }}
+
+static void _launch(int gridX, int gridY, int gridZ, int num_warps, int num_ctas, int launch_cooperative_grid, int shared_memory, hipStream_t stream, hipFunction_t function, hipDeviceptr_t profile_scratch{', ' + arg_decls if len(arg_decls) > 0 else ''}) {{
+ if (gridX * gridY * gridZ == 0)
+ return;
+ hipDeviceptr_t global_scratch = 0;
+ void *params[] = {{ {', '.join(params)} }};
+ if(num_ctas > 1) {{
+ if (!hipSymbolTable.hipDrvLaunchKernelEx) {{
+ PyErr_SetString(PyExc_RuntimeError, "missing hipDrvLaunchKernelEx symbol; please update HIP runtime");
+ return;
+ }}
+
+ hipLaunchAttribute attributes[2];
+ // Attribute0: Cluster dimensions
+ attributes[0].id = 4;
+ int *cluster_dims = (int*)attributes[0].val.pad;
+ cluster_dims[0] = num_ctas;
+ cluster_dims[1] = 1;
+ cluster_dims[2] = 1;
+ // Attribute1: Cooperative launch
+ attributes[1].id = hipLaunchAttributeCooperative;
+ attributes[1].val.cooperative = launch_cooperative_grid;
+
+ HIP_LAUNCH_CONFIG config = {{
+ gridX * num_ctas, gridY, gridZ, // Grid size
+ {warp_size} * num_warps, 1, 1, // Block size
+ shared_memory, stream,
+ attributes, 2 // Number of attributes
+ }};
+ HIP_CHECK(hipSymbolTable.hipDrvLaunchKernelEx(&config, function, params, 0));
+ return;
+ }}
+ else if (launch_cooperative_grid) {{
+ HIP_CHECK(hipSymbolTable.hipModuleLaunchCooperativeKernel(function, gridX, gridY, gridZ, {warp_size}*num_warps, 1, 1, shared_memory, stream, params, 0));
+ return;
+ }}
+ else {{
+ HIP_CHECK(hipSymbolTable.hipModuleLaunchKernel(function, gridX, gridY, gridZ, {warp_size}*num_warps, 1, 1, shared_memory, stream, params, 0));
+ }}
+}}
+
+typedef struct _DevicePtrInfo {{
+ hipDeviceptr_t dev_ptr;
+ bool valid;
+}} DevicePtrInfo;
+
+static PyObject* data_ptr_str = NULL;
+static PyObject* py_tdm_descriptor_type = NULL;
+
+static inline DevicePtrInfo getPointer(PyObject *obj, int idx) {{
+ DevicePtrInfo ptr_info;
+ hipError_t status = hipSuccess;
+ ptr_info.dev_ptr = 0;
+ ptr_info.valid = true;
+ if (PyLong_Check(obj)) {{
+ ptr_info.dev_ptr = (hipDeviceptr_t)PyLong_AsUnsignedLongLong(obj);
+ return ptr_info;
+ }}
+ if (obj == Py_None) {{
+ // valid nullptr
+ return ptr_info;
+ }}
+ PyObject *ret = PyObject_CallMethodNoArgs(obj, data_ptr_str);
+ if (!ret) {{
+ PyErr_SetString(PyExc_TypeError, "Pointer argument must be either uint64 or have data_ptr method");
+ ptr_info.valid = false;
+ goto cleanup;
+ }}
+ if (!PyLong_Check(ret)) {{
+ PyErr_SetString(PyExc_TypeError, "data_ptr method of Pointer object must return 64-bit int");
+ ptr_info.valid = false;
+ goto cleanup;
+ }}
+ ptr_info.dev_ptr = (hipDeviceptr_t)PyLong_AsUnsignedLongLong(ret);
+ if (!ptr_info.dev_ptr)
+ goto cleanup;
+ uint64_t dev_ptr;
+ status = hipSymbolTable.hipPointerGetAttribute(&dev_ptr, HIP_POINTER_ATTRIBUTE_DEVICE_POINTER, ptr_info.dev_ptr);
+ if (status == hipErrorInvalidValue) {{
+ PyErr_Format(PyExc_ValueError,
+ "Pointer argument (at %d) cannot be accessed from Triton (cpu tensor?)", idx);
+ ptr_info.valid = false;
+ // Clear and ignore HIP error
+ (void)hipSymbolTable.hipGetLastError();
+ }}
+ ptr_info.dev_ptr = (hipDeviceptr_t)dev_ptr;
+cleanup:
+ Py_DECREF(ret);
+ return ptr_info;
+}}
+
+static inline TDMDescriptor* getTDMDescriptor(PyObject* obj, int idx) {{
+ if (Py_TYPE(obj) != (PyTypeObject*)py_tdm_descriptor_type) {{
+ PyErr_Format(PyExc_TypeError, "object must be of type PyTDMDescriptor, got %s", Py_TYPE(obj)->tp_name);
+ return NULL;
+ }}
+
+ TDMDescriptor* desc = &((PyTDMDescriptorObject*)obj)->desc;
+ return desc;
+}}
+
+static uint16_t pack_fp16(double f) {{
+ uint16_t result;
+ // from https://github.com/python/pythoncapi-compat/blob/5e317108f872c904eb726cb8d560dcadbdf88a72/pythoncapi_compat.h#L482-L492
+#if 0x030600B1 <= PY_VERSION_HEX && PY_VERSION_HEX <= 0x030B00A1 && !defined(PYPY_VERSION)
+ _PyFloat_Pack2(f, (unsigned char*)&result, 1);
+#else
+ PyFloat_Pack2(f, (char*)&result, 1);
+#endif
+ return result;
+}}
+
+static uint16_t pack_bf16(double f) {{
+ float f32 = (float)f;
+ uint32_t u32 = *(uint32_t*)&f32;
+ return (uint16_t)(u32 >> 16);
+}}
+
+static uint32_t pack_fp32(double f) {{
+ float f32 = (float)f;
+ return *(uint32_t*)&f32;
+}}
+
+static uint64_t pack_fp64(double f) {{
+ return *(uint64_t*)&f;
+}}
+
+static PyObject* launch(PyObject* self, PyObject* args) {{
+ int gridX, gridY, gridZ;
+ uint64_t _stream;
+ uint64_t _function;
+ int launch_cooperative_grid;
+ PyObject *profile_scratch_obj = NULL;
+ PyObject *launch_enter_hook = NULL;
+ PyObject *launch_exit_hook = NULL;
+ PyObject *kernel_metadata = NULL;
+ PyObject *launch_metadata = NULL;
+ {' '.join([f"{_extracted_type(ty)} _arg{i}; " for i, ty in signature.items()])}
+ if(!PyArg_ParseTuple(args, \"{format}\", &launch_cooperative_grid,
+ &gridX, &gridY, &gridZ, &_stream, &_function, &profile_scratch_obj,
+ &kernel_metadata, &launch_metadata,
+ &launch_enter_hook, &launch_exit_hook {args_list})) {{
+ return NULL;
+ }}
+
+ // extract kernel metadata
+ int num_warps, num_ctas, shared_memory;
+ if (!PyArg_ParseTuple(kernel_metadata, \"iii\", &num_warps, &num_ctas, &shared_memory)) {{
+ return NULL;
+ }}
+ // extract launch metadata
+ if (launch_enter_hook != Py_None){{
+ PyObject* ret = PyObject_CallOneArg(launch_enter_hook, launch_metadata);
+ if (!ret)
+ return NULL;
+ Py_DECREF(ret);
+ }}
+
+ hipDeviceptr_t profile_scratch = 0;
+ if (profile_scratch_obj != Py_None) {{
+ DevicePtrInfo profile_scratch_info = getPointer(profile_scratch_obj, -1);
+ if (!profile_scratch_info.valid) {{
+ return NULL;
+ }}
+ profile_scratch = profile_scratch_info.dev_ptr;
+ }}
+
+ // raise exception asap
+ {newline.join(tensor_desc_decls)}
+ {newline.join(ptr_decls)}
+ {newline.join(float_storage_decls)}
+ _launch(gridX, gridY, gridZ, num_warps, num_ctas, launch_cooperative_grid, shared_memory, (hipStream_t)_stream, (hipFunction_t)_function, (hipDeviceptr_t)profile_scratch{', ' + ', '.join(internal_args_list) if len(internal_args_list) > 0 else ''});
+
+ if(launch_exit_hook != Py_None){{
+ PyObject* ret = PyObject_CallOneArg(launch_exit_hook, launch_metadata);
+ if (!ret)
+ return NULL;
+ Py_DECREF(ret);
+ }}
+
+ if(PyErr_Occurred()) {{
+ return NULL;
+ }}
+ Py_RETURN_NONE;
+}}
+
+static PyMethodDef ModuleMethods[] = {{
+ {{"launch", launch, METH_VARARGS, "Entry point for all kernels with this signature"}},
+ {{NULL, NULL, 0, NULL}} // sentinel
+}};
+
+static struct PyModuleDef ModuleDef = {{
+ PyModuleDef_HEAD_INIT,
+ \"__triton_launcher\",
+ NULL, //documentation
+ -1, //size
+ ModuleMethods
+}};
+
+PyMODINIT_FUNC PyInit___triton_launcher(void) {{
+ if (!initSymbolTable()) {{
+ return NULL;
+ }}
+ PyObject *m = PyModule_Create(&ModuleDef);
+ if(m == NULL) {{
+ return NULL;
+ }}
+ data_ptr_str = PyUnicode_InternFromString("data_ptr");
+ if(data_ptr_str == NULL) {{
+ return NULL;
+ }}
+ PyObject* driver_mod = PyImport_ImportModule("triton.backends.amd.driver");
+ if (driver_mod == NULL) {{
+ return NULL;
+ }}
+ py_tdm_descriptor_type = PyObject_GetAttrString(driver_mod, "PyTDMDescriptor");
+ if (py_tdm_descriptor_type == NULL) {{
+ return NULL;
+ }}
+
+ PyModule_AddFunctions(m, ModuleMethods);
+ return m;
+}}
+"""
+ return src
+
+
+def make_tensordesc_arg(arg, kernel_metadata, tensordesc_metadata):
+ """
+ Translate a tensor descriptor argument into the appropriate list of kernel
+ arguments. If `tensordesc_metadata` is provided, we will create a
+ TDMDescriptor object. Otherwise, we decompose the tensor descriptor into
+ base pointer, shape, strides, and padding flag. In both cases, we append the
+ shape and strides at the end to match the expected kernel signature.
+ """
+
+ if tensordesc_metadata is None:
+ # Currently the host side tensor descriptors get decomposed in
+ # the frontend to tensor desc, shape, and strides. We have no
+ # way to use these shape and strides when processing tensor
+ # descriptors which is why we provide our own decomposition
+ # above. Sadly this means we have to pass the shape and strides
+ # twice.
+ return [arg.base, *arg.shape, *arg.strides, arg.padding == "nan", *arg.shape, *arg.strides]
+
+ shape = arg.shape
+ strides = arg.strides
+ base = arg.base.data_ptr()
+
+ assert "elem_bits" in tensordesc_metadata and "block_size" in tensordesc_metadata
+ elem_bits = tensordesc_metadata["elem_bits"]
+ block_size = tensordesc_metadata["block_size"]
+ pad_interval, pad_amount = 0, 0
+ interval_padding_pairs = tensordesc_metadata.get("interval_padding_pairs", [])
+ if interval_padding_pairs:
+ assert len(interval_padding_pairs) == 1 and len(interval_padding_pairs[0]) == 2
+ pad_interval, pad_amount = interval_padding_pairs[0]
+ num_warps = kernel_metadata[0]
+
+ driver = triton.runtime.driver.active
+ assert isinstance(driver, HIPDriver)
+
+ desc = driver.utils.create_tdm_descriptor(elem_bits, block_size, num_warps, pad_interval, pad_amount, shape,
+ strides, base)
+
+ return [desc, *shape, *strides]
+
+
+def wrap_handle_tensordesc(launcher, signature, tensordesc_metadata):
+ """
+ Wrap a kernel launcher function to handle tensor descriptor arguments.
+ Use the provided `tensordesc_metadata` to determine whether to create
+ TDMDescriptor objects or decompose the tensor descriptors.
+
+ Args:
+ launcher (callable): The original kernel launcher function.
+ signature (Dict[int, str]): The kernel signature mapping argument indices to types.
+ tensordesc_metadata (List[Dict] or None): The list of tensor descriptor metadata, following the order
+ of tensor descriptor arguments. If None, decompose tensor descriptors.
+ Returns:
+ launcher (callable): The wrapped kernel launcher function.
+ """
+
+ has_tensor_desc_arg = any(isinstance(sig, str) and sig.startswith("tensordesc") for sig in signature.values())
+ if not has_tensor_desc_arg:
+ return launcher
+
+ tensordesc_indices = set(
+ [i for i, sig in enumerate(signature.values()) if isinstance(sig, str) and sig.startswith("tensordesc")])
+ assert not tensordesc_metadata or len(tensordesc_metadata) == len(tensordesc_indices)
+ if not tensordesc_metadata:
+ tensordesc_metadata = [None] * len(tensordesc_indices)
+
+ def inner(*args):
+ meta_args = args[:len(_BASE_ARGS_FORMAT)]
+ raw_kernel_args = args[len(_BASE_ARGS_FORMAT):]
+ final_args = []
+ tensordesc_idx = 0
+ for i, arg in enumerate(raw_kernel_args):
+ if i in tensordesc_indices:
+ tensordesc_args = make_tensordesc_arg(arg, meta_args[7], # kernel_metadata
+ tensordesc_metadata[tensordesc_idx])
+ final_args.extend(tensordesc_args)
+ tensordesc_idx += 1
+ else:
+ final_args.append(arg)
+ return launcher(*meta_args, *final_args)
+
+ return inner
+
+
+class HIPLauncher(object):
+
+ def __init__(self, src, metadata):
+ constants = src.constants if hasattr(src, "constants") else dict()
+ arg_idx = lambda x: (src.fn.arg_names.index(x), ) if isinstance(x, str) else x
+ constants = {arg_idx(idx): value for idx, value in constants.items()}
+ signature = {idx: value for idx, value in src.signature.items()}
+ tensordesc_meta = getattr(metadata, "tensordesc_meta", None)
+ src = make_launcher(constants, signature, metadata.warp_size, tensordesc_meta)
+ mod = compile_module_from_src(src=src, name="__triton_launcher", include_dirs=include_dirs)
+ self.launch = wrap_handle_tensordesc(mod.launch, signature, tensordesc_meta)
+ self.launch_cooperative_grid = metadata.launch_cooperative_grid
+ self.profile_scratch_size = metadata.profile_scratch_size
+ self.profile_scratch_align = metadata.profile_scratch_align
+
+ def __call__(self, gridX, gridY, gridZ, stream, function, *args):
+
+ def allocate_scratch(size, align, allocator):
+ if size > 0:
+ grid_size = gridX * gridY * gridZ
+ alloc_size = grid_size * size
+ alloc_fn = allocator.get()
+ return alloc_fn(alloc_size, align, stream)
+ return None
+
+ profile_scratch = allocate_scratch(self.profile_scratch_size, self.profile_scratch_align,
+ _allocation._profile_allocator)
+
+ self.launch(self.launch_cooperative_grid, gridX, gridY, gridZ, stream, function, profile_scratch, *args)
+
+
+class HIPDriver(GPUDriver):
+
+ def __init__(self):
+ super().__init__()
+ self.utils = HIPUtils()
+ self.launcher_cls = HIPLauncher
+
+ def get_device_interface(self):
+ import torch
+ return torch.cuda
+
+ @staticmethod
+ def is_active():
+ try:
+ import torch
+ return torch.cuda.is_available() and (torch.version.hip is not None)
+ except ImportError:
+ return False
+
+ def map_python_to_cpp_type(self, ty: str) -> str:
+ return ty_to_cpp(ty)
+
+ def get_current_target(self):
+ device = self.get_current_device()
+ device_properties = self.utils.get_device_properties(device)
+ arch = knobs.runtime.override_arch or device_properties['arch']
+ warp_size = device_properties['warpSize']
+ return GPUTarget("hip", arch.split(':')[0], warp_size)
+
+ def get_active_torch_device(self):
+ import torch
+ # when using hip devices, the device string in pytorch is "cuda"
+ return torch.device("cuda", self.get_current_device())
+
+ def get_benchmarker(self):
+ from triton.testing import do_bench
+ return do_bench
+
+ def get_empty_cache_for_benchmark(self):
+ import torch
+
+ # It's the same as the Nvidia backend.
+ cache_size = 256 * 1024 * 1024
+ return torch.empty(int(cache_size // 4), dtype=torch.int, device='cuda')
+
+ def clear_cache(self, cache):
+ cache.zero_()
diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_channel_descriptor.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_channel_descriptor.h
new file mode 100644
index 0000000000000000000000000000000000000000..26d03abfb44ee564d22da3df1d94f4a4df57782d
--- /dev/null
+++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_channel_descriptor.h
@@ -0,0 +1,311 @@
+/*
+Copyright (c) 2015 - 2023 Advanced Micro Devices, Inc. All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+#ifndef HIP_INCLUDE_HIP_AMD_DETAIL_CHANNEL_DESCRIPTOR_H
+#define HIP_INCLUDE_HIP_AMD_DETAIL_CHANNEL_DESCRIPTOR_H
+
+#if !defined(__HIPCC_RTC__)
+#include
+#include
+#include
+#endif
+
+#ifdef __cplusplus
+
+extern "C" HIP_PUBLIC_API hipChannelFormatDesc hipCreateChannelDesc(int x, int y, int z, int w,
+ hipChannelFormatKind f);
+
+static inline hipChannelFormatDesc hipCreateChannelDescHalf() {
+ int e = (int)sizeof(unsigned short) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindFloat);
+}
+
+static inline hipChannelFormatDesc hipCreateChannelDescHalf1() {
+ int e = (int)sizeof(unsigned short) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindFloat);
+}
+
+static inline hipChannelFormatDesc hipCreateChannelDescHalf2() {
+ int e = (int)sizeof(unsigned short) * 8;
+ return hipCreateChannelDesc(e, e, 0, 0, hipChannelFormatKindFloat);
+}
+
+static inline hipChannelFormatDesc hipCreateChannelDescHalf4() {
+ int e = (int)sizeof(unsigned short) * 8;
+ return hipCreateChannelDesc(e, e, e, e, hipChannelFormatKindFloat);
+}
+
+template static inline hipChannelFormatDesc hipCreateChannelDesc() {
+ return hipCreateChannelDesc(0, 0, 0, 0, hipChannelFormatKindNone);
+}
+
+template <> inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(char) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindSigned);
+}
+
+template <> inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed char) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindSigned);
+}
+
+template <> inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned char) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindUnsigned);
+}
+
+template <> inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned char) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindUnsigned);
+}
+
+template <> inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed char) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindSigned);
+}
+
+template <> inline hipChannelFormatDesc hipCreateChannelDesc