`."
+ ) 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 requests.HTTPError:
+ # Any authentication/authorization error will be caught here => default to cache
+ return has_file_in_cache
+
+
+class PushToHubMixin:
+ """
+ A Mixin containing the functionality to push a model or tokenizer to the hub.
+ """
+
+ def _create_repo(
+ self,
+ repo_id: str,
+ private: Optional[bool] = None,
+ token: Optional[Union[bool, str]] = None,
+ repo_url: Optional[str] = None,
+ organization: Optional[str] = None,
+ ) -> str:
+ """
+ Create the repo if needed, cleans up repo_id with deprecated kwargs `repo_url` and `organization`, retrieves
+ the token.
+ """
+ if repo_url is not None:
+ warnings.warn(
+ "The `repo_url` argument is deprecated and will be removed in v5 of Transformers. Use `repo_id` "
+ "instead."
+ )
+ if repo_id is not None:
+ raise ValueError(
+ "`repo_id` and `repo_url` are both specified. Please set only the argument `repo_id`."
+ )
+ repo_id = repo_url.replace(f"{HUGGINGFACE_CO_RESOLVE_ENDPOINT}/", "")
+ if organization is not None:
+ warnings.warn(
+ "The `organization` argument is deprecated and will be removed in v5 of Transformers. Set your "
+ "organization directly in the `repo_id` passed instead (`repo_id={organization}/{model_id}`)."
+ )
+ if not repo_id.startswith(organization):
+ if "/" in repo_id:
+ repo_id = repo_id.split("/")[-1]
+ repo_id = f"{organization}/{repo_id}"
+
+ url = create_repo(repo_id=repo_id, token=token, private=private, exist_ok=True)
+ return url.repo_id
+
+ def _get_files_timestamps(self, working_dir: Union[str, os.PathLike]):
+ """
+ Returns the list of files with their last modification timestamp.
+ """
+ return {f: os.path.getmtime(os.path.join(working_dir, f)) for f in os.listdir(working_dir)}
+
+ def _upload_modified_files(
+ self,
+ working_dir: Union[str, os.PathLike],
+ repo_id: str,
+ files_timestamps: dict[str, float],
+ commit_message: Optional[str] = None,
+ token: Optional[Union[bool, str]] = None,
+ create_pr: bool = False,
+ revision: Optional[str] = None,
+ commit_description: Optional[str] = None,
+ ):
+ """
+ Uploads all modified files in `working_dir` to `repo_id`, based on `files_timestamps`.
+ """
+ if commit_message is None:
+ if "Model" in self.__class__.__name__:
+ commit_message = "Upload model"
+ elif "Config" in self.__class__.__name__:
+ commit_message = "Upload config"
+ elif "Tokenizer" in self.__class__.__name__:
+ commit_message = "Upload tokenizer"
+ elif "FeatureExtractor" in self.__class__.__name__:
+ commit_message = "Upload feature extractor"
+ elif "Processor" in self.__class__.__name__:
+ commit_message = "Upload processor"
+ else:
+ commit_message = f"Upload {self.__class__.__name__}"
+ modified_files = [
+ f
+ for f in os.listdir(working_dir)
+ if f not in files_timestamps or os.path.getmtime(os.path.join(working_dir, f)) > files_timestamps[f]
+ ]
+
+ # filter for actual files + folders at the root level
+ modified_files = [
+ f
+ for f in modified_files
+ if os.path.isfile(os.path.join(working_dir, f)) or os.path.isdir(os.path.join(working_dir, f))
+ ]
+
+ operations = []
+ # upload standalone files
+ for file in modified_files:
+ if os.path.isdir(os.path.join(working_dir, file)):
+ # go over individual files of folder
+ for f in os.listdir(os.path.join(working_dir, file)):
+ operations.append(
+ CommitOperationAdd(
+ path_or_fileobj=os.path.join(working_dir, file, f), path_in_repo=os.path.join(file, f)
+ )
+ )
+ else:
+ operations.append(
+ CommitOperationAdd(path_or_fileobj=os.path.join(working_dir, file), path_in_repo=file)
+ )
+
+ if revision is not None and not revision.startswith("refs/pr"):
+ try:
+ create_branch(repo_id=repo_id, branch=revision, token=token, exist_ok=True)
+ except HfHubHTTPError as e:
+ if e.response.status_code == 403 and create_pr:
+ # If we are creating a PR on a repo we don't have access to, we can't create the branch.
+ # so let's assume the branch already exists. If it's not the case, an error will be raised when
+ # calling `create_commit` below.
+ pass
+ else:
+ raise
+
+ logger.info(f"Uploading the following files to {repo_id}: {','.join(modified_files)}")
+ return create_commit(
+ repo_id=repo_id,
+ operations=operations,
+ commit_message=commit_message,
+ commit_description=commit_description,
+ token=token,
+ create_pr=create_pr,
+ revision=revision,
+ )
+
+ def push_to_hub(
+ self,
+ repo_id: str,
+ use_temp_dir: Optional[bool] = None,
+ commit_message: Optional[str] = None,
+ private: Optional[bool] = None,
+ token: Optional[Union[bool, str]] = None,
+ max_shard_size: Optional[Union[int, str]] = "5GB",
+ create_pr: bool = False,
+ safe_serialization: bool = True,
+ revision: Optional[str] = None,
+ commit_description: Optional[str] = None,
+ tags: Optional[list[str]] = None,
+ **deprecated_kwargs,
+ ) -> str:
+ """
+ Upload the {object_files} to the 🤗 Model Hub.
+
+ Parameters:
+ repo_id (`str`):
+ The name of the repository you want to push your {object} to. It should contain your organization name
+ when pushing to a given organization.
+ use_temp_dir (`bool`, *optional*):
+ Whether or not to use a temporary directory to store the files saved before they are pushed to the Hub.
+ Will default to `True` if there is no directory named like `repo_id`, `False` otherwise.
+ commit_message (`str`, *optional*):
+ Message to commit while pushing. Will default to `"Upload {object}"`.
+ private (`bool`, *optional*):
+ Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
+ token (`bool` or `str`, *optional*):
+ The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
+ when running `hf auth login` (stored in `~/.huggingface`). Will default to `True` if `repo_url`
+ is not specified.
+ max_shard_size (`int` or `str`, *optional*, defaults to `"5GB"`):
+ Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard
+ will then be each of size lower than this size. If expressed as a string, needs to be digits followed
+ by a unit (like `"5MB"`). We default it to `"5GB"` so that users can easily load models on free-tier
+ Google Colab instances without any CPU OOM issues.
+ create_pr (`bool`, *optional*, defaults to `False`):
+ Whether or not to create a PR with the uploaded files or directly commit.
+ safe_serialization (`bool`, *optional*, defaults to `True`):
+ Whether or not to convert the model weights in safetensors format for safer serialization.
+ revision (`str`, *optional*):
+ Branch to push the uploaded files to.
+ commit_description (`str`, *optional*):
+ The description of the commit that will be created
+ tags (`list[str]`, *optional*):
+ List of tags to push on the Hub.
+
+ Examples:
+
+ ```python
+ from transformers import {object_class}
+
+ {object} = {object_class}.from_pretrained("google-bert/bert-base-cased")
+
+ # Push the {object} to your namespace with the name "my-finetuned-bert".
+ {object}.push_to_hub("my-finetuned-bert")
+
+ # Push the {object} to an organization with the name "my-finetuned-bert".
+ {object}.push_to_hub("huggingface/my-finetuned-bert")
+ ```
+ """
+ use_auth_token = deprecated_kwargs.pop("use_auth_token", None)
+ ignore_metadata_errors = deprecated_kwargs.pop("ignore_metadata_errors", False)
+ save_jinja_files = deprecated_kwargs.pop(
+ "save_jinja_files", None
+ ) # TODO: This is only used for testing and should be removed once save_jinja_files becomes the default
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
+ FutureWarning,
+ )
+ if token is not None:
+ raise ValueError(
+ "`token` and `use_auth_token` are both specified. Please set only the argument `token`."
+ )
+ token = use_auth_token
+
+ repo_path_or_name = deprecated_kwargs.pop("repo_path_or_name", None)
+ if repo_path_or_name is not None:
+ # Should use `repo_id` instead of `repo_path_or_name`. When using `repo_path_or_name`, we try to infer
+ # repo_id from the folder path, if it exists.
+ warnings.warn(
+ "The `repo_path_or_name` argument is deprecated and will be removed in v5 of Transformers. Use "
+ "`repo_id` instead.",
+ FutureWarning,
+ )
+ if repo_id is not None:
+ raise ValueError(
+ "`repo_id` and `repo_path_or_name` are both specified. Please set only the argument `repo_id`."
+ )
+ if os.path.isdir(repo_path_or_name):
+ # repo_path: infer repo_id from the path
+ repo_id = repo_path_or_name.split(os.path.sep)[-1]
+ working_dir = repo_id
+ else:
+ # repo_name: use it as repo_id
+ repo_id = repo_path_or_name
+ working_dir = repo_id.split("/")[-1]
+ else:
+ # Repo_id is passed correctly: infer working_dir from it
+ working_dir = repo_id.split("/")[-1]
+
+ # Deprecation warning will be sent after for repo_url and organization
+ repo_url = deprecated_kwargs.pop("repo_url", None)
+ organization = deprecated_kwargs.pop("organization", None)
+
+ repo_id = self._create_repo(
+ repo_id, private=private, token=token, repo_url=repo_url, organization=organization
+ )
+
+ # Create a new empty model card and eventually tag it
+ model_card = create_and_tag_model_card(
+ repo_id, tags, token=token, ignore_metadata_errors=ignore_metadata_errors
+ )
+
+ if use_temp_dir is None:
+ use_temp_dir = not os.path.isdir(working_dir)
+
+ with working_or_temp_dir(working_dir=working_dir, use_temp_dir=use_temp_dir) as work_dir:
+ files_timestamps = self._get_files_timestamps(work_dir)
+
+ # Save all files.
+ if save_jinja_files:
+ self.save_pretrained(
+ work_dir,
+ max_shard_size=max_shard_size,
+ safe_serialization=safe_serialization,
+ save_jinja_files=True,
+ )
+ else:
+ self.save_pretrained(work_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)
+
+ # Update model card if needed:
+ model_card.save(os.path.join(work_dir, "README.md"))
+
+ return self._upload_modified_files(
+ work_dir,
+ repo_id,
+ files_timestamps,
+ commit_message=commit_message,
+ token=token,
+ create_pr=create_pr,
+ revision=revision,
+ commit_description=commit_description,
+ )
+
+
+def send_example_telemetry(example_name, *example_args, framework="pytorch"):
+ """
+ Sends telemetry that helps tracking the examples use.
+
+ Args:
+ example_name (`str`): The name of the example.
+ *example_args (dataclasses or `argparse.ArgumentParser`): The arguments to the script. This function will only
+ try to extract the model and dataset name from those. Nothing else is tracked.
+ framework (`str`, *optional*, defaults to `"pytorch"`): The framework for the example.
+ """
+ if is_offline_mode():
+ return
+
+ data = {"example": example_name, "framework": framework}
+ for args in example_args:
+ args_as_dict = {k: v for k, v in args.__dict__.items() if not k.startswith("_") and v is not None}
+ if "model_name_or_path" in args_as_dict:
+ model_name = args_as_dict["model_name_or_path"]
+ # Filter out local paths
+ if not os.path.isdir(model_name):
+ data["model_name"] = args_as_dict["model_name_or_path"]
+ if "dataset_name" in args_as_dict:
+ data["dataset_name"] = args_as_dict["dataset_name"]
+ elif "task_name" in args_as_dict:
+ # Extract script name from the example_name
+ script_name = example_name.replace("tf_", "").replace("flax_", "").replace("run_", "")
+ script_name = script_name.replace("_no_trainer", "")
+ data["dataset_name"] = f"{script_name}-{args_as_dict['task_name']}"
+
+ # Send telemetry in the background
+ send_telemetry(
+ topic="examples", library_name="transformers", library_version=__version__, user_agent=http_user_agent(data)
+ )
+
+
+def convert_file_size_to_int(size: Union[int, str]):
+ """
+ Converts a size expressed as a string with digits an unit (like `"5MB"`) to an integer (in bytes).
+
+ Args:
+ size (`int` or `str`): The size to convert. Will be directly returned if an `int`.
+
+ Example:
+ ```py
+ >>> convert_file_size_to_int("1MiB")
+ 1048576
+ ```
+ """
+ if isinstance(size, int):
+ return size
+ if size.upper().endswith("GIB"):
+ return int(size[:-3]) * (2**30)
+ if size.upper().endswith("MIB"):
+ return int(size[:-3]) * (2**20)
+ if size.upper().endswith("KIB"):
+ return int(size[:-3]) * (2**10)
+ if size.upper().endswith("GB"):
+ int_size = int(size[:-2]) * (10**9)
+ return int_size // 8 if size.endswith("b") else int_size
+ if size.upper().endswith("MB"):
+ int_size = int(size[:-2]) * (10**6)
+ return int_size // 8 if size.endswith("b") else int_size
+ if size.upper().endswith("KB"):
+ int_size = int(size[:-2]) * (10**3)
+ return int_size // 8 if size.endswith("b") else int_size
+ raise ValueError("`size` is not in a valid format. Use an integer followed by the unit, e.g., '5GB'.")
+
+
+def get_checkpoint_shard_files(
+ pretrained_model_name_or_path,
+ index_filename,
+ cache_dir=None,
+ force_download=False,
+ proxies=None,
+ resume_download=None,
+ local_files_only=False,
+ token=None,
+ user_agent=None,
+ revision=None,
+ subfolder="",
+ _commit_hash=None,
+ **deprecated_kwargs,
+):
+ """
+ For a given model:
+
+ - download and cache all the shards of a sharded checkpoint if `pretrained_model_name_or_path` is a model ID on the
+ Hub
+ - returns the list of paths to all the shards, as well as some metadata.
+
+ For the description of each arg, see [`PreTrainedModel.from_pretrained`]. `index_filename` is the full path to the
+ index (downloaded and cached if `pretrained_model_name_or_path` is a model ID on the Hub).
+ """
+ import json
+
+ use_auth_token = deprecated_kwargs.pop("use_auth_token", None)
+ if use_auth_token is not None:
+ warnings.warn(
+ "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
+ FutureWarning,
+ )
+ if token is not None:
+ raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
+ token = use_auth_token
+
+ if not os.path.isfile(index_filename):
+ raise ValueError(f"Can't find a checkpoint index ({index_filename}) in {pretrained_model_name_or_path}.")
+
+ with open(index_filename) as f:
+ index = json.loads(f.read())
+
+ shard_filenames = sorted(set(index["weight_map"].values()))
+ sharded_metadata = index["metadata"]
+ sharded_metadata["all_checkpoint_keys"] = list(index["weight_map"].keys())
+ sharded_metadata["weight_map"] = index["weight_map"].copy()
+
+ # First, let's deal with local folder.
+ if os.path.isdir(pretrained_model_name_or_path):
+ shard_filenames = [os.path.join(pretrained_model_name_or_path, subfolder, f) for f in shard_filenames]
+ return shard_filenames, sharded_metadata
+
+ # At this stage pretrained_model_name_or_path is a model identifier on the Hub. Try to get everything from cache,
+ # or download the files
+ cached_filenames = cached_files(
+ pretrained_model_name_or_path,
+ shard_filenames,
+ cache_dir=cache_dir,
+ force_download=force_download,
+ proxies=proxies,
+ resume_download=resume_download,
+ local_files_only=local_files_only,
+ token=token,
+ user_agent=user_agent,
+ revision=revision,
+ subfolder=subfolder,
+ _commit_hash=_commit_hash,
+ )
+
+ return cached_filenames, sharded_metadata
+
+
+def create_and_tag_model_card(
+ repo_id: str,
+ tags: Optional[list[str]] = None,
+ token: Optional[str] = None,
+ ignore_metadata_errors: bool = False,
+):
+ """
+ Creates or loads an existing model card and tags it.
+
+ Args:
+ repo_id (`str`):
+ The repo_id where to look for the model card.
+ tags (`list[str]`, *optional*):
+ The list of tags to add in the model card
+ token (`str`, *optional*):
+ Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to the stored token.
+ ignore_metadata_errors (`bool`, *optional*, defaults to `False`):
+ If True, errors while parsing the metadata section will be ignored. Some information might be lost during
+ the process. Use it at your own risk.
+ """
+ try:
+ # Check if the model card is present on the remote repo
+ model_card = ModelCard.load(repo_id, token=token, ignore_metadata_errors=ignore_metadata_errors)
+ except EntryNotFoundError:
+ # Otherwise create a simple model card from template
+ model_description = "This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated."
+ card_data = ModelCardData(tags=[] if tags is None else tags, library_name="transformers")
+ model_card = ModelCard.from_template(card_data, model_description=model_description)
+
+ if tags is not None:
+ # Ensure model_card.data.tags is a list and not None
+ if model_card.data.tags is None:
+ model_card.data.tags = []
+ for model_tag in tags:
+ if model_tag not in model_card.data.tags:
+ model_card.data.tags.append(model_tag)
+
+ return model_card
+
+
+class PushInProgress:
+ """
+ Internal class to keep track of a push in progress (which might contain multiple `Future` jobs).
+ """
+
+ def __init__(self, jobs: Optional[futures.Future] = None) -> None:
+ self.jobs = [] if jobs is None else jobs
+
+ def is_done(self):
+ return all(job.done() for job in self.jobs)
+
+ def wait_until_done(self):
+ futures.wait(self.jobs)
+
+ def cancel(self) -> None:
+ self.jobs = [
+ job
+ for job in self.jobs
+ # Cancel the job if it wasn't started yet and remove cancelled/done jobs from the list
+ if not (job.cancel() or job.done())
+ ]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/import_utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/import_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..11c84566e3e8172f5390d37f42f0160dde2429f4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/import_utils.py
@@ -0,0 +1,2883 @@
+# 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
+import warnings
+from collections import OrderedDict
+from enum import Enum
+from functools import lru_cache
+from itertools import chain
+from types import ModuleType
+from typing import Any, Callable, Optional, Union
+
+from packaging import version
+
+from . import logging
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+# TODO: This doesn't work for all packages (`bs4`, `faiss`, etc.) Talk to Sylvain to see how to do with it better.
+def _is_package_available(pkg_name: str, return_version: bool = False) -> Union[tuple[bool, str], bool]:
+ # Check if the package spec exists and grab its version to avoid importing a local directory
+ package_exists = importlib.util.find_spec(pkg_name) is not None
+ package_version = "N/A"
+ if package_exists:
+ try:
+ # TODO: Once python 3.9 support is dropped, `importlib.metadata.packages_distributions()`
+ # should be used here to map from package name to distribution names
+ # e.g. PIL -> Pillow, Pillow-SIMD; quark -> amd-quark; onnxruntime -> onnxruntime-gpu.
+ # `importlib.metadata.packages_distributions()` is not available in Python 3.9.
+
+ # Primary method to get the package version
+ package_version = importlib.metadata.version(pkg_name)
+ except importlib.metadata.PackageNotFoundError:
+ # Fallback method: Only for "torch" and versions containing "dev"
+ if pkg_name == "torch":
+ try:
+ package = importlib.import_module(pkg_name)
+ temp_version = getattr(package, "__version__", "N/A")
+ # Check if the version contains "dev"
+ if "dev" in temp_version:
+ package_version = temp_version
+ package_exists = True
+ else:
+ package_exists = False
+ except ImportError:
+ # If the package can't be imported, it's not available
+ package_exists = False
+ elif pkg_name == "quark":
+ # TODO: remove once `importlib.metadata.packages_distributions()` is supported.
+ try:
+ package_version = importlib.metadata.version("amd-quark")
+ except Exception:
+ package_exists = False
+ elif pkg_name == "triton":
+ try:
+ # import triton works for both linux and windows
+ package = importlib.import_module(pkg_name)
+ package_version = getattr(package, "__version__", "N/A")
+ except Exception:
+ try:
+ package_version = importlib.metadata.version("pytorch-triton") # pytorch-triton
+ except Exception:
+ package_exists = False
+ else:
+ # For packages other than "torch", don't attempt the fallback and set as not available
+ package_exists = False
+ logger.debug(f"Detected {pkg_name} version: {package_version}")
+ if return_version:
+ return package_exists, package_version
+ else:
+ return package_exists
+
+
+ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"}
+ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"})
+
+USE_TF = os.environ.get("USE_TF", "AUTO").upper()
+USE_TORCH = os.environ.get("USE_TORCH", "AUTO").upper()
+USE_JAX = os.environ.get("USE_FLAX", "AUTO").upper()
+
+# Try to run a native pytorch job in an environment with TorchXLA installed by setting this value to 0.
+USE_TORCH_XLA = os.environ.get("USE_TORCH_XLA", "1").upper()
+
+FORCE_TF_AVAILABLE = os.environ.get("FORCE_TF_AVAILABLE", "AUTO").upper()
+
+# `transformers` requires `torch>=1.11` but this variable is exposed publicly, and we can't simply remove it.
+# This is the version of torch required to run torch.fx features and torch.onnx with dictionary inputs.
+TORCH_FX_REQUIRED_VERSION = version.parse("1.10")
+
+ACCELERATE_MIN_VERSION = "0.26.0"
+SCHEDULEFREE_MIN_VERSION = "1.2.6"
+FSDP_MIN_VERSION = "1.12.0"
+GGUF_MIN_VERSION = "0.10.0"
+XLA_FSDPV2_MIN_VERSION = "2.2.0"
+HQQ_MIN_VERSION = "0.2.1"
+VPTQ_MIN_VERSION = "0.0.4"
+TORCHAO_MIN_VERSION = "0.4.0"
+AUTOROUND_MIN_VERSION = "0.5.0"
+TRITON_MIN_VERSION = "1.0.0"
+
+_accelerate_available, _accelerate_version = _is_package_available("accelerate", return_version=True)
+_apex_available = _is_package_available("apex")
+_apollo_torch_available = _is_package_available("apollo_torch")
+_aqlm_available = _is_package_available("aqlm")
+_vptq_available, _vptq_version = _is_package_available("vptq", return_version=True)
+_av_available = importlib.util.find_spec("av") is not None
+_decord_available = importlib.util.find_spec("decord") is not None
+_torchcodec_available = importlib.util.find_spec("torchcodec") is not None
+_libcst_available = _is_package_available("libcst")
+_bitsandbytes_available = _is_package_available("bitsandbytes")
+_eetq_available = _is_package_available("eetq")
+_fbgemm_gpu_available = _is_package_available("fbgemm_gpu")
+_galore_torch_available = _is_package_available("galore_torch")
+_lomo_available = _is_package_available("lomo_optim")
+_grokadamw_available = _is_package_available("grokadamw")
+_schedulefree_available, _schedulefree_version = _is_package_available("schedulefree", return_version=True)
+_torch_optimi_available = importlib.util.find_spec("optimi") is not None
+# `importlib.metadata.version` doesn't work with `bs4` but `beautifulsoup4`. For `importlib.util.find_spec`, reversed.
+_bs4_available = importlib.util.find_spec("bs4") is not None
+_coloredlogs_available = _is_package_available("coloredlogs")
+# `importlib.metadata.util` doesn't work with `opencv-python-headless`.
+_cv2_available = importlib.util.find_spec("cv2") is not None
+_yt_dlp_available = importlib.util.find_spec("yt_dlp") is not None
+_datasets_available = _is_package_available("datasets")
+_detectron2_available = _is_package_available("detectron2")
+# We need to check `faiss`, `faiss-cpu` and `faiss-gpu`.
+_faiss_available = importlib.util.find_spec("faiss") is not None
+try:
+ _faiss_version = importlib.metadata.version("faiss")
+ logger.debug(f"Successfully imported faiss version {_faiss_version}")
+except importlib.metadata.PackageNotFoundError:
+ try:
+ _faiss_version = importlib.metadata.version("faiss-cpu")
+ logger.debug(f"Successfully imported faiss version {_faiss_version}")
+ except importlib.metadata.PackageNotFoundError:
+ try:
+ _faiss_version = importlib.metadata.version("faiss-gpu")
+ logger.debug(f"Successfully imported faiss version {_faiss_version}")
+ except importlib.metadata.PackageNotFoundError:
+ _faiss_available = False
+_ftfy_available = _is_package_available("ftfy")
+_g2p_en_available = _is_package_available("g2p_en")
+_hadamard_available = _is_package_available("fast_hadamard_transform")
+_ipex_available, _ipex_version = _is_package_available("intel_extension_for_pytorch", return_version=True)
+_jieba_available = _is_package_available("jieba")
+_jinja_available = _is_package_available("jinja2")
+_kenlm_available = _is_package_available("kenlm")
+_keras_nlp_available = _is_package_available("keras_nlp")
+_levenshtein_available = _is_package_available("Levenshtein")
+_librosa_available = _is_package_available("librosa")
+_natten_available = _is_package_available("natten")
+_nltk_available = _is_package_available("nltk")
+_onnx_available = _is_package_available("onnx")
+_openai_available = _is_package_available("openai")
+_optimum_available = _is_package_available("optimum")
+_auto_gptq_available = _is_package_available("auto_gptq")
+_gptqmodel_available = _is_package_available("gptqmodel")
+_auto_round_available, _auto_round_version = _is_package_available("auto_round", return_version=True)
+# `importlib.metadata.version` doesn't work with `awq`
+_auto_awq_available = importlib.util.find_spec("awq") is not None
+_quark_available = _is_package_available("quark")
+_fp_quant_available, _fp_quant_version = _is_package_available("fp_quant", return_version=True)
+_qutlass_available = _is_package_available("qutlass")
+_is_optimum_quanto_available = False
+try:
+ importlib.metadata.version("optimum_quanto")
+ _is_optimum_quanto_available = True
+except importlib.metadata.PackageNotFoundError:
+ _is_optimum_quanto_available = False
+# For compressed_tensors, only check spec to allow compressed_tensors-nightly package
+_compressed_tensors_available = importlib.util.find_spec("compressed_tensors") is not None
+_pandas_available = _is_package_available("pandas")
+_peft_available = _is_package_available("peft")
+_phonemizer_available = _is_package_available("phonemizer")
+_uroman_available = _is_package_available("uroman")
+_psutil_available = _is_package_available("psutil")
+_py3nvml_available = _is_package_available("py3nvml")
+_pyctcdecode_available = _is_package_available("pyctcdecode")
+_pygments_available = _is_package_available("pygments")
+_pytesseract_available = _is_package_available("pytesseract")
+_pytest_available = _is_package_available("pytest")
+_pytorch_quantization_available = _is_package_available("pytorch_quantization")
+_rjieba_available = _is_package_available("rjieba")
+_sacremoses_available = _is_package_available("sacremoses")
+_safetensors_available = _is_package_available("safetensors")
+_scipy_available = _is_package_available("scipy")
+_sentencepiece_available = _is_package_available("sentencepiece")
+_is_seqio_available = _is_package_available("seqio")
+_is_gguf_available, _gguf_version = _is_package_available("gguf", return_version=True)
+_sklearn_available = importlib.util.find_spec("sklearn") is not None
+if _sklearn_available:
+ try:
+ importlib.metadata.version("scikit-learn")
+ except importlib.metadata.PackageNotFoundError:
+ _sklearn_available = False
+_smdistributed_available = importlib.util.find_spec("smdistributed") is not None
+_soundfile_available = _is_package_available("soundfile")
+_spacy_available = _is_package_available("spacy")
+_sudachipy_available, _sudachipy_version = _is_package_available("sudachipy", return_version=True)
+_tensorflow_probability_available = _is_package_available("tensorflow_probability")
+_tensorflow_text_available = _is_package_available("tensorflow_text")
+_tf2onnx_available = _is_package_available("tf2onnx")
+_timm_available = _is_package_available("timm")
+_tokenizers_available = _is_package_available("tokenizers")
+_torchaudio_available = _is_package_available("torchaudio")
+_torchao_available, _torchao_version = _is_package_available("torchao", return_version=True)
+_torchdistx_available = _is_package_available("torchdistx")
+_torchvision_available, _torchvision_version = _is_package_available("torchvision", return_version=True)
+_mlx_available = _is_package_available("mlx")
+_num2words_available = _is_package_available("num2words")
+_hqq_available, _hqq_version = _is_package_available("hqq", return_version=True)
+_tiktoken_available = _is_package_available("tiktoken")
+_blobfile_available = _is_package_available("blobfile")
+_liger_kernel_available = _is_package_available("liger_kernel")
+_spqr_available = _is_package_available("spqr_quant")
+_rich_available = _is_package_available("rich")
+_kernels_available = _is_package_available("kernels")
+_matplotlib_available = _is_package_available("matplotlib")
+_mistral_common_available = _is_package_available("mistral_common")
+_triton_available, _triton_version = _is_package_available("triton", return_version=True)
+
+_torch_version = "N/A"
+_torch_available = False
+if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES:
+ _torch_available, _torch_version = _is_package_available("torch", return_version=True)
+ if _torch_available:
+ _torch_available = version.parse(_torch_version) >= version.parse("2.1.0")
+ if not _torch_available:
+ logger.warning(f"Disabling PyTorch because PyTorch >= 2.1 is required but found {_torch_version}")
+else:
+ logger.info("Disabling PyTorch because USE_TF is set")
+ _torch_available = False
+
+
+_tf_version = "N/A"
+_tf_available = False
+if FORCE_TF_AVAILABLE in ENV_VARS_TRUE_VALUES:
+ _tf_available = True
+else:
+ if USE_TF in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TORCH not in ENV_VARS_TRUE_VALUES:
+ # Note: _is_package_available("tensorflow") fails for tensorflow-cpu. Please test any changes to the line below
+ # with tensorflow-cpu to make sure it still works!
+ _tf_available = importlib.util.find_spec("tensorflow") is not None
+ if _tf_available:
+ candidates = (
+ "tensorflow",
+ "tensorflow-cpu",
+ "tensorflow-gpu",
+ "tf-nightly",
+ "tf-nightly-cpu",
+ "tf-nightly-gpu",
+ "tf-nightly-rocm",
+ "intel-tensorflow",
+ "intel-tensorflow-avx512",
+ "tensorflow-rocm",
+ "tensorflow-macos",
+ "tensorflow-aarch64",
+ )
+ _tf_version = None
+ # For the metadata, we have to look for both tensorflow and tensorflow-cpu
+ for pkg in candidates:
+ try:
+ _tf_version = importlib.metadata.version(pkg)
+ break
+ except importlib.metadata.PackageNotFoundError:
+ pass
+ _tf_available = _tf_version is not None
+ if _tf_available:
+ if version.parse(_tf_version) < version.parse("2"):
+ logger.info(
+ f"TensorFlow found but with version {_tf_version}. Transformers requires version 2 minimum."
+ )
+ _tf_available = False
+ else:
+ logger.info("Disabling Tensorflow because USE_TORCH is set")
+
+
+_essentia_available = importlib.util.find_spec("essentia") is not None
+try:
+ _essentia_version = importlib.metadata.version("essentia")
+ logger.debug(f"Successfully imported essentia version {_essentia_version}")
+except importlib.metadata.PackageNotFoundError:
+ _essentia_version = False
+
+
+_pydantic_available = importlib.util.find_spec("pydantic") is not None
+try:
+ _pydantic_version = importlib.metadata.version("pydantic")
+ logger.debug(f"Successfully imported pydantic version {_pydantic_version}")
+except importlib.metadata.PackageNotFoundError:
+ _pydantic_available = False
+
+
+_fastapi_available = importlib.util.find_spec("fastapi") is not None
+try:
+ _fastapi_version = importlib.metadata.version("fastapi")
+ logger.debug(f"Successfully imported pydantic version {_fastapi_version}")
+except importlib.metadata.PackageNotFoundError:
+ _fastapi_available = False
+
+
+_uvicorn_available = importlib.util.find_spec("uvicorn") is not None
+try:
+ _uvicorn_version = importlib.metadata.version("uvicorn")
+ logger.debug(f"Successfully imported pydantic version {_uvicorn_version}")
+except importlib.metadata.PackageNotFoundError:
+ _uvicorn_available = False
+
+
+_pretty_midi_available = importlib.util.find_spec("pretty_midi") is not None
+try:
+ _pretty_midi_version = importlib.metadata.version("pretty_midi")
+ logger.debug(f"Successfully imported pretty_midi version {_pretty_midi_version}")
+except importlib.metadata.PackageNotFoundError:
+ _pretty_midi_available = False
+
+
+ccl_version = "N/A"
+_is_ccl_available = (
+ importlib.util.find_spec("torch_ccl") is not None
+ or importlib.util.find_spec("oneccl_bindings_for_pytorch") is not None
+)
+try:
+ ccl_version = importlib.metadata.version("oneccl_bind_pt")
+ logger.debug(f"Detected oneccl_bind_pt version {ccl_version}")
+except importlib.metadata.PackageNotFoundError:
+ _is_ccl_available = False
+
+
+_flax_available = False
+if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES:
+ _flax_available, _flax_version = _is_package_available("flax", return_version=True)
+ if _flax_available:
+ _jax_available, _jax_version = _is_package_available("jax", return_version=True)
+ if _jax_available:
+ logger.info(f"JAX version {_jax_version}, Flax version {_flax_version} available.")
+ else:
+ _flax_available = _jax_available = False
+ _jax_version = _flax_version = "N/A"
+
+
+_torch_xla_available = False
+if USE_TORCH_XLA in ENV_VARS_TRUE_VALUES:
+ _torch_xla_available, _torch_xla_version = _is_package_available("torch_xla", return_version=True)
+ if _torch_xla_available:
+ logger.info(f"Torch XLA version {_torch_xla_version} available.")
+
+
+def is_kenlm_available() -> Union[tuple[bool, str], bool]:
+ return _kenlm_available
+
+
+def is_kernels_available() -> Union[tuple[bool, str], bool]:
+ return _kernels_available
+
+
+def is_cv2_available() -> Union[tuple[bool, str], bool]:
+ return _cv2_available
+
+
+def is_yt_dlp_available() -> Union[tuple[bool, str], bool]:
+ return _yt_dlp_available
+
+
+def is_torch_available() -> Union[tuple[bool, str], bool]:
+ return _torch_available
+
+
+def is_libcst_available() -> Union[tuple[bool, str], bool]:
+ return _libcst_available
+
+
+def is_accelerate_available(min_version: str = ACCELERATE_MIN_VERSION) -> bool:
+ return _accelerate_available and version.parse(_accelerate_version) >= version.parse(min_version)
+
+
+def is_torch_accelerator_available() -> bool:
+ if is_torch_available():
+ import torch
+
+ return hasattr(torch, "accelerator")
+
+ return False
+
+
+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
+
+
+def is_triton_available(min_version: str = TRITON_MIN_VERSION) -> bool:
+ return _triton_available and version.parse(_triton_version) >= version.parse(min_version)
+
+
+def is_hadamard_available() -> Union[tuple[bool, str], bool]:
+ return _hadamard_available
+
+
+def is_hqq_available(min_version: str = HQQ_MIN_VERSION) -> bool:
+ return _hqq_available and version.parse(_hqq_version) >= version.parse(min_version)
+
+
+def is_pygments_available() -> Union[tuple[bool, str], bool]:
+ return _pygments_available
+
+
+def get_torch_version() -> str:
+ return _torch_version
+
+
+def get_torch_major_and_minor_version() -> str:
+ 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_torch_sdpa_available():
+ # Mostly retained for backward compatibility in remote code, since sdpa works correctly on all torch versions >= 2.2
+ if not is_torch_available() or _torch_version == "N/A":
+ return False
+ return True
+
+
+def is_torch_flex_attn_available() -> bool:
+ if not is_torch_available() or _torch_version == "N/A":
+ return False
+
+ # TODO check if some bugs cause push backs on the exact version
+ # NOTE: We require torch>=2.5.0 as it is the first release
+ return version.parse(_torch_version) >= version.parse("2.5.0")
+
+
+def is_torchvision_available() -> bool:
+ return _torchvision_available
+
+
+def is_torchvision_v2_available() -> bool:
+ if not is_torchvision_available():
+ return False
+
+ # NOTE: We require torchvision>=0.15 as v2 transforms are available from this version: https://pytorch.org/vision/stable/transforms.html#v1-or-v2-which-one-should-i-use
+ return version.parse(_torchvision_version) >= version.parse("0.15")
+
+
+def is_galore_torch_available() -> Union[tuple[bool, str], bool]:
+ return _galore_torch_available
+
+
+def is_apollo_torch_available() -> Union[tuple[bool, str], bool]:
+ return _apollo_torch_available
+
+
+def is_torch_optimi_available() -> Union[tuple[bool, str], bool]:
+ return _torch_optimi_available
+
+
+def is_lomo_available() -> Union[tuple[bool, str], bool]:
+ return _lomo_available
+
+
+def is_grokadamw_available() -> Union[tuple[bool, str], bool]:
+ return _grokadamw_available
+
+
+def is_schedulefree_available(min_version: str = SCHEDULEFREE_MIN_VERSION) -> bool:
+ return _schedulefree_available and version.parse(_schedulefree_version) >= version.parse(min_version)
+
+
+def is_pyctcdecode_available() -> Union[tuple[bool, str], bool]:
+ return _pyctcdecode_available
+
+
+def is_librosa_available() -> Union[tuple[bool, str], bool]:
+ return _librosa_available
+
+
+def is_essentia_available() -> Union[tuple[bool, str], bool]:
+ return _essentia_available
+
+
+def is_pydantic_available() -> Union[tuple[bool, str], bool]:
+ return _pydantic_available
+
+
+def is_fastapi_available() -> Union[tuple[bool, str], bool]:
+ return _fastapi_available
+
+
+def is_uvicorn_available() -> Union[tuple[bool, str], bool]:
+ return _uvicorn_available
+
+
+def is_openai_available() -> Union[tuple[bool, str], bool]:
+ return _openai_available
+
+
+def is_pretty_midi_available() -> Union[tuple[bool, str], bool]:
+ return _pretty_midi_available
+
+
+def is_torch_cuda_available() -> bool:
+ if is_torch_available():
+ import torch
+
+ return torch.cuda.is_available()
+ else:
+ return False
+
+
+def is_cuda_platform() -> bool:
+ if is_torch_available():
+ import torch
+
+ return torch.version.cuda is not None
+ else:
+ return False
+
+
+def is_rocm_platform() -> bool:
+ if is_torch_available():
+ import torch
+
+ return torch.version.hip is not None
+ else:
+ return False
+
+
+def is_mamba_ssm_available() -> Union[tuple[bool, str], bool]:
+ if is_torch_available():
+ import torch
+
+ if not torch.cuda.is_available():
+ return False
+ else:
+ return _is_package_available("mamba_ssm")
+ return False
+
+
+def is_mamba_2_ssm_available() -> bool:
+ if is_torch_available():
+ import torch
+
+ if not torch.cuda.is_available():
+ return False
+ else:
+ if _is_package_available("mamba_ssm"):
+ import mamba_ssm
+
+ if version.parse(mamba_ssm.__version__) >= version.parse("2.0.4"):
+ return True
+ return False
+
+
+def is_causal_conv1d_available() -> Union[tuple[bool, str], bool]:
+ if is_torch_available():
+ import torch
+
+ if not torch.cuda.is_available():
+ return False
+ return _is_package_available("causal_conv1d")
+ return False
+
+
+def is_xlstm_available() -> Union[tuple[bool, str], bool]:
+ if is_torch_available():
+ return _is_package_available("xlstm")
+ return False
+
+
+def is_mambapy_available() -> Union[tuple[bool, str], bool]:
+ if is_torch_available():
+ return _is_package_available("mambapy")
+ return False
+
+
+def is_torch_mps_available(min_version: Optional[str] = None) -> bool:
+ if is_torch_available():
+ import torch
+
+ if hasattr(torch.backends, "mps"):
+ backend_available = torch.backends.mps.is_available() and torch.backends.mps.is_built()
+ if min_version is not None:
+ flag = version.parse(_torch_version) >= version.parse(min_version)
+ backend_available = backend_available and flag
+ return backend_available
+ return False
+
+
+def is_torch_bf16_gpu_available() -> 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 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)
+ return False
+
+
+def is_torch_bf16_cpu_available() -> Union[tuple[bool, str], bool]:
+ return is_torch_available()
+
+
+def is_torch_bf16_available() -> bool:
+ # the original bf16 check was for gpu only, but later a cpu/bf16 combo has emerged so this util
+ # has become ambiguous and therefore deprecated
+ warnings.warn(
+ "The util is_torch_bf16_available is deprecated, please use is_torch_bf16_gpu_available "
+ "or is_torch_bf16_cpu_available instead according to whether it's used with cpu or gpu",
+ FutureWarning,
+ )
+ return is_torch_bf16_gpu_available()
+
+
+@lru_cache
+def is_torch_fp16_available_on_device(device: 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)
+
+ except: # noqa: E722
+ # TODO: more precise exception matching, if possible.
+ # most backends should return `RuntimeError` however this is not guaranteed.
+ return False
+
+ return True
+
+
+@lru_cache
+def is_torch_bf16_available_on_device(device: 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
+ except: # noqa: E722
+ # TODO: more precise exception matching, if possible.
+ # most backends should return `RuntimeError` however this is not guaranteed.
+ return False
+
+ return True
+
+
+def is_torch_tf32_available() -> bool:
+ if not is_torch_available():
+ return False
+
+ import torch
+
+ if not torch.cuda.is_available() or torch.version.cuda is None:
+ return False
+ if torch.cuda.get_device_properties(torch.cuda.current_device()).major < 8:
+ return False
+ return True
+
+
+def is_torch_fx_available() -> Union[tuple[bool, str], bool]:
+ return is_torch_available()
+
+
+def is_peft_available() -> Union[tuple[bool, str], bool]:
+ return _peft_available
+
+
+def is_bs4_available() -> Union[tuple[bool, str], bool]:
+ return _bs4_available
+
+
+def is_tf_available() -> bool:
+ return _tf_available
+
+
+def is_coloredlogs_available() -> Union[tuple[bool, str], bool]:
+ return _coloredlogs_available
+
+
+def is_tf2onnx_available() -> Union[tuple[bool, str], bool]:
+ return _tf2onnx_available
+
+
+def is_onnx_available() -> Union[tuple[bool, str], bool]:
+ return _onnx_available
+
+
+def is_flax_available() -> bool:
+ return _flax_available
+
+
+def is_flute_available() -> bool:
+ try:
+ return importlib.util.find_spec("flute") is not None and importlib.metadata.version("flute-kernel") >= "0.4.1"
+ except importlib.metadata.PackageNotFoundError:
+ return False
+
+
+def is_ftfy_available() -> Union[tuple[bool, str], bool]:
+ return _ftfy_available
+
+
+def is_g2p_en_available() -> Union[tuple[bool, str], bool]:
+ return _g2p_en_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."
+
+ if not _torch_xla_available:
+ return False
+
+ import torch_xla
+
+ if check_is_gpu:
+ return torch_xla.runtime.device_type() in ["GPU", "CUDA"]
+ elif check_is_tpu:
+ return torch_xla.runtime.device_type() == "TPU"
+
+ return True
+
+
+@lru_cache
+def is_torch_neuroncore_available(check_device=True) -> bool:
+ if importlib.util.find_spec("torch_neuronx") is not None:
+ return is_torch_xla_available()
+ return False
+
+
+@lru_cache
+def is_torch_npu_available(check_device=False) -> bool:
+ "Checks if `torch_npu` is installed and potentially if a NPU is in the environment"
+ if not _torch_available or importlib.util.find_spec("torch_npu") is None:
+ return False
+
+ import torch
+ import torch_npu # noqa: F401
+
+ if check_device:
+ try:
+ # Will raise a RuntimeError if no NPU is found
+ _ = torch.npu.device_count()
+ return torch.npu.is_available()
+ except RuntimeError:
+ return False
+ return hasattr(torch, "npu") and torch.npu.is_available()
+
+
+@lru_cache
+def is_torch_mlu_available(check_device=False) -> bool:
+ """
+ Checks if `mlu` is available via an `cndev-based` check which won't trigger the drivers and leave mlu
+ uninitialized.
+ """
+ if not _torch_available or importlib.util.find_spec("torch_mlu") is None:
+ return False
+
+ import torch
+ import torch_mlu # noqa: F401
+
+ pytorch_cndev_based_mlu_check_previous_value = os.environ.get("PYTORCH_CNDEV_BASED_MLU_CHECK")
+ try:
+ os.environ["PYTORCH_CNDEV_BASED_MLU_CHECK"] = str(1)
+ available = torch.mlu.is_available()
+ finally:
+ if pytorch_cndev_based_mlu_check_previous_value:
+ os.environ["PYTORCH_CNDEV_BASED_MLU_CHECK"] = pytorch_cndev_based_mlu_check_previous_value
+ else:
+ os.environ.pop("PYTORCH_CNDEV_BASED_MLU_CHECK", None)
+
+ return available
+
+
+@lru_cache
+def is_torch_musa_available(check_device=False) -> bool:
+ "Checks if `torch_musa` is installed and potentially if a MUSA is in the environment"
+ if not _torch_available or importlib.util.find_spec("torch_musa") is None:
+ return False
+
+ import torch
+ import torch_musa # noqa: F401
+
+ torch_musa_min_version = "0.33.0"
+ if _accelerate_available and version.parse(_accelerate_version) < version.parse(torch_musa_min_version):
+ return False
+
+ if check_device:
+ try:
+ # Will raise a RuntimeError if no MUSA is found
+ _ = torch.musa.device_count()
+ return torch.musa.is_available()
+ except RuntimeError:
+ return False
+ return hasattr(torch, "musa") and torch.musa.is_available()
+
+
+@lru_cache
+def is_torch_hpu_available() -> bool:
+ "Checks if `torch.hpu` is available and potentially if a HPU is in the environment"
+ if (
+ not _torch_available
+ or importlib.util.find_spec("habana_frameworks") is None
+ or importlib.util.find_spec("habana_frameworks.torch") is None
+ ):
+ return False
+
+ torch_hpu_min_accelerate_version = "1.5.0"
+ 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: Optional[int] = 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_habana_gaudi1() -> bool:
+ if not is_torch_hpu_available():
+ return False
+
+ import habana_frameworks.torch.utils.experimental as htexp # noqa: F401
+
+ # Check if the device is Gaudi1 (vs Gaudi2, Gaudi3)
+ return htexp._get_device_type() == htexp.synDeviceType.synDeviceGaudi
+
+
+def is_torchdynamo_available() -> Union[tuple[bool, str], bool]:
+ return is_torch_available()
+
+
+def is_torch_compile_available() -> Union[tuple[bool, str], bool]:
+ return is_torch_available()
+
+
+def is_torchdynamo_compiling() -> Union[tuple[bool, str], bool]:
+ if not is_torch_available():
+ return False
+
+ # Importing torch._dynamo causes issues with PyTorch profiler (https://github.com/pytorch/pytorch/issues/130622)
+ # hence rather relying on `torch.compiler.is_compiling()` when possible (torch>=2.3)
+ try:
+ import torch
+
+ return torch.compiler.is_compiling()
+ except Exception:
+ try:
+ import torch._dynamo as dynamo # noqa: F401
+
+ return dynamo.is_compiling()
+ except Exception:
+ return False
+
+
+def is_torchdynamo_exporting() -> bool:
+ if not is_torch_available():
+ return False
+
+ try:
+ import torch
+
+ return torch.compiler.is_exporting()
+ except Exception:
+ try:
+ import torch._dynamo as dynamo # noqa: F401
+
+ return dynamo.is_exporting()
+ except Exception:
+ return False
+
+
+def is_torch_tensorrt_fx_available() -> bool:
+ if importlib.util.find_spec("torch_tensorrt") is None:
+ return False
+ return importlib.util.find_spec("torch_tensorrt.fx") is not None
+
+
+def is_datasets_available() -> Union[tuple[bool, str], bool]:
+ return _datasets_available
+
+
+def is_detectron2_available() -> Union[tuple[bool, str], bool]:
+ return _detectron2_available
+
+
+def is_rjieba_available() -> Union[tuple[bool, str], bool]:
+ return _rjieba_available
+
+
+def is_psutil_available() -> Union[tuple[bool, str], bool]:
+ return _psutil_available
+
+
+def is_py3nvml_available() -> Union[tuple[bool, str], bool]:
+ return _py3nvml_available
+
+
+def is_sacremoses_available() -> Union[tuple[bool, str], bool]:
+ return _sacremoses_available
+
+
+def is_apex_available() -> Union[tuple[bool, str], bool]:
+ return _apex_available
+
+
+def is_aqlm_available() -> Union[tuple[bool, str], bool]:
+ return _aqlm_available
+
+
+def is_vptq_available(min_version: str = VPTQ_MIN_VERSION) -> bool:
+ return _vptq_available and version.parse(_vptq_version) >= version.parse(min_version)
+
+
+def is_av_available() -> bool:
+ return _av_available
+
+
+def is_decord_available() -> bool:
+ return _decord_available
+
+
+def is_torchcodec_available() -> bool:
+ return _torchcodec_available
+
+
+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
+
+
+def is_ipex_available(min_version: str = "") -> bool:
+ def get_major_and_minor_from_version(full_version):
+ return str(version.parse(full_version).major) + "." + str(version.parse(full_version).minor)
+
+ if not is_torch_available() or not _ipex_available:
+ return False
+
+ torch_major_and_minor = get_major_and_minor_from_version(_torch_version)
+ ipex_major_and_minor = get_major_and_minor_from_version(_ipex_version)
+ if torch_major_and_minor != ipex_major_and_minor:
+ logger.warning(
+ f"Intel Extension for PyTorch {ipex_major_and_minor} needs to work with PyTorch {ipex_major_and_minor}.*,"
+ f" but PyTorch {_torch_version} is found. Please switch to the matching version and run again."
+ )
+ return False
+ if min_version:
+ return version.parse(_ipex_version) >= version.parse(min_version)
+ return True
+
+
+@lru_cache
+def is_torch_xpu_available(check_device: bool = False) -> bool:
+ """
+ Checks if XPU acceleration is available either via native PyTorch (>=2.6),
+ `intel_extension_for_pytorch` or via stock PyTorch (>=2.4) and potentially
+ if a XPU is in the environment.
+ """
+ if not is_torch_available():
+ return False
+
+ torch_version = version.parse(_torch_version)
+ if torch_version.major == 2 and torch_version.minor < 6:
+ if is_ipex_available():
+ import intel_extension_for_pytorch # noqa: F401
+ elif torch_version.major == 2 and torch_version.minor < 4:
+ return False
+
+ import torch
+
+ if check_device:
+ try:
+ # Will raise a RuntimeError if no XPU is found
+ _ = torch.xpu.device_count()
+ return torch.xpu.is_available()
+ except RuntimeError:
+ return False
+ return hasattr(torch, "xpu") and torch.xpu.is_available()
+
+
+@lru_cache
+def is_bitsandbytes_available(check_library_only: bool = False) -> bool:
+ if not _bitsandbytes_available:
+ return False
+
+ if check_library_only:
+ return True
+
+ if not is_torch_available():
+ return False
+
+ import torch
+
+ # `bitsandbytes` versions older than 0.43.1 eagerly require CUDA at import time,
+ # so those versions of the library are practically only available when CUDA is too.
+ if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.43.1"):
+ return torch.cuda.is_available()
+
+ # Newer versions of `bitsandbytes` can be imported on systems without CUDA.
+ return True
+
+
+def is_bitsandbytes_multi_backend_available() -> bool:
+ if not is_bitsandbytes_available():
+ return False
+
+ import bitsandbytes as bnb
+
+ return "multi_backend" in getattr(bnb, "features", set())
+
+
+def is_flash_attn_2_available() -> bool:
+ if not is_torch_available():
+ return False
+
+ if not _is_package_available("flash_attn"):
+ return False
+
+ # Let's add an extra check to see if cuda is available
+ import torch
+
+ if not (torch.cuda.is_available() or is_torch_mlu_available()):
+ return False
+
+ if torch.version.cuda:
+ return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.1.0")
+ elif torch.version.hip:
+ # TODO: Bump the requirement to 2.1.0 once released in https://github.com/ROCmSoftwarePlatform/flash-attention
+ return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.0.4")
+ elif is_torch_mlu_available():
+ return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.3.3")
+ else:
+ return False
+
+
+@lru_cache
+def is_flash_attn_3_available() -> bool:
+ if not is_torch_available():
+ return False
+
+ if not _is_package_available("flash_attn_3"):
+ return False
+
+ import torch
+
+ if not torch.cuda.is_available():
+ return False
+
+ # TODO: Check for a minimum version when FA3 is stable
+ # return version.parse(importlib.metadata.version("flash_attn_3")) >= version.parse("3.0.0")
+
+ return True
+
+
+@lru_cache
+def is_flash_attn_greater_or_equal_2_10() -> bool:
+ if not _is_package_available("flash_attn"):
+ return False
+
+ return version.parse(importlib.metadata.version("flash_attn")) >= version.parse("2.1.0")
+
+
+@lru_cache
+def is_flash_attn_greater_or_equal(library_version: str) -> bool:
+ if not _is_package_available("flash_attn"):
+ return False
+
+ return version.parse(importlib.metadata.version("flash_attn")) >= version.parse(library_version)
+
+
+@lru_cache
+def is_torch_greater_or_equal(library_version: str, 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_package_available("torch"):
+ return False
+
+ if accept_dev:
+ return version.parse(version.parse(importlib.metadata.version("torch")).base_version) >= version.parse(
+ library_version
+ )
+ else:
+ return version.parse(importlib.metadata.version("torch")) >= 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_package_available("torch"):
+ return False
+
+ if accept_dev:
+ return version.parse(version.parse(importlib.metadata.version("torch")).base_version) <= version.parse(
+ library_version
+ )
+ else:
+ return version.parse(importlib.metadata.version("torch")) <= version.parse(library_version)
+
+
+@lru_cache
+def is_huggingface_hub_greater_or_equal(library_version: str, accept_dev: bool = False) -> bool:
+ if not _is_package_available("huggingface_hub"):
+ return False
+
+ if accept_dev:
+ return version.parse(
+ version.parse(importlib.metadata.version("huggingface_hub")).base_version
+ ) >= version.parse(library_version)
+ else:
+ return version.parse(importlib.metadata.version("huggingface_hub")) >= 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_package_available("optimum.quanto"):
+ return False
+
+ if accept_dev:
+ return version.parse(version.parse(importlib.metadata.version("optimum-quanto")).base_version) > version.parse(
+ library_version
+ )
+ else:
+ return version.parse(importlib.metadata.version("optimum-quanto")) > version.parse(library_version)
+
+
+def is_torchdistx_available():
+ return _torchdistx_available
+
+
+def is_faiss_available() -> bool:
+ return _faiss_available
+
+
+def is_scipy_available() -> Union[tuple[bool, str], bool]:
+ return _scipy_available
+
+
+def is_sklearn_available() -> Union[tuple[bool, str], bool]:
+ return _sklearn_available
+
+
+def is_sentencepiece_available() -> Union[tuple[bool, str], bool]:
+ return _sentencepiece_available
+
+
+def is_seqio_available() -> Union[tuple[bool, str], bool]:
+ return _is_seqio_available
+
+
+def is_gguf_available(min_version: str = GGUF_MIN_VERSION) -> bool:
+ return _is_gguf_available and version.parse(_gguf_version) >= version.parse(min_version)
+
+
+def is_protobuf_available() -> bool:
+ if importlib.util.find_spec("google") is None:
+ return False
+ return importlib.util.find_spec("google.protobuf") is not None
+
+
+def is_fsdp_available(min_version: str = FSDP_MIN_VERSION) -> bool:
+ return is_torch_available() and version.parse(_torch_version) >= version.parse(min_version)
+
+
+def is_optimum_available() -> Union[tuple[bool, str], bool]:
+ return _optimum_available
+
+
+def is_auto_awq_available() -> bool:
+ return _auto_awq_available
+
+
+def is_auto_round_available(min_version: str = AUTOROUND_MIN_VERSION) -> bool:
+ return _auto_round_available and version.parse(_auto_round_version) >= version.parse(min_version)
+
+
+def is_optimum_quanto_available():
+ # `importlib.metadata.version` doesn't work with `optimum.quanto`, need to put `optimum_quanto`
+ return _is_optimum_quanto_available
+
+
+def is_quark_available() -> Union[tuple[bool, str], bool]:
+ return _quark_available
+
+
+def is_fp_quant_available() -> bool:
+ return _fp_quant_available and version.parse(_fp_quant_version) >= version.parse("0.1.6")
+
+
+def is_qutlass_available() -> Union[tuple[bool, str], bool]:
+ return _qutlass_available
+
+
+def is_compressed_tensors_available() -> bool:
+ return _compressed_tensors_available
+
+
+def is_auto_gptq_available() -> Union[tuple[bool, str], bool]:
+ return _auto_gptq_available
+
+
+def is_gptqmodel_available() -> Union[tuple[bool, str], bool]:
+ return _gptqmodel_available
+
+
+def is_eetq_available() -> Union[tuple[bool, str], bool]:
+ return _eetq_available
+
+
+def is_fbgemm_gpu_available() -> Union[tuple[bool, str], bool]:
+ return _fbgemm_gpu_available
+
+
+def is_levenshtein_available() -> Union[tuple[bool, str], bool]:
+ return _levenshtein_available
+
+
+def is_optimum_neuron_available() -> Union[tuple[bool, str], bool]:
+ return _optimum_available and _is_package_available("optimum.neuron")
+
+
+def is_safetensors_available() -> Union[tuple[bool, str], bool]:
+ return _safetensors_available
+
+
+def is_tokenizers_available() -> Union[tuple[bool, str], bool]:
+ return _tokenizers_available
+
+
+@lru_cache
+def is_vision_available() -> bool:
+ _pil_available = importlib.util.find_spec("PIL") is not None
+ if _pil_available:
+ try:
+ package_version = importlib.metadata.version("Pillow")
+ except importlib.metadata.PackageNotFoundError:
+ try:
+ package_version = importlib.metadata.version("Pillow-SIMD")
+ except importlib.metadata.PackageNotFoundError:
+ return False
+ logger.debug(f"Detected PIL version {package_version}")
+ return _pil_available
+
+
+def is_pytesseract_available() -> Union[tuple[bool, str], bool]:
+ return _pytesseract_available
+
+
+def is_pytest_available() -> Union[tuple[bool, str], bool]:
+ return _pytest_available
+
+
+def is_spacy_available() -> Union[tuple[bool, str], bool]:
+ return _spacy_available
+
+
+def is_tensorflow_text_available() -> Union[tuple[bool, str], bool]:
+ return is_tf_available() and _tensorflow_text_available
+
+
+def is_keras_nlp_available() -> Union[tuple[bool, str], bool]:
+ return is_tensorflow_text_available() and _keras_nlp_available
+
+
+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_pytorch_quantization_available() -> Union[tuple[bool, str], bool]:
+ return _pytorch_quantization_available
+
+
+def is_tensorflow_probability_available() -> Union[tuple[bool, str], bool]:
+ return _tensorflow_probability_available
+
+
+def is_pandas_available() -> Union[tuple[bool, str], bool]:
+ return _pandas_available
+
+
+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 _smdistributed_available
+
+
+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 _smdistributed_available
+
+
+def is_training_run_on_sagemaker() -> bool:
+ return "SAGEMAKER_JOB_NAME" in os.environ
+
+
+def is_soundfile_available() -> Union[tuple[bool, str], bool]:
+ return _soundfile_available
+
+
+def is_timm_available() -> Union[tuple[bool, str], bool]:
+ return _timm_available
+
+
+def is_natten_available() -> Union[tuple[bool, str], bool]:
+ return _natten_available
+
+
+def is_nltk_available() -> Union[tuple[bool, str], bool]:
+ return _nltk_available
+
+
+def is_torchaudio_available() -> Union[tuple[bool, str], bool]:
+ return _torchaudio_available
+
+
+def is_torchao_available(min_version: str = TORCHAO_MIN_VERSION) -> bool:
+ return _torchao_available and version.parse(_torchao_version) >= version.parse(min_version)
+
+
+def is_speech_available() -> Union[tuple[bool, str], bool]:
+ # For now this depends on torchaudio but the exact dependency might evolve in the future.
+ return _torchaudio_available
+
+
+def is_spqr_available() -> Union[tuple[bool, str], bool]:
+ return _spqr_available
+
+
+def is_phonemizer_available() -> Union[tuple[bool, str], bool]:
+ return _phonemizer_available
+
+
+def is_uroman_available() -> Union[tuple[bool, str], bool]:
+ return _uroman_available
+
+
+def torch_only_method(fn: Callable) -> Callable:
+ def wrapper(*args, **kwargs):
+ if not _torch_available:
+ raise ImportError(
+ "You need to install pytorch to use this method or class, "
+ "or activate it with environment variables USE_TORCH=1 and USE_TF=0."
+ )
+ else:
+ return fn(*args, **kwargs)
+
+ return wrapper
+
+
+def is_ccl_available() -> bool:
+ return _is_ccl_available
+
+
+def is_sudachi_available() -> bool:
+ return _sudachipy_available
+
+
+def get_sudachi_version() -> bool:
+ return _sudachipy_version
+
+
+def is_sudachi_projection_available() -> bool:
+ if not is_sudachi_available():
+ return False
+
+ # NOTE: We require sudachipy>=0.6.8 to use projection option in sudachi_kwargs for the constructor of BertJapaneseTokenizer.
+ # - `projection` option is not supported in sudachipy<0.6.8, see https://github.com/WorksApplications/sudachi.rs/issues/230
+ return version.parse(_sudachipy_version) >= version.parse("0.6.8")
+
+
+def is_jumanpp_available() -> bool:
+ return (importlib.util.find_spec("rhoknp") is not None) and (shutil.which("jumanpp") is not None)
+
+
+def is_cython_available() -> bool:
+ return importlib.util.find_spec("pyximport") is not None
+
+
+def is_jieba_available() -> Union[tuple[bool, str], bool]:
+ return _jieba_available
+
+
+def is_jinja_available() -> Union[tuple[bool, str], bool]:
+ return _jinja_available
+
+
+def is_mlx_available() -> Union[tuple[bool, str], bool]:
+ return _mlx_available
+
+
+def is_num2words_available() -> Union[tuple[bool, str], bool]:
+ return _num2words_available
+
+
+def is_tiktoken_available() -> Union[tuple[bool, str], bool]:
+ return _tiktoken_available and _blobfile_available
+
+
+def is_liger_kernel_available() -> bool:
+ if not _liger_kernel_available:
+ return False
+
+ return version.parse(importlib.metadata.version("liger_kernel")) >= version.parse("0.3.0")
+
+
+def is_rich_available() -> Union[tuple[bool, str], bool]:
+ return _rich_available
+
+
+def is_matplotlib_available() -> Union[tuple[bool, str], bool]:
+ return _matplotlib_available
+
+
+def is_mistral_common_available() -> Union[tuple[bool, str], bool]:
+ return _mistral_common_available
+
+
+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"
+ )
+
+
+# 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
+PYTORCH_IMPORT_ERROR_WITH_TF = """
+{0} requires the PyTorch library but it was not found in your environment.
+However, we were able to find a TensorFlow installation. TensorFlow classes begin
+with "TF", but are otherwise identically named to our PyTorch classes. This
+means that the TF equivalent of the class you tried to import would be "TF{0}".
+If you want to use TensorFlow, please use TF classes instead!
+
+If you really do want to use PyTorch please go to
+https://pytorch.org/get-started/locally/ and follow the instructions that
+match your environment.
+"""
+
+# docstyle-ignore
+TF_IMPORT_ERROR_WITH_PYTORCH = """
+{0} requires the TensorFlow library but it was not found in your environment.
+However, we were able to find a PyTorch installation. PyTorch classes do not begin
+with "TF", but are otherwise identically named to our TF classes.
+If you want to use PyTorch, please use those classes instead!
+
+If you really do want to use TensorFlow, please follow the instructions on the
+installation page https://www.tensorflow.org/install that match your environment.
+"""
+
+# docstyle-ignore
+BS4_IMPORT_ERROR = """
+{0} requires the Beautiful Soup library but it was not found in your environment. You can install it with pip:
+`pip install beautifulsoup4`. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+SKLEARN_IMPORT_ERROR = """
+{0} requires the scikit-learn library but it was not found in your environment. You can install it with:
+```
+pip install -U scikit-learn
+```
+In a notebook or a colab, you can install it by executing a cell with
+```
+!pip install -U scikit-learn
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+TENSORFLOW_IMPORT_ERROR = """
+{0} requires the TensorFlow library but it was not found in your environment. Check out the instructions on the
+installation page: https://www.tensorflow.org/install and follow the ones that match your environment.
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+DETECTRON2_IMPORT_ERROR = """
+{0} requires the detectron2 library but it was not found in your environment. 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.
+"""
+
+
+# docstyle-ignore
+FLAX_IMPORT_ERROR = """
+{0} requires the FLAX library but it was not found in your environment. Check out the instructions on the
+installation page: https://github.com/google/flax and follow the ones that match your environment.
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+FTFY_IMPORT_ERROR = """
+{0} requires the ftfy library but it was not found in your environment. Check out the instructions on the
+installation section: https://github.com/rspeer/python-ftfy/tree/master#installing and follow the ones
+that match your environment. Please note that you may need to restart your runtime after installation.
+"""
+
+LEVENSHTEIN_IMPORT_ERROR = """
+{0} requires the python-Levenshtein library but it was not found in your environment. You can install it with pip: `pip
+install python-Levenshtein`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+G2P_EN_IMPORT_ERROR = """
+{0} requires the g2p-en library but it was not found in your environment. You can install it with pip:
+`pip install g2p-en`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+PYTORCH_QUANTIZATION_IMPORT_ERROR = """
+{0} requires the pytorch-quantization library but it was not found in your environment. You can install it with pip:
+`pip install pytorch-quantization --extra-index-url https://pypi.ngc.nvidia.com`
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+TENSORFLOW_PROBABILITY_IMPORT_ERROR = """
+{0} requires the tensorflow_probability library but it was not found in your environment. You can install it with pip as
+explained here: https://github.com/tensorflow/probability. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+TENSORFLOW_TEXT_IMPORT_ERROR = """
+{0} requires the tensorflow_text library but it was not found in your environment. You can install it with pip as
+explained here: https://www.tensorflow.org/text/guide/tf_text_intro.
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+TORCHAUDIO_IMPORT_ERROR = """
+{0} requires the torchaudio library but it was not found in your environment. Please install it and restart your
+runtime.
+"""
+
+# docstyle-ignore
+PANDAS_IMPORT_ERROR = """
+{0} requires the pandas library but it was not found in your environment. You can install it with pip as
+explained here: https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html.
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+PHONEMIZER_IMPORT_ERROR = """
+{0} requires the phonemizer library but it was not found in your environment. You can install it with pip:
+`pip install phonemizer`. Please note that you may need to restart your runtime after installation.
+"""
+# docstyle-ignore
+UROMAN_IMPORT_ERROR = """
+{0} requires the uroman library but it was not found in your environment. You can install it with pip:
+`pip install uroman`. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+SACREMOSES_IMPORT_ERROR = """
+{0} requires the sacremoses library but it was not found in your environment. You can install it with pip:
+`pip install sacremoses`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+SCIPY_IMPORT_ERROR = """
+{0} requires the scipy library but it was not found in your environment. You can install it with pip:
+`pip install scipy`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+KERAS_NLP_IMPORT_ERROR = """
+{0} requires the keras_nlp library but it was not found in your environment. You can install it with pip.
+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
+CCL_IMPORT_ERROR = """
+{0} requires the torch ccl library but it was not found in your environment. You can install it with pip:
+`pip install oneccl_bind_pt -f https://developer.intel.com/ipex-whl-stable`
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+ESSENTIA_IMPORT_ERROR = """
+{0} requires essentia library. But that was not found in your environment. You can install them with pip:
+`pip install essentia==2.1b6.dev1034`
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+LIBROSA_IMPORT_ERROR = """
+{0} requires 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.
+"""
+
+JIEBA_IMPORT_ERROR = """
+{0} requires the jieba library but it was not found in your environment. You can install it with pip: `pip install
+jieba`. Please note that you may need to restart your runtime after installation.
+"""
+
+PEFT_IMPORT_ERROR = """
+{0} requires the peft library but it was not found in your environment. You can install it with pip: `pip install
+peft`. Please note that you may need to restart your runtime after installation.
+"""
+
+JINJA_IMPORT_ERROR = """
+{0} requires the jinja library but it was not found in your environment. You can install it with pip: `pip install
+jinja2`. Please note that you may need to restart your runtime after installation.
+"""
+
+RICH_IMPORT_ERROR = """
+{0} requires the rich library but it was not found in your environment. You can install it with pip: `pip install
+rich`. Please note that you may need to restart your runtime after installation.
+"""
+
+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)),
+ ("flax", (is_flax_available, FLAX_IMPORT_ERROR)),
+ ("ftfy", (is_ftfy_available, FTFY_IMPORT_ERROR)),
+ ("g2p_en", (is_g2p_en_available, G2P_EN_IMPORT_ERROR)),
+ ("pandas", (is_pandas_available, PANDAS_IMPORT_ERROR)),
+ ("phonemizer", (is_phonemizer_available, PHONEMIZER_IMPORT_ERROR)),
+ ("uroman", (is_uroman_available, UROMAN_IMPORT_ERROR)),
+ ("pretty_midi", (is_pretty_midi_available, PRETTY_MIDI_IMPORT_ERROR)),
+ ("levenshtein", (is_levenshtein_available, LEVENSHTEIN_IMPORT_ERROR)),
+ ("librosa", (is_librosa_available, LIBROSA_IMPORT_ERROR)),
+ ("protobuf", (is_protobuf_available, PROTOBUF_IMPORT_ERROR)),
+ ("pyctcdecode", (is_pyctcdecode_available, PYCTCDECODE_IMPORT_ERROR)),
+ ("pytesseract", (is_pytesseract_available, PYTESSERACT_IMPORT_ERROR)),
+ ("sacremoses", (is_sacremoses_available, SACREMOSES_IMPORT_ERROR)),
+ ("pytorch_quantization", (is_pytorch_quantization_available, PYTORCH_QUANTIZATION_IMPORT_ERROR)),
+ ("sentencepiece", (is_sentencepiece_available, SENTENCEPIECE_IMPORT_ERROR)),
+ ("sklearn", (is_sklearn_available, SKLEARN_IMPORT_ERROR)),
+ ("speech", (is_speech_available, SPEECH_IMPORT_ERROR)),
+ ("tensorflow_probability", (is_tensorflow_probability_available, TENSORFLOW_PROBABILITY_IMPORT_ERROR)),
+ ("tf", (is_tf_available, TENSORFLOW_IMPORT_ERROR)),
+ ("tensorflow_text", (is_tensorflow_text_available, TENSORFLOW_TEXT_IMPORT_ERROR)),
+ ("timm", (is_timm_available, TIMM_IMPORT_ERROR)),
+ ("torchaudio", (is_torchaudio_available, TORCHAUDIO_IMPORT_ERROR)),
+ ("natten", (is_natten_available, NATTEN_IMPORT_ERROR)),
+ ("nltk", (is_nltk_available, NLTK_IMPORT_ERROR)),
+ ("tokenizers", (is_tokenizers_available, TOKENIZERS_IMPORT_ERROR)),
+ ("torch", (is_torch_available, PYTORCH_IMPORT_ERROR)),
+ ("torchvision", (is_torchvision_available, TORCHVISION_IMPORT_ERROR)),
+ ("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)),
+ ("oneccl_bind_pt", (is_ccl_available, CCL_IMPORT_ERROR)),
+ ("cython", (is_cython_available, CYTHON_IMPORT_ERROR)),
+ ("jieba", (is_jieba_available, JIEBA_IMPORT_ERROR)),
+ ("peft", (is_peft_available, PEFT_IMPORT_ERROR)),
+ ("jinja", (is_jinja_available, JINJA_IMPORT_ERROR)),
+ ("yt_dlp", (is_yt_dlp_available, YT_DLP_IMPORT_ERROR)),
+ ("rich", (is_rich_available, RICH_IMPORT_ERROR)),
+ ("keras_nlp", (is_keras_nlp_available, KERAS_NLP_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):
+ if not isinstance(backends, (list, tuple)):
+ backends = [backends]
+
+ name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
+
+ # Raise an error for users who might not realize that classes without "TF" are torch-only
+ if "torch" in backends and "tf" not in backends and not is_torch_available() and is_tf_available():
+ raise ImportError(PYTORCH_IMPORT_ERROR_WITH_TF.format(name))
+
+ # Raise the inverse error for PyTorch users trying to load TF classes
+ if "tf" in backends and "torch" not in backends and is_torch_available() and not is_tf_available():
+ raise ImportError(TF_IMPORT_ERROR_WITH_PYTORCH.format(name))
+
+ 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)
+
+
+def is_torch_fx_proxy(x):
+ if is_torch_fx_available():
+ import torch.fx
+
+ return isinstance(x, torch.fx.Proxy)
+ return False
+
+
+BACKENDS_T = frozenset[str]
+IMPORT_STRUCTURE_T = dict[BACKENDS_T, dict[str, set[str]]]
+
+
+class _LazyModule(ModuleType):
+ """
+ Module class that surfaces all objects but only performs associated imports when the objects are requested.
+ """
+
+ # Very heavily inspired by optuna.integration._IntegrationModule
+ # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py
+ def __init__(
+ self,
+ name: str,
+ module_file: str,
+ import_structure: IMPORT_STRUCTURE_T,
+ module_spec: Optional[importlib.machinery.ModuleSpec] = None,
+ extra_objects: Optional[dict[str, object]] = None,
+ explicit_import_shortcut: Optional[dict[str, list[str]]] = 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 (importlib.metadata.PackageNotFoundError, 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 = 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) as e:
+ 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:
+ value = None
+ for key, values in self._explicit_import_shortcut.items():
+ if name in values:
+ value = self._get_module(key)
+
+ 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])
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ module = sys.modules[name]
+ return module
+
+
+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.value,
+ "==": VersionComparison.EQUAL.value,
+ "!=": VersionComparison.NOT_EQUAL.value,
+ ">": VersionComparison.GREATER_THAN.value,
+ "<": VersionComparison.LESS_THAN.value,
+ ">=": VersionComparison.GREATER_THAN_OR_EQUAL.value,
+ "<=": VersionComparison.LESS_THAN_OR_EQUAL.value,
+ }
+
+ 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 is_satisfied(self) -> bool:
+ return VersionComparison.from_string(self.version_comparison)(
+ version.parse(importlib.metadata.version(self.package_name)), 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_tf_" in e: ("tf",),
+ lambda e: "modeling_flax_" in e: ("flax",),
+ lambda e: "modeling_" in e: ("torch",),
+ lambda e: e.startswith("tokenization_") and e.endswith("_fast"): ("tokenizers",),
+ lambda e: e.startswith("image_processing_") and e.endswith("_fast"): ("vision", "torch", "torchvision"),
+ lambda e: e.startswith("image_processing_"): ("vision",),
+}
+
+
+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 `modeling_tf_*.py`, it will have a `tf` backend
+ - If a file is named like `modeling_flax_*.py`, it will have a `flax` backend
+ - If a file is named like `tokenization_*_fast.py`, it will have a `tokenizers` backend
+ - 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', 'AlbertOnnxConfig'}
+ },
+ frozenset({'tokenizers'}): {
+ 'tokenization_albert_fast': {'AlbertTokenizerFast'}
+ },
+ },
+ 'align': {
+ frozenset(): {
+ 'configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
+ 'processing_align': {'AlignProcessor'}
+ },
+ },
+ 'altclip': {
+ frozenset(): {
+ 'configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
+ 'processing_altclip': {'AltCLIPProcessor'},
+ }
+ }
+ }
+ """
+ import_structure = {}
+
+ if os.path.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_tf_xxx.py`
+ # should have TensorFlow as a required backend.
+ base_requirements = ()
+ for string_check, requirements in BASE_FILE_REQUIREMENTS.items():
+ if string_check(module_name):
+ base_requirements = requirements
+ break
+
+ # Objects that have a `@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",
+ # "tf",
+ # )
+ # )
+ #
+ # or
+ #
+ # @export(
+ # backends=(
+ # "sentencepiece", "tf"
+ # )
+ # )
+ elif "backends" in lines[previous_index + 1]:
+ backends = []
+ for backend_line in lines[previous_index:index]:
+ if "backends" in backend_line:
+ backend_line = backend_line.split("=")[1]
+ if '"' in backend_line or "'" in backend_line:
+ if ", " in backend_line:
+ backends.extend(backend.strip("()\"', ") for backend in backend_line.split(", "))
+ else:
+ backends.append(backend_line.strip("()\"', "))
+
+ # If the line is only a ')', then we reached the end of the backends and we break.
+ if backend_line.strip() == ")":
+ break
+ backends = tuple(backends)
+
+ # No backends are registered for export
+ else:
+ backends = ()
+
+ backends = frozenset(backends + base_requirements)
+ if backends not in module_requirements:
+ module_requirements[backends] = {}
+ if module_name not in module_requirements[backends]:
+ module_requirements[backends][module_name] = set()
+
+ if not line.startswith("class") and not line.startswith("def"):
+ skip_line = True
+ else:
+ start_index = 6 if line.startswith("class") else 4
+ object_name = line[start_index:].split("(")[0].strip(":")
+ module_requirements[backends][module_name].add(object_name)
+ exported_objects.add(object_name)
+
+ if not skip_line:
+ previous_line = line
+ previous_index = index
+
+ # All objects that are in __all__ should be exported by default.
+ # These objects are exported with the file backends.
+ if "__all__" in file_content:
+ for _all_object in fetch__all__(file_content):
+ if _all_object not in exported_objects:
+ backends = frozenset(base_requirements)
+ if backends not in module_requirements:
+ module_requirements[backends] = {}
+ if module_name not in module_requirements[backends]:
+ module_requirements[backends][module_name] = set()
+
+ module_requirements[backends][module_name].add(_all_object)
+
+ import_structure = {**module_requirements, **import_structure}
+ return import_structure
+
+
+def spread_import_structure(nested_import_structure):
+ """
+ This method takes as input an unordered import structure and brings the required backends at the top-level,
+ aggregating modules and objects under their required backends.
+
+ Here's an example of an input import structure at the src.transformers.models level:
+
+ {
+ 'albert': {
+ frozenset(): {
+ 'configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'}
+ },
+ frozenset({'tokenizers'}): {
+ 'tokenization_albert_fast': {'AlbertTokenizerFast'}
+ },
+ },
+ 'align': {
+ frozenset(): {
+ 'configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
+ 'processing_align': {'AlignProcessor'}
+ },
+ },
+ 'altclip': {
+ frozenset(): {
+ 'configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
+ 'processing_altclip': {'AltCLIPProcessor'},
+ }
+ }
+ }
+
+ Here's an example of an output import structure at the src.transformers.models level:
+
+ {
+ frozenset({'tokenizers'}): {
+ 'albert.tokenization_albert_fast': {'AlbertTokenizerFast'}
+ },
+ frozenset(): {
+ 'albert.configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'},
+ 'align.processing_align': {'AlignProcessor'},
+ 'align.configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
+ 'altclip.configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
+ 'altclip.processing_altclip': {'AltCLIPProcessor'}
+ }
+ }
+
+ """
+
+ def propagate_frozenset(unordered_import_structure):
+ 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: Optional[str] = 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': {'AlbertTokenizerFast'}
+ },
+ frozenset(): {
+ 'albert.configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'},
+ 'align.processing_align': {'AlignProcessor'},
+ 'align.configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
+ 'altclip.configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
+ 'altclip.processing_altclip': {'AltCLIPProcessor'}
+ }
+ }
+
+ The import structure is a dict defined with frozensets as keys, and dicts of strings to sets of objects.
+
+ 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/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/logging.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..88a6a9769f65cc8d027059088cb02828e2fa13e8
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/logging.py
@@ -0,0 +1,409 @@
+# Copyright 2020 Optuna, Hugging Face
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Logging utilities."""
+
+import functools
+import logging
+import os
+import sys
+import threading
+from logging import (
+ CRITICAL, # NOQA
+ DEBUG, # NOQA
+ ERROR, # NOQA
+ FATAL, # NOQA
+ INFO, # NOQA
+ NOTSET, # NOQA
+ WARN, # NOQA
+ WARNING, # NOQA
+)
+from logging import captureWarnings as _captureWarnings
+from typing import Optional
+
+import huggingface_hub.utils as hf_hub_utils
+from tqdm import auto as tqdm_lib
+
+
+_lock = threading.Lock()
+_default_handler: Optional[logging.Handler] = None
+
+log_levels = {
+ "detail": logging.DEBUG, # will also print filename and line number
+ "debug": logging.DEBUG,
+ "info": logging.INFO,
+ "warning": logging.WARNING,
+ "error": logging.ERROR,
+ "critical": logging.CRITICAL,
+}
+
+_default_log_level = logging.WARNING
+
+_tqdm_active = not hf_hub_utils.are_progress_bars_disabled()
+
+
+def _get_default_logging_level():
+ """
+ If TRANSFORMERS_VERBOSITY env var is set to one of the valid choices return that as the new default level. If it is
+ not - fall back to `_default_log_level`
+ """
+ env_level_str = os.getenv("TRANSFORMERS_VERBOSITY", None)
+ if env_level_str:
+ if env_level_str in log_levels:
+ return log_levels[env_level_str]
+ else:
+ logging.getLogger().warning(
+ f"Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, "
+ f"has to be one of: {', '.join(log_levels.keys())}"
+ )
+ return _default_log_level
+
+
+def _get_library_name() -> str:
+ return __name__.split(".")[0]
+
+
+def _get_library_root_logger() -> logging.Logger:
+ return logging.getLogger(_get_library_name())
+
+
+def _configure_library_root_logger() -> None:
+ global _default_handler
+
+ with _lock:
+ if _default_handler:
+ # This library has already configured the library root logger.
+ return
+ _default_handler = logging.StreamHandler() # Set sys.stderr as stream.
+ # set defaults based on https://github.com/pyinstaller/pyinstaller/issues/7334#issuecomment-1357447176
+ if sys.stderr is None:
+ sys.stderr = open(os.devnull, "w")
+
+ _default_handler.flush = sys.stderr.flush
+
+ # Apply our default configuration to the library root logger.
+ library_root_logger = _get_library_root_logger()
+ library_root_logger.addHandler(_default_handler)
+ library_root_logger.setLevel(_get_default_logging_level())
+ # if logging level is debug, we add pathname and lineno to formatter for easy debugging
+ if os.getenv("TRANSFORMERS_VERBOSITY", None) == "detail":
+ formatter = logging.Formatter("[%(levelname)s|%(pathname)s:%(lineno)s] %(asctime)s >> %(message)s")
+ _default_handler.setFormatter(formatter)
+
+ is_ci = os.getenv("CI") is not None and os.getenv("CI").upper() in {"1", "ON", "YES", "TRUE"}
+ library_root_logger.propagate = 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: Optional[str] = None) -> logging.Logger:
+ """
+ Return a logger with the specified name.
+
+ This function is not supposed to be directly accessed unless you are writing a custom transformers module.
+ """
+
+ if name is None:
+ name = _get_library_name()
+
+ _configure_library_root_logger()
+ return logging.getLogger(name)
+
+
+def get_verbosity() -> int:
+ """
+ Return the current level for the 🤗 Transformers's root logger as an int.
+
+ Returns:
+ `int`: The logging level.
+
+
+
+ 🤗 Transformers has following logging levels:
+
+ - 50: `transformers.logging.CRITICAL` or `transformers.logging.FATAL`
+ - 40: `transformers.logging.ERROR`
+ - 30: `transformers.logging.WARNING` or `transformers.logging.WARN`
+ - 20: `transformers.logging.INFO`
+ - 10: `transformers.logging.DEBUG`
+
+ """
+
+ _configure_library_root_logger()
+ return _get_library_root_logger().getEffectiveLevel()
+
+
+def set_verbosity(verbosity: int) -> None:
+ """
+ Set the verbosity level for the 🤗 Transformers's root logger.
+
+ Args:
+ verbosity (`int`):
+ Logging level, e.g., one of:
+
+ - `transformers.logging.CRITICAL` or `transformers.logging.FATAL`
+ - `transformers.logging.ERROR`
+ - `transformers.logging.WARNING` or `transformers.logging.WARN`
+ - `transformers.logging.INFO`
+ - `transformers.logging.DEBUG`
+ """
+
+ _configure_library_root_logger()
+ _get_library_root_logger().setLevel(verbosity)
+
+
+def set_verbosity_info():
+ """Set the verbosity to the `INFO` level."""
+ return set_verbosity(INFO)
+
+
+def set_verbosity_warning():
+ """Set the verbosity to the `WARNING` level."""
+ return set_verbosity(WARNING)
+
+
+def set_verbosity_debug():
+ """Set the verbosity to the `DEBUG` level."""
+ return set_verbosity(DEBUG)
+
+
+def set_verbosity_error():
+ """Set the verbosity to the `ERROR` level."""
+ return set_verbosity(ERROR)
+
+
+def disable_default_handler() -> None:
+ """Disable the default handler of the HuggingFace Transformers's root logger."""
+
+ _configure_library_root_logger()
+
+ assert _default_handler is not None
+ _get_library_root_logger().removeHandler(_default_handler)
+
+
+def enable_default_handler() -> None:
+ """Enable the default handler of the HuggingFace Transformers's root logger."""
+
+ _configure_library_root_logger()
+
+ assert _default_handler is not None
+ _get_library_root_logger().addHandler(_default_handler)
+
+
+def add_handler(handler: logging.Handler) -> None:
+ """adds a handler to the HuggingFace Transformers's root logger."""
+
+ _configure_library_root_logger()
+
+ assert handler is not None
+ _get_library_root_logger().addHandler(handler)
+
+
+def remove_handler(handler: logging.Handler) -> None:
+ """removes given handler from the HuggingFace Transformers's root logger."""
+
+ _configure_library_root_logger()
+
+ assert handler is not None and handler not in _get_library_root_logger().handlers
+ _get_library_root_logger().removeHandler(handler)
+
+
+def disable_propagation() -> None:
+ """
+ Disable propagation of the library log outputs. Note that log propagation is disabled by default.
+ """
+
+ _configure_library_root_logger()
+ _get_library_root_logger().propagate = False
+
+
+def enable_propagation() -> None:
+ """
+ Enable propagation of the library log outputs. Please disable the HuggingFace Transformers's default handler to
+ prevent double logging if the root logger has been configured.
+ """
+
+ _configure_library_root_logger()
+ _get_library_root_logger().propagate = True
+
+
+def enable_explicit_format() -> None:
+ """
+ Enable explicit formatting for every HuggingFace Transformers's logger. The explicit formatter is as follows:
+ ```
+ [LEVELNAME|FILENAME|LINE NUMBER] TIME >> MESSAGE
+ ```
+ All handlers currently bound to the root logger are affected by this method.
+ """
+ handlers = _get_library_root_logger().handlers
+
+ for handler in handlers:
+ formatter = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s")
+ handler.setFormatter(formatter)
+
+
+def reset_format() -> None:
+ """
+ Resets the formatting for HuggingFace Transformers's loggers.
+
+ All handlers currently bound to the root logger are affected by this method.
+ """
+ handlers = _get_library_root_logger().handlers
+
+ for handler in handlers:
+ handler.setFormatter(None)
+
+
+def warning_advice(self, *args, **kwargs):
+ """
+ This method is identical to `logger.warning()`, but if env var TRANSFORMERS_NO_ADVISORY_WARNINGS=1 is set, this
+ warning will not be printed
+ """
+ no_advisory_warnings = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS")
+ if no_advisory_warnings:
+ return
+ self.warning(*args, **kwargs)
+
+
+logging.Logger.warning_advice = warning_advice
+
+
+@functools.lru_cache(None)
+def warning_once(self, *args, **kwargs):
+ """
+ This method is identical to `logger.warning()`, but will emit the warning with the same message only once
+
+ Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the cache.
+ The assumption here is that all warning messages are unique across the code. If they aren't then need to switch to
+ another type of cache that includes the caller frame information in the hashing function.
+ """
+ self.warning(*args, **kwargs)
+
+
+logging.Logger.warning_once = warning_once
+
+
+@functools.lru_cache(None)
+def info_once(self, *args, **kwargs):
+ """
+ This method is identical to `logger.info()`, but will emit the info with the same message only once
+
+ Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the cache.
+ The assumption here is that all warning messages are unique across the code. If they aren't then need to switch to
+ another type of cache that includes the caller frame information in the hashing function.
+ """
+ self.info(*args, **kwargs)
+
+
+logging.Logger.info_once = info_once
+
+
+class EmptyTqdm:
+ """Dummy tqdm which doesn't do anything."""
+
+ def __init__(self, *args, **kwargs): # pylint: disable=unused-argument
+ self._iterator = args[0] if args else None
+
+ def __iter__(self):
+ return iter(self._iterator)
+
+ def __getattr__(self, _):
+ """Return empty function."""
+
+ def empty_fn(*args, **kwargs): # pylint: disable=unused-argument
+ return
+
+ return empty_fn
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, type_, value, traceback):
+ return
+
+
+class _tqdm_cls:
+ def __call__(self, *args, **kwargs):
+ if _tqdm_active:
+ return tqdm_lib.tqdm(*args, **kwargs)
+ else:
+ return EmptyTqdm(*args, **kwargs)
+
+ def set_lock(self, *args, **kwargs):
+ self._lock = None
+ if _tqdm_active:
+ return tqdm_lib.tqdm.set_lock(*args, **kwargs)
+
+ def get_lock(self):
+ if _tqdm_active:
+ return tqdm_lib.tqdm.get_lock()
+
+
+tqdm = _tqdm_cls()
+
+
+def is_progress_bar_enabled() -> bool:
+ """Return a boolean indicating whether tqdm progress bars are enabled."""
+ 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/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/metrics.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/metrics.py
new file mode 100644
index 0000000000000000000000000000000000000000..114abd8400e0e24f90a8a216bb2450a170887eb1
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/metrics.py
@@ -0,0 +1,416 @@
+import functools
+import logging
+import time
+from enum import Enum
+from typing import Any, Callable, Optional, Union
+
+import torch
+
+
+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"
+
+
+try:
+ from opentelemetry import metrics
+ from opentelemetry.trace import Status, StatusCode, get_tracer
+
+ _has_opentelemetry = True
+except ImportError:
+ _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: Optional[list[tuple[str, str, Union[Any, Callable[[Any], Any]]]]] = 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
+
+ import functools
+
+ @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.")
+ 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:
+ # Calculate memory usage based on cache configuration
+ num_used_blocks = cache.num_blocks - len(cache._free_blocks)
+ num_layers = len(cache.key_cache)
+
+ # Each used block stores key and value states
+ # Each with shape: (num_kv_heads, block_size, head_dim)
+ bytes_per_parameter = 2 if cache.dtype in [torch.float16, torch.bfloat16] else 4 # Size in bytes
+
+ # Total bytes = num_layers * num_used_blocks * block_size *
+ # num_kv_heads * head_dim * 2 (both K and V) * bytes_per_parameter
+ memory_bytes = (
+ num_layers
+ * num_used_blocks
+ * cache.block_size
+ * cache.num_key_value_heads
+ * cache.head_dim
+ * 2 # For both key and value caches
+ * bytes_per_parameter
+ )
+
+ free_memory_bytes = (
+ num_layers
+ * len(cache._free_blocks)
+ * cache.block_size
+ * cache.num_key_value_heads
+ * cache.head_dim
+ * 2 # For both key and value caches
+ * bytes_per_parameter
+ )
+
+ self.kv_cache_memory_gauge.set(memory_bytes)
+ self.kv_cache_free_memory_gauge.set(free_memory_bytes)
+ logger.debug(
+ f"KV Cache memory: {memory_bytes / (1024 * 1024):.2f}MB, "
+ f"Used blocks: {num_used_blocks}/{cache.num_blocks} "
+ f"({num_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/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/model_parallel_utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/model_parallel_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..7db16b70a75ccdce7bd9c07c5dfc99f42e5c8807
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/model_parallel_utils.py
@@ -0,0 +1,55 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from math import ceil
+
+
+def assert_device_map(device_map, num_blocks):
+ blocks = list(range(0, num_blocks))
+
+ device_map_blocks = [item for sublist in list(device_map.values()) for item in sublist]
+
+ # Duplicate check
+ duplicate_blocks = []
+ for i in device_map_blocks:
+ if device_map_blocks.count(i) > 1 and i not in duplicate_blocks:
+ duplicate_blocks.append(i)
+ # Missing blocks
+ missing_blocks = [i for i in blocks if i not in device_map_blocks]
+ extra_blocks = [i for i in device_map_blocks if i not in blocks]
+
+ if len(duplicate_blocks) != 0:
+ raise ValueError(
+ "Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device."
+ " These attention blocks were specified more than once: " + str(duplicate_blocks)
+ )
+ if len(missing_blocks) != 0:
+ raise ValueError(
+ "There are attention blocks for this model that are not specified in the device_map. Add these attention "
+ "blocks to a device on the device_map: " + str(missing_blocks)
+ )
+ if len(extra_blocks) != 0:
+ raise ValueError(
+ "The device_map contains more attention blocks than this model has. Remove these from the device_map:"
+ + str(extra_blocks)
+ )
+
+
+def get_device_map(n_layers, devices):
+ """Returns a dictionary of layers distributed evenly across all devices."""
+ layers = list(range(n_layers))
+ n_blocks = int(ceil(n_layers / len(devices)))
+ layers_list = [layers[i : i + n_blocks] for i in range(0, n_layers, n_blocks)]
+
+ return dict(zip(devices, layers_list))
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/notebook.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/notebook.py
new file mode 100644
index 0000000000000000000000000000000000000000..397aa3e3ff044dbfdb869ff1166cf45f1861216f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/notebook.py
@@ -0,0 +1,383 @@
+# Copyright 2020 Hugging Face
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import re
+import time
+from typing import Optional
+
+import IPython.display as disp
+
+from ..trainer_callback import TrainerCallback
+from ..trainer_utils import IntervalStrategy, has_length
+
+
+def format_time(t):
+ "Format `t` (in seconds) to (h):mm:ss"
+ t = int(t)
+ h, m, s = t // 3600, (t // 60) % 60, t % 60
+ return f"{h}:{m:02d}:{s:02d}" if h != 0 else f"{m:02d}:{s:02d}"
+
+
+def html_progress_bar(value, total, prefix, label, width=300):
+ # docstyle-ignore
+ return f"""
+
+ """
+
+
+def text_to_html_table(items):
+ "Put the texts in `items` in an HTML table."
+ html_code = """\n"""
+ html_code += """ \n \n"""
+ for i in items[0]:
+ html_code += f" | {i} | \n"
+ html_code += "
\n \n \n"
+ for line in items[1:]:
+ html_code += " \n"
+ for elt in line:
+ elt = f"{elt:.6f}" if isinstance(elt, float) else str(elt)
+ html_code += f" | {elt} | \n"
+ html_code += "
\n"
+ html_code += " \n
"
+ return html_code
+
+
+class NotebookProgressBar:
+ """
+ A progress par for display in a notebook.
+
+ Class attributes (overridden by derived classes)
+
+ - **warmup** (`int`) -- The number of iterations to do at the beginning while ignoring `update_every`.
+ - **update_every** (`float`) -- Since calling the time takes some time, we only do it every presumed
+ `update_every` seconds. The progress bar uses the average time passed up until now to guess the next value
+ for which it will call the update.
+
+ Args:
+ total (`int`):
+ The total number of iterations to reach.
+ prefix (`str`, *optional*):
+ A prefix to add before the progress bar.
+ leave (`bool`, *optional*, defaults to `True`):
+ Whether or not to leave the progress bar once it's completed. You can always call the
+ [`~utils.notebook.NotebookProgressBar.close`] method to make the bar disappear.
+ parent ([`~notebook.NotebookTrainingTracker`], *optional*):
+ A parent object (like [`~utils.notebook.NotebookTrainingTracker`]) that spawns progress bars and handle
+ their display. If set, the object passed must have a `display()` method.
+ width (`int`, *optional*, defaults to 300):
+ The width (in pixels) that the bar will take.
+
+ Example:
+
+ ```python
+ import time
+
+ pbar = NotebookProgressBar(100)
+ for val in range(100):
+ pbar.update(val)
+ time.sleep(0.07)
+ pbar.update(100)
+ ```"""
+
+ warmup = 5
+ update_every = 0.2
+
+ def __init__(
+ self,
+ total: int,
+ prefix: Optional[str] = None,
+ leave: bool = True,
+ parent: Optional["NotebookTrainingTracker"] = None,
+ width: int = 300,
+ ):
+ self.total = total
+ self.prefix = "" if prefix is None else prefix
+ self.leave = leave
+ self.parent = parent
+ self.width = width
+ self.last_value = None
+ self.comment = None
+ self.output = None
+ self.value = None
+ self.label = None
+ if "VSCODE_PID" in os.environ:
+ self.update_every = 0.5 # Adjusted for smooth updated as html rending is slow on VS Code
+ # This is the only adjustment required to optimize training html rending
+
+ def update(self, value: int, force_update: bool = False, comment: Optional[str] = None):
+ """
+ The main method to update the progress bar to `value`.
+
+ Args:
+ value (`int`):
+ The value to use. Must be between 0 and `total`.
+ force_update (`bool`, *optional*, defaults to `False`):
+ Whether or not to force and update of the internal state and display (by default, the bar will wait for
+ `value` to reach the value it predicted corresponds to a time of more than the `update_every` attribute
+ since the last update to avoid adding boilerplate).
+ comment (`str`, *optional*):
+ A comment to add on the left of the progress bar.
+ """
+ self.value = value
+ if comment is not None:
+ self.comment = comment
+ if self.last_value is None:
+ self.start_time = self.last_time = time.time()
+ self.start_value = self.last_value = value
+ self.elapsed_time = self.predicted_remaining = None
+ self.first_calls = self.warmup
+ self.wait_for = 1
+ self.update_bar(value)
+ elif value <= self.last_value and not force_update:
+ return
+ elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for, self.total):
+ if self.first_calls > 0:
+ self.first_calls -= 1
+ current_time = time.time()
+ self.elapsed_time = current_time - self.start_time
+ # We could have value = self.start_value if the update is called twixe with the same start value.
+ if value > self.start_value:
+ self.average_time_per_item = self.elapsed_time / (value - self.start_value)
+ else:
+ self.average_time_per_item = None
+ if value >= self.total:
+ value = self.total
+ self.predicted_remaining = None
+ if not self.leave:
+ self.close()
+ elif self.average_time_per_item is not None:
+ self.predicted_remaining = self.average_time_per_item * (self.total - value)
+ self.update_bar(value)
+ self.last_value = value
+ self.last_time = current_time
+ if (self.average_time_per_item is None) or (self.average_time_per_item == 0):
+ self.wait_for = 1
+ else:
+ self.wait_for = max(int(self.update_every / self.average_time_per_item), 1)
+
+ def update_bar(self, value, comment=None):
+ spaced_value = " " * (len(str(self.total)) - len(str(value))) + str(value)
+ if self.elapsed_time is None:
+ self.label = f"[{spaced_value}/{self.total} : < :"
+ elif self.predicted_remaining is None:
+ self.label = f"[{spaced_value}/{self.total} {format_time(self.elapsed_time)}"
+ else:
+ self.label = (
+ f"[{spaced_value}/{self.total} {format_time(self.elapsed_time)} <"
+ f" {format_time(self.predicted_remaining)}"
+ )
+ if self.average_time_per_item == 0:
+ self.label += ", +inf it/s"
+ else:
+ self.label += f", {1 / self.average_time_per_item:.2f} it/s"
+
+ self.label += "]" if self.comment is None or len(self.comment) == 0 else f", {self.comment}]"
+ self.display()
+
+ def display(self):
+ self.html_code = html_progress_bar(self.value, self.total, self.prefix, self.label, self.width)
+ if self.parent is not None:
+ # If this is a child bar, the parent will take care of the display.
+ self.parent.display()
+ return
+ if self.output is None:
+ self.output = disp.display(disp.HTML(self.html_code), display_id=True)
+ else:
+ self.output.update(disp.HTML(self.html_code))
+
+ def close(self):
+ "Closes the progress bar."
+ if self.parent is None and self.output is not None:
+ self.output.update(disp.HTML(""))
+
+
+class NotebookTrainingTracker(NotebookProgressBar):
+ """
+ An object tracking the updates of an ongoing training with progress bars and a nice table reporting metrics.
+
+ Args:
+ num_steps (`int`): The number of steps during training. column_names (`list[str]`, *optional*):
+ The list of column names for the metrics table (will be inferred from the first call to
+ [`~utils.notebook.NotebookTrainingTracker.write_line`] if not set).
+ """
+
+ def __init__(self, num_steps, column_names=None):
+ super().__init__(num_steps)
+ self.inner_table = None if column_names is None else [column_names]
+ self.child_bar = None
+
+ def display(self):
+ self.html_code = html_progress_bar(self.value, self.total, self.prefix, self.label, self.width)
+ if self.inner_table is not None:
+ self.html_code += text_to_html_table(self.inner_table)
+ if self.child_bar is not None:
+ self.html_code += self.child_bar.html_code
+ if self.output is None:
+ self.output = disp.display(disp.HTML(self.html_code), display_id=True)
+ else:
+ self.output.update(disp.HTML(self.html_code))
+
+ def write_line(self, values):
+ """
+ Write the values in the inner table.
+
+ Args:
+ values (`dict[str, float]`): The values to display.
+ """
+ if self.inner_table is None:
+ self.inner_table = [list(values.keys()), list(values.values())]
+ else:
+ columns = self.inner_table[0]
+ for key in values:
+ 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}"
+ self.training_tracker.update(
+ state.global_step + 1,
+ comment=f"Epoch {epoch}/{state.num_train_epochs}",
+ force_update=self._force_next_update,
+ )
+ self._force_next_update = False
+
+ def on_prediction_step(self, args, state, control, eval_dataloader=None, **kwargs):
+ if not has_length(eval_dataloader):
+ return
+ if self.prediction_bar is None:
+ if self.training_tracker is not None:
+ self.prediction_bar = self.training_tracker.add_child(len(eval_dataloader))
+ else:
+ self.prediction_bar = NotebookProgressBar(len(eval_dataloader))
+ self.prediction_bar.update(1)
+ else:
+ self.prediction_bar.update(self.prediction_bar.value + 1)
+
+ def on_predict(self, args, state, control, **kwargs):
+ if self.prediction_bar is not None:
+ self.prediction_bar.close()
+ self.prediction_bar = None
+
+ def on_log(self, args, state, control, logs=None, **kwargs):
+ # Only for when there is no evaluation
+ if args.eval_strategy == IntervalStrategy.NO and "loss" in logs:
+ values = {"Training Loss": logs["loss"]}
+ # First column is necessarily Step sine we're not in epoch eval strategy
+ values["Step"] = state.global_step
+ self.training_tracker.write_line(values)
+
+ def on_evaluate(self, args, state, control, metrics=None, **kwargs):
+ if self.training_tracker is not None:
+ values = {"Training Loss": "No log", "Validation Loss": "No log"}
+ for log in reversed(state.log_history):
+ if "loss" in log:
+ values["Training Loss"] = log["loss"]
+ break
+
+ if self.first_column == "Epoch":
+ values["Epoch"] = int(state.epoch)
+ else:
+ values["Step"] = state.global_step
+ metric_key_prefix = "eval"
+ for k in metrics:
+ if k.endswith("_loss"):
+ metric_key_prefix = re.sub(r"\_loss$", "", k)
+ _ = metrics.pop("total_flos", None)
+ _ = metrics.pop("epoch", None)
+ _ = metrics.pop(f"{metric_key_prefix}_runtime", None)
+ _ = metrics.pop(f"{metric_key_prefix}_samples_per_second", None)
+ _ = metrics.pop(f"{metric_key_prefix}_steps_per_second", None)
+ _ = metrics.pop(f"{metric_key_prefix}_jit_compilation_time", None)
+ for k, v in metrics.items():
+ splits = k.split("_")
+ name = " ".join([part.capitalize() for part in splits[1:]])
+ if name == "Loss":
+ # Single dataset
+ name = "Validation Loss"
+ values[name] = v
+ self.training_tracker.write_line(values)
+ self.training_tracker.remove_child()
+ self.prediction_bar = None
+ # Evaluation takes a long time so we should force the next update.
+ self._force_next_update = True
+
+ def on_train_end(self, args, state, control, **kwargs):
+ self.training_tracker.update(
+ state.global_step,
+ comment=f"Epoch {int(state.epoch)}/{state.num_train_epochs}",
+ force_update=True,
+ )
+ self.training_tracker = None
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/peft_utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/peft_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3976acf168bee27583aa18510c1f0b28aeba00e
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/peft_utils.py
@@ -0,0 +1,125 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import importlib
+import os
+from typing import Optional, Union
+
+from packaging import version
+
+from .hub import cached_file
+from .import_utils import is_peft_available
+
+
+ADAPTER_CONFIG_NAME = "adapter_config.json"
+ADAPTER_WEIGHTS_NAME = "adapter_model.bin"
+ADAPTER_SAFE_WEIGHTS_NAME = "adapter_model.safetensors"
+
+
+def find_adapter_config_file(
+ model_id: str,
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
+ force_download: bool = False,
+ resume_download: Optional[bool] = None,
+ proxies: Optional[dict[str, str]] = None,
+ token: Optional[Union[bool, str]] = None,
+ revision: Optional[str] = None,
+ local_files_only: bool = False,
+ subfolder: str = "",
+ _commit_hash: Optional[str] = None,
+) -> Optional[str]:
+ r"""
+ Simply checks if the model stored on the Hub or locally is an adapter model or not, return the path of the adapter
+ config file if it is, None otherwise.
+
+ Args:
+ model_id (`str`):
+ The identifier of the model to look for, can be either a local path or an id to the repository on the Hub.
+ cache_dir (`str` or `os.PathLike`, *optional*):
+ Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
+ cache should not be used.
+ force_download (`bool`, *optional*, defaults to `False`):
+ Whether or not to force to (re-)download the configuration files and override the cached versions if they
+ exist.
+ resume_download:
+ Deprecated and ignored. All downloads are now resumed by default when possible.
+ Will be removed in v5 of Transformers.
+ proxies (`dict[str, str]`, *optional*):
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
+ 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
+ token (`str` or *bool*, *optional*):
+ The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
+ when running `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,
+ resume_download=resume_download,
+ proxies=proxies,
+ token=token,
+ revision=revision,
+ local_files_only=local_files_only,
+ subfolder=subfolder,
+ _commit_hash=_commit_hash,
+ _raise_exceptions_for_gated_repo=False,
+ _raise_exceptions_for_missing_entries=False,
+ _raise_exceptions_for_connection_errors=False,
+ )
+
+ return adapter_cached_filename
+
+
+def check_peft_version(min_version: str) -> None:
+ r"""
+ Checks if the version of PEFT is compatible.
+
+ Args:
+ version (`str`):
+ The version of PEFT to check against.
+ """
+ if not is_peft_available():
+ raise ValueError("PEFT is not installed. Please install it with `pip install peft`")
+
+ is_peft_version_compatible = version.parse(importlib.metadata.version("peft")) >= version.parse(min_version)
+
+ if not is_peft_version_compatible:
+ raise ValueError(
+ f"The version of PEFT you are using is not compatible, please use a version that is greater"
+ f" than {min_version}"
+ )
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/quantization_config.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/quantization_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..037bf3ed73d48c9e55a2d7ef364927822ed899ef
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/quantization_config.py
@@ -0,0 +1,2086 @@
+#!/usr/bin/env python
+# coding=utf-8
+
+# 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_auto_awq_available,
+ is_compressed_tensors_available,
+ is_gptqmodel_available,
+ is_hqq_available,
+ is_quark_available,
+ is_torch_available,
+ is_torchao_available,
+ logging,
+)
+from .import_utils import is_auto_gptq_available
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+class QuantizationMethod(str, Enum):
+ BITS_AND_BYTES = "bitsandbytes"
+ GPTQ = "gptq"
+ AWQ = "awq"
+ AQLM = "aqlm"
+ VPTQ = "vptq"
+ QUANTO = "quanto"
+ EETQ = "eetq"
+ HIGGS = "higgs"
+ HQQ = "hqq"
+ COMPRESSED_TENSORS = "compressed-tensors"
+ FBGEMM_FP8 = "fbgemm_fp8"
+ TORCHAO = "torchao"
+ BITNET = "bitnet"
+ SPQR = "spqr"
+ FP8 = "fp8"
+ QUARK = "quark"
+ FPQUANT = "fp_quant"
+ AUTOROUND = "auto-round"
+ MXFP4 = "mxfp4"
+
+
+class AWQLinearVersion(str, Enum):
+ GEMM = "gemm"
+ GEMV = "gemv"
+ EXLLAMA = "exllama"
+ IPEX = "ipex"
+
+ @staticmethod
+ def from_str(version: str):
+ version = version.lower()
+ if version == "gemm":
+ return AWQLinearVersion.GEMM
+ elif version == "gemv":
+ return AWQLinearVersion.GEMV
+ elif version == "exllama":
+ return AWQLinearVersion.EXLLAMA
+ elif version == "ipex":
+ return AWQLinearVersion.IPEX
+ else:
+ raise ValueError(f"Unknown AWQLinearVersion {version}")
+
+
+class AwqBackendPackingMethod(str, Enum):
+ AUTOAWQ = "autoawq"
+ LLMAWQ = "llm-awq"
+
+
+@dataclass
+class QuantizationConfigMixin:
+ """
+ Mixin class for quantization config
+ """
+
+ quant_method: QuantizationMethod
+
+ @classmethod
+ def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs):
+ """
+ Instantiates a [`QuantizationConfigMixin`] from a Python dictionary of parameters.
+
+ Args:
+ config_dict (`dict[str, Any]`):
+ Dictionary that will be used to instantiate the configuration object.
+ return_unused_kwargs (`bool`,*optional*, defaults to `False`):
+ Whether or not to return a list of unused keyword arguments. Used for `from_pretrained` method in
+ `PreTrainedModel`.
+ kwargs (`dict[str, Any]`):
+ Additional parameters from which to initialize the configuration object.
+
+ Returns:
+ [`QuantizationConfigMixin`]: The configuration object instantiated from those parameters.
+ """
+ config = cls(**config_dict)
+
+ to_remove = []
+ for key, value in kwargs.items():
+ if hasattr(config, key):
+ setattr(config, key, value)
+ to_remove.append(key)
+ for key in to_remove:
+ kwargs.pop(key, None)
+
+ if return_unused_kwargs:
+ return config, kwargs
+ else:
+ return config
+
+ def to_json_file(self, json_file_path: Union[str, os.PathLike]):
+ """
+ Save this instance to a JSON file.
+
+ Args:
+ json_file_path (`str` or `os.PathLike`):
+ Path to the JSON file in which this configuration instance's parameters will be saved.
+ use_diff (`bool`, *optional*, defaults to `True`):
+ If set to `True`, only the difference between the config instance and the default
+ `QuantizationConfig()` is serialized to JSON file.
+ """
+ with open(json_file_path, "w", encoding="utf-8") as writer:
+ config_dict = self.to_dict()
+ json_string = json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
+
+ writer.write(json_string)
+
+ def to_dict(self) -> dict[str, Any]:
+ """
+ Serializes this instance to a Python dictionary. Returns:
+ `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
+ """
+ return copy.deepcopy(self.__dict__)
+
+ def __iter__(self):
+ """allows `dict(obj)` for situations where obj may be a dict or QuantizationConfigMixin"""
+ for attr, value in copy.deepcopy(self.__dict__).items():
+ yield attr, value
+
+ def __repr__(self):
+ return f"{self.__class__.__name__} {self.to_json_string()}"
+
+ def to_json_string(self, use_diff: bool = True) -> str:
+ """
+ Serializes this instance to a JSON string.
+
+ Args:
+ use_diff (`bool`, *optional*, defaults to `True`):
+ If set to `True`, only the difference between the config instance and the default `PretrainedConfig()`
+ is serialized to JSON string.
+
+ Returns:
+ `str`: String containing all the attributes that make up this configuration instance in JSON format.
+ """
+ if use_diff is True:
+ config_dict = self.to_diff_dict()
+ else:
+ config_dict = self.to_dict()
+ return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
+
+ def update(self, **kwargs):
+ """
+ Updates attributes of this class instance with attributes from `kwargs` if they match existing attributes,
+ returning all the unused kwargs.
+
+ Args:
+ kwargs (`dict[str, Any]`):
+ Dictionary of attributes to tentatively update this class.
+
+ Returns:
+ `dict[str, Any]`: Dictionary containing all the key-value pairs that were not used to update the instance.
+ """
+ to_remove = []
+ for key, value in kwargs.items():
+ if hasattr(self, key):
+ setattr(self, key, value)
+ to_remove.append(key)
+
+ # Remove all the attributes that were updated, without modifying the input dict
+ unused_kwargs = {key: value for key, value in kwargs.items() if key not in to_remove}
+ return unused_kwargs
+
+
+@dataclass
+class 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: Optional[int] = None,
+ dynamic_config: Optional[dict] = None,
+ skip_modules: list[str] = ["lm_head"],
+ **kwargs,
+ ):
+ if is_hqq_available():
+ from hqq.core.quantize import BaseQuantizeConfig as HQQBaseQuantizeConfig
+ else:
+ raise ImportError(
+ "A valid HQQ version (>=0.2.1) is not available. Please follow the instructions to install it: `https://github.com/mobiusml/hqq/`."
+ )
+
+ for deprecated_key in ["quant_zero", "quant_scale", "offload_meta"]:
+ if deprecated_key in kwargs:
+ logger.info(
+ deprecated_key + " is deprecated. This parameter will be ignored in quantization settings."
+ )
+
+ if axis is None:
+ axis = 1
+ logger.info("Setting axis=1 as faster backends such as TorchAO or BitBlas are only compatible with it.")
+
+ if axis not in [0, 1]:
+ raise ValueError("Invalid axis value. Only 0 and 1 are allowed.")
+
+ if dynamic_config is not None:
+ self.quant_config = {}
+ for key in dynamic_config:
+ self.quant_config[key] = HQQBaseQuantizeConfig(**dynamic_config[key])
+ else:
+ self.quant_config = HQQBaseQuantizeConfig(
+ **{
+ "nbits": nbits,
+ "group_size": group_size,
+ "view_as_float": view_as_float,
+ "axis": axis,
+ }
+ )
+
+ self.quant_method = QuantizationMethod.HQQ
+ self.skip_modules = skip_modules
+
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
+ """
+ pass
+
+ @classmethod
+ def from_dict(cls, config: dict[str, Any]):
+ """
+ Override from_dict, used in AutoQuantizationConfig.from_dict in quantizers/auto.py
+ """
+ instance = cls()
+ instance.quant_config = config["quant_config"]
+ instance.skip_modules = config["skip_modules"]
+ return instance
+
+ def to_dict(self) -> dict[str, Any]:
+ """
+ Serializes this instance to a Python dictionary. Returns:
+ `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
+ """
+ return {
+ "quant_config": self.quant_config,
+ "quant_method": self.quant_method,
+ "skip_modules": self.skip_modules,
+ }
+
+ def __repr__(self):
+ config_dict = self.to_dict()
+ return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n"
+
+ def to_diff_dict(self) -> dict[str, Any]:
+ """
+ Removes all attributes from config which correspond to the default config attributes for better readability and
+ serializes to a Python dictionary.
+ Returns:
+ `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
+ """
+ config_dict = self.to_dict()
+
+ # get the default config dict
+ default_config_dict = HqqConfig().to_dict()
+
+ serializable_config_dict = {}
+
+ # only serialize values that differ from the default config
+ for key, value in config_dict.items():
+ if value != default_config_dict[key]:
+ serializable_config_dict[key] = value
+
+ return serializable_config_dict
+
+
+@dataclass
+class BitsAndBytesConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded using `bitsandbytes`.
+
+ This replaces `load_in_8bit` or `load_in_4bit`therefore both options are mutually exclusive.
+
+ Currently only supports `LLM.int8()`, `FP4`, and `NF4` quantization. If more methods are added to `bitsandbytes`,
+ then more arguments will be added to this class.
+
+ Args:
+ load_in_8bit (`bool`, *optional*, defaults to `False`):
+ This flag is used to enable 8-bit quantization with LLM.int8().
+ load_in_4bit (`bool`, *optional*, defaults to `False`):
+ This flag is used to enable 4-bit quantization by replacing the Linear layers with FP4/NF4 layers from
+ `bitsandbytes`.
+ llm_int8_threshold (`float`, *optional*, defaults to 6.0):
+ This corresponds to the outlier threshold for outlier detection as described in `LLM.int8() : 8-bit Matrix
+ Multiplication for Transformers at Scale` paper: https://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")
+
+ if self.load_in_4bit and not version.parse(importlib.metadata.version("bitsandbytes")) >= version.parse(
+ "0.39.0"
+ ):
+ raise ValueError(
+ "4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version"
+ )
+
+ def is_quantizable(self):
+ r"""
+ Returns `True` if the model is quantizable, `False` otherwise.
+ """
+ return self.load_in_8bit or self.load_in_4bit
+
+ def quantization_method(self):
+ r"""
+ This method returns the quantization method used for the model. If the model is not quantizable, it returns
+ `None`.
+ """
+ if self.load_in_8bit:
+ return "llm_int8"
+ elif self.load_in_4bit and self.bnb_4bit_quant_type == "fp4":
+ return "fp4"
+ elif self.load_in_4bit and self.bnb_4bit_quant_type == "nf4":
+ return "nf4"
+ else:
+ return None
+
+ def to_dict(self) -> dict[str, Any]:
+ """
+ Serializes this instance to a Python dictionary. Returns:
+ `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
+ """
+ output = copy.deepcopy(self.__dict__)
+ output["bnb_4bit_compute_dtype"] = str(output["bnb_4bit_compute_dtype"]).split(".")[1]
+ output["bnb_4bit_quant_storage"] = str(output["bnb_4bit_quant_storage"]).split(".")[1]
+ output["load_in_4bit"] = self.load_in_4bit
+ output["load_in_8bit"] = self.load_in_8bit
+
+ return output
+
+ def __repr__(self):
+ config_dict = self.to_dict()
+ return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n"
+
+ def to_diff_dict(self) -> dict[str, Any]:
+ """
+ Removes all attributes from config which correspond to the default config attributes for better readability and
+ serializes to a Python dictionary.
+
+ Returns:
+ `dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
+ """
+ config_dict = self.to_dict()
+
+ # get the default config dict
+ default_config_dict = BitsAndBytesConfig().to_dict()
+
+ serializable_config_dict = {}
+
+ # only serialize values that differ from the default config
+ for key, value in config_dict.items():
+ if value != default_config_dict[key]:
+ serializable_config_dict[key] = value
+
+ return serializable_config_dict
+
+
+class ExllamaVersion(int, Enum):
+ ONE = 1
+ TWO = 2
+
+
+@dataclass
+class GPTQConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded using `optimum` api for gptq quantization relying on auto_gptq backend.
+
+ Args:
+ bits (`int`):
+ The number of bits to quantize to, supported numbers are (2, 3, 4, 8).
+ tokenizer (`str` or `PreTrainedTokenizerBase`, *optional*):
+ The tokenizer used to process the dataset. You can pass either:
+ - A custom tokenizer object.
+ - A string, the *model id* of a predefined tokenizer hosted inside a model repo on huggingface.co.
+ - A path to a *directory* containing vocabulary files required by the tokenizer, for instance saved
+ using the [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
+ dataset (`Union[list[str]]`, *optional*):
+ The dataset used for quantization. You can provide your own dataset in a list of string or just use the
+ original datasets used in GPTQ paper ['wikitext2','c4','c4-new']
+ group_size (`int`, *optional*, defaults to 128):
+ The group size to use for quantization. Recommended value is 128 and -1 uses per-column quantization.
+ damp_percent (`float`, *optional*, defaults to 0.1):
+ The percent of the average Hessian diagonal to use for dampening. Recommended value is 0.1.
+ desc_act (`bool`, *optional*, defaults to `False`):
+ Whether to quantize columns in order of decreasing activation size. Setting it to False can significantly
+ speed up inference but the perplexity may become slightly worse. Also known as act-order.
+ sym (`bool`, *optional*, defaults to `True`):
+ Whether to use 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.
+ checkpoint_format (`str`, *optional*, defaults to `"gptq"`):
+ GPTQ weight format. `gptq`(v1) is supported by both gptqmodel and auto-gptq. `gptq_v2` is gptqmodel only.
+ meta (`dict[str, any]`, *optional*):
+ Properties, such as tooling:version, that do not directly contributes to quantization or quant inference are stored in meta.
+ i.e. `meta.quantizer`: ["optimum:_version_", "gptqmodel:_version_"]
+ backend (`str`, *optional*):
+ Controls which gptq kernel to be used. Valid values for gptqmodel are `auto`, `auto_trainable` and more. For auto-gptq, only
+ valid value is None and `auto_trainable`. Ref gptqmodel backends: https://github.com/ModelCloud/GPTQModel/blob/main/gptqmodel/utils/backend.py
+ use_cuda_fp16 (`bool`, *optional*, defaults to `False`):
+ Whether or not to use optimized cuda kernel for fp16 model. Need to have model in fp16. Auto-gptq only.
+ model_seqlen (`int`, *optional*):
+ The maximum sequence length that the model can take.
+ block_name_to_quantize (`str`, *optional*):
+ The transformers block name to quantize. If None, we will infer the block name using common patterns (e.g. model.layers)
+ module_name_preceding_first_block (`list[str]`, *optional*):
+ The layers that are preceding the first Transformer block.
+ batch_size (`int`, *optional*, defaults to 1):
+ The batch size used when processing the dataset
+ pad_token_id (`int`, *optional*):
+ The pad token id. Needed to prepare the dataset when `batch_size` > 1.
+ use_exllama (`bool`, *optional*):
+ Whether to use exllama backend. Defaults to `True` if unset. Only works with `bits` = 4.
+ max_input_length (`int`, *optional*):
+ The maximum input length. This is needed to initialize a buffer that depends on the maximum expected input
+ length. It is specific to the exllama backend with act-order.
+ exllama_config (`dict[str, Any]`, *optional*):
+ The exllama config. You can specify the version of the exllama kernel through the `version` key. Defaults
+ to `{"version": 1}` if unset.
+ cache_block_outputs (`bool`, *optional*, defaults to `True`):
+ Whether to cache block outputs to reuse as inputs for the succeeding block.
+ modules_in_block_to_quantize (`list[list[str]]`, *optional*):
+ List of list of module names to quantize in the specified block. This argument is useful to exclude certain linear modules from being quantized.
+ The block to quantize can be specified by setting `block_name_to_quantize`. We will quantize each list sequentially. If not set, we will quantize all linear layers.
+ Example: `modules_in_block_to_quantize =[["self_attn.k_proj", "self_attn.v_proj", "self_attn.q_proj"], ["self_attn.o_proj"]]`.
+ In this example, we will first quantize the q,k,v layers simultaneously since they are independent.
+ Then, we will quantize `self_attn.o_proj` layer with the q,k,v layers quantized. This way, we will get
+ better results since it reflects the real input `self_attn.o_proj` will get when the model is quantized.
+ """
+
+ def __init__(
+ self,
+ bits: int,
+ tokenizer: Any = None,
+ dataset: Optional[Union[list[str], str]] = None,
+ group_size: int = 128,
+ damp_percent: float = 0.1,
+ desc_act: bool = False,
+ sym: bool = True,
+ true_sequential: bool = True,
+ checkpoint_format: str = "gptq",
+ meta: Optional[dict[str, Any]] = None,
+ backend: Optional[str] = None,
+ use_cuda_fp16: bool = False,
+ model_seqlen: Optional[int] = None,
+ block_name_to_quantize: Optional[str] = None,
+ module_name_preceding_first_block: Optional[list[str]] = None,
+ batch_size: int = 1,
+ pad_token_id: Optional[int] = None,
+ use_exllama: Optional[bool] = None,
+ max_input_length: Optional[int] = None,
+ exllama_config: Optional[dict[str, Any]] = None,
+ cache_block_outputs: bool = True,
+ modules_in_block_to_quantize: Optional[list[list[str]]] = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.GPTQ
+ self.bits = bits
+ self.tokenizer = tokenizer
+ self.dataset = dataset
+ self.group_size = group_size
+ self.damp_percent = damp_percent
+ self.desc_act = desc_act
+ self.sym = sym
+ self.true_sequential = true_sequential
+ self.checkpoint_format = checkpoint_format.lower()
+ self.meta = meta
+ self.backend = backend.lower() if isinstance(backend, str) else backend
+ self.use_cuda_fp16 = use_cuda_fp16
+ self.model_seqlen = model_seqlen
+ self.block_name_to_quantize = block_name_to_quantize
+ self.module_name_preceding_first_block = module_name_preceding_first_block
+ self.batch_size = batch_size
+ self.pad_token_id = pad_token_id
+ self.use_exllama = use_exllama
+ self.max_input_length = max_input_length
+ self.exllama_config = exllama_config
+ self.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 = [
+ "use_exllama",
+ "exllama_config",
+ "use_cuda_fp16",
+ "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 in ["ptb", "ptb-new"]:
+ raise ValueError(
+ f"""{self.dataset} dataset was deprecated. You can only choose between
+ ['wikitext2','c4','c4-new']"""
+ )
+ if self.dataset not in ["wikitext2", "c4", "c4-new"]:
+ raise ValueError(
+ f"""You have entered a string value for dataset. You can only choose between
+ ['wikitext2','c4','c4-new'], but we found {self.dataset}"""
+ )
+ elif not isinstance(self.dataset, list):
+ raise ValueError(
+ f"""dataset needs to be either a list of string or a value in
+ ['wikitext2','c4','c4-new'], but we found {self.dataset}"""
+ )
+
+ # make sure backend is back/forward compatible with both gptqmodel (full) and auto-gptq (partial)
+ if is_gptqmodel_available():
+ # convert auto-gptq control into gptqmodel backend
+ if self.backend is None:
+ self.backend = "auto_trainable" if self.use_exllama is not None and not self.use_exllama else "auto"
+ else:
+ # convert gptqmodel backend `auto_trainable` into auto-gptq control
+ if self.backend == "auto_trainable":
+ self.use_exllama = False
+
+ # auto-gptq specific kernel control logic
+ if self.use_exllama is None:
+ # New default behaviour
+ self.use_exllama = True
+
+ if self.exllama_config is None:
+ self.exllama_config = {"version": ExllamaVersion.ONE}
+ else:
+ if "version" not in self.exllama_config:
+ raise ValueError("`exllama_config` needs to have a `version` key.")
+ elif self.exllama_config["version"] not in [ExllamaVersion.ONE, ExllamaVersion.TWO]:
+ exllama_version = self.exllama_config["version"]
+ raise ValueError(
+ f"Only supported versions are in [ExllamaVersion.ONE, ExllamaVersion.TWO] - not recognized version {exllama_version}"
+ )
+
+ if self.bits == 4 and self.use_exllama:
+ if self.exllama_config["version"] == ExllamaVersion.ONE:
+ logger.info(
+ "You have activated exllama backend. Note that you can get better inference "
+ "speed using exllamav2 kernel by setting `exllama_config`."
+ )
+ elif self.exllama_config["version"] == ExllamaVersion.TWO:
+ if is_auto_gptq_available():
+ optimum_version = version.parse(importlib.metadata.version("optimum"))
+ autogptq_version = version.parse(importlib.metadata.version("auto_gptq"))
+ if optimum_version <= version.parse("1.13.2") or autogptq_version <= version.parse("0.4.2"):
+ raise ValueError(
+ f"You need optimum > 1.13.2 and auto-gptq > 0.4.2 . Make sure to have that version installed - detected version : optimum {optimum_version} and autogptq {autogptq_version}"
+ )
+ if self.modules_in_block_to_quantize is not None:
+ optimum_version = version.parse(importlib.metadata.version("optimum"))
+ if optimum_version < version.parse("1.15.0"):
+ raise ValueError(
+ "You current version of `optimum` does not support `modules_in_block_to_quantize` quantization argument, please upgrade `optimum` package to a version superior than 1.15.0 ."
+ )
+
+ def to_dict(self):
+ config_dict = super().to_dict()
+ config_dict.pop("disable_exllama", None)
+ return config_dict
+
+ def to_dict_optimum(self):
+ """
+ Get compatible dict for optimum gptq config
+ """
+ quant_dict = self.to_dict()
+ # make it compatible with optimum config
+ quant_dict["disable_exllama"] = not self.use_exllama
+ return quant_dict
+
+ @classmethod
+ def from_dict_optimum(cls, config_dict):
+ """
+ Get compatible class with optimum gptq config dict
+ """
+
+ if "disable_exllama" in config_dict:
+ config_dict["use_exllama"] = not config_dict["disable_exllama"]
+ # switch to None to not trigger the warning
+ config_dict.pop("disable_exllama")
+
+ config = cls(**config_dict)
+ return config
+
+
+@dataclass
+class AwqConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded using `auto-awq` library awq quantization relying on auto_awq backend.
+
+ Args:
+ bits (`int`, *optional*, defaults to 4):
+ The number of bits to quantize to.
+ group_size (`int`, *optional*, defaults to 128):
+ The group size to use for quantization. Recommended value is 128 and -1 uses per-column quantization.
+ zero_point (`bool`, *optional*, defaults to `True`):
+ Whether to use zero point quantization.
+ version (`AWQLinearVersion`, *optional*, defaults to `AWQLinearVersion.GEMM`):
+ The version of the quantization algorithm to use. GEMM is better for big batch_size (e.g. >= 8) otherwise,
+ GEMV is better (e.g. < 8 ). GEMM models are compatible with Exllama kernels.
+ backend (`AwqBackendPackingMethod`, *optional*, defaults to `AwqBackendPackingMethod.AUTOAWQ`):
+ The quantization backend. Some models might be quantized using `llm-awq` backend. This is useful for users
+ that quantize their own models using `llm-awq` library.
+ do_fuse (`bool`, *optional*, defaults to `False`):
+ Whether to fuse attention and mlp layers together for faster inference
+ fuse_max_seq_len (`int`, *optional*):
+ The Maximum sequence length to generate when using fusing.
+ modules_to_fuse (`dict`, *optional*, default to `None`):
+ Overwrite the natively supported fusing scheme with the one specified by the users.
+ modules_to_not_convert (`list`, *optional*, default to `None`):
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have
+ some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers).
+ Note you cannot quantize directly with transformers, please refer to `AutoAWQ` documentation for quantizing HF models.
+ exllama_config (`dict[str, Any]`, *optional*):
+ You can specify the version of the exllama kernel through the `version` key, the maximum sequence
+ length through the `max_input_len` key, and the maximum batch size through the `max_batch_size` key.
+ Defaults to `{"version": 2, "max_input_len": 2048, "max_batch_size": 8}` if unset.
+ """
+
+ def __init__(
+ self,
+ bits: int = 4,
+ group_size: int = 128,
+ zero_point: bool = True,
+ version: AWQLinearVersion = AWQLinearVersion.GEMM,
+ backend: AwqBackendPackingMethod = AwqBackendPackingMethod.AUTOAWQ,
+ do_fuse: Optional[bool] = None,
+ fuse_max_seq_len: Optional[int] = None,
+ modules_to_fuse: Optional[dict] = None,
+ modules_to_not_convert: Optional[list] = None,
+ exllama_config: Optional[dict[str, int]] = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.AWQ
+
+ self.bits = bits
+ self.group_size = group_size
+ self.zero_point = zero_point
+ self.version = version
+ self.backend = backend
+ self.fuse_max_seq_len = fuse_max_seq_len
+ self.modules_to_not_convert = modules_to_not_convert
+ self.exllama_config = exllama_config
+
+ self.modules_to_fuse = modules_to_fuse
+ if do_fuse is None:
+ self.do_fuse = modules_to_fuse is not None and len(modules_to_fuse) > 0
+ else:
+ self.do_fuse = do_fuse
+ self.fuse_max_seq_len = fuse_max_seq_len
+
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ if self.backend not in [AwqBackendPackingMethod.AUTOAWQ, AwqBackendPackingMethod.LLMAWQ]:
+ raise ValueError(
+ f"Only supported quantization backends in {AwqBackendPackingMethod.AUTOAWQ} and {AwqBackendPackingMethod.LLMAWQ} - not recognized backend {self.backend}"
+ )
+
+ self.version = AWQLinearVersion.from_str(self.version)
+ if self.version not in [
+ AWQLinearVersion.GEMM,
+ AWQLinearVersion.GEMV,
+ AWQLinearVersion.EXLLAMA,
+ AWQLinearVersion.IPEX,
+ ]:
+ raise ValueError(
+ f"Only supported versions are in [AWQLinearVersion.GEMM, AWQLinearVersion.GEMV, AWQLinearVersion.EXLLAMA, AWQLinearVersion.IPEX] - not recognized version {self.version}"
+ )
+
+ if self.backend == AwqBackendPackingMethod.LLMAWQ:
+ # Only cuda device can run this function
+ if not (torch.cuda.is_available() or torch.xpu.is_available()):
+ raise ValueError("LLM-AWQ backend is only supported on CUDA and XPU")
+ if torch.cuda.is_available():
+ compute_capability = torch.cuda.get_device_capability()
+ major, minor = compute_capability
+ if major < 8:
+ raise ValueError("LLM-AWQ backend is only supported on CUDA GPUs with compute capability >= 8.0")
+
+ if self.do_fuse and self.fuse_max_seq_len is None:
+ raise ValueError(
+ "You cannot enable fused modules without specifying a `fuse_max_seq_len`, make sure to pass a valid `fuse_max_seq_len` for your usecase"
+ )
+
+ if self.do_fuse:
+ awq_version_supports_fusing = False
+ MIN_AWQ_VERSION = "0.1.7"
+ if is_auto_awq_available():
+ awq_version_supports_fusing = version.parse(importlib.metadata.version("autoawq")) >= version.parse(
+ MIN_AWQ_VERSION
+ )
+
+ if not awq_version_supports_fusing:
+ raise ValueError(
+ f"You current version of `autoawq` does not support module fusing, please upgrade `autoawq` package to at least {MIN_AWQ_VERSION}."
+ )
+
+ if self.modules_to_not_convert is not None:
+ awq_version_supports_non_conversion = False
+ MIN_AWQ_VERSION = "0.1.8"
+ if is_auto_awq_available():
+ awq_version_supports_non_conversion = version.parse(
+ importlib.metadata.version("autoawq")
+ ) >= version.parse(MIN_AWQ_VERSION)
+
+ if not awq_version_supports_non_conversion:
+ raise ValueError(
+ f"You current version of `autoawq` does not support module quantization skipping, please upgrade `autoawq` package to at least {MIN_AWQ_VERSION}."
+ )
+
+ if self.do_fuse and self.modules_to_fuse is not None:
+ required_keys = [
+ "hidden_size",
+ "num_attention_heads",
+ "num_key_value_heads",
+ "mlp",
+ "attention",
+ "layernorm",
+ "use_alibi",
+ ]
+ if not all(key in self.modules_to_fuse for key in required_keys):
+ raise ValueError(
+ f"Required fields are missing in the fusing mapping, required fields are {required_keys}"
+ )
+
+ if self.version == AWQLinearVersion.EXLLAMA:
+ awq_version_supports_exllama = False
+ MIN_AWQ_VERSION = "0.2.0"
+ if is_auto_awq_available():
+ awq_version_supports_exllama = version.parse(importlib.metadata.version("autoawq")) >= version.parse(
+ MIN_AWQ_VERSION
+ )
+
+ if not awq_version_supports_exllama:
+ raise ValueError(
+ f"You current version of `autoawq` does not support exllama backend, "
+ f"please upgrade `autoawq` package to at least {MIN_AWQ_VERSION}."
+ )
+
+ if self.exllama_config is None:
+ self.exllama_config = {"version": ExllamaVersion.TWO, "max_input_len": 2048, "max_batch_size": 8}
+ else:
+ if "version" not in self.exllama_config:
+ raise ValueError("`exllama_config` needs to have a `version` key.")
+ elif self.exllama_config["version"] not in [ExllamaVersion.ONE, ExllamaVersion.TWO]:
+ exllama_version = self.exllama_config["version"]
+ raise ValueError(
+ f"Only supported versions are in [ExllamaVersion.ONE, ExllamaVersion.TWO] - not recognized version {exllama_version}"
+ )
+
+ def get_loading_attributes(self):
+ attributes_dict = copy.deepcopy(self.__dict__)
+ loading_attributes = ["version", "do_fuse", "modules_to_fuse", "fuse_max_seq_len", "exllama_config"]
+ loading_attributes_dict = {i: j for i, j in attributes_dict.items() if i in loading_attributes}
+ return loading_attributes_dict
+
+
+@dataclass
+class AqlmConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about `aqlm` parameters.
+
+ Args:
+ in_group_size (`int`, *optional*, defaults to 8):
+ The group size along the input dimension.
+ out_group_size (`int`, *optional*, defaults to 1):
+ The group size along the output dimension. It's recommended to always use 1.
+ num_codebooks (`int`, *optional*, defaults to 1):
+ Number of codebooks for the Additive Quantization procedure.
+ nbits_per_codebook (`int`, *optional*, defaults to 16):
+ Number of bits encoding a single codebook vector. Codebooks size is 2**nbits_per_codebook.
+ linear_weights_not_to_quantize (`Optional[list[str]]`, *optional*):
+ List of full paths of `nn.Linear` weight parameters that shall not be quantized.
+ kwargs (`dict[str, Any]`, *optional*):
+ Additional parameters from which to initialize the configuration object.
+ """
+
+ def __init__(
+ self,
+ in_group_size: int = 8,
+ out_group_size: int = 1,
+ num_codebooks: int = 1,
+ nbits_per_codebook: int = 16,
+ linear_weights_not_to_quantize: Optional[list[str]] = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.AQLM
+ self.in_group_size = in_group_size
+ self.out_group_size = out_group_size
+ self.num_codebooks = num_codebooks
+ self.nbits_per_codebook = nbits_per_codebook
+ self.linear_weights_not_to_quantize = linear_weights_not_to_quantize
+
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
+ """
+ if not isinstance(self.in_group_size, int):
+ raise TypeError("in_group_size must be a float")
+ if not isinstance(self.out_group_size, int):
+ raise TypeError("out_group_size must be a float")
+ if not isinstance(self.num_codebooks, int):
+ raise TypeError("num_codebooks must be a float")
+ if not isinstance(self.nbits_per_codebook, int):
+ raise TypeError("nbits_per_codebook must be a float")
+
+ if self.linear_weights_not_to_quantize is not None and not isinstance(
+ self.linear_weights_not_to_quantize, list
+ ):
+ raise ValueError("linear_weights_not_to_quantize must be a list of strings")
+
+ if self.linear_weights_not_to_quantize is None:
+ self.linear_weights_not_to_quantize = []
+
+
+@dataclass
+class VptqLayerConfig(QuantizationConfigMixin):
+ """
+ This is used to explain vptq config params for each layer
+ Args:
+ enable_norm (`bool`, *optional*, defaults to `True`): to control if we have scale/bias for fp-weight
+ enable_perm (`bool`, *optional*, defaults to `True`): to perm input_channel or not
+ group_num (`int`, *optional*, defaults to `1`): how many single groups for vector-quantization
+ group_size (`int`, *optional*, defaults to `-1`): depends on out-features
+ indices_as_float (`bool`, *optional*, defaults to `False`): for Finetuning
+ is_indice_packed (`bool`, *optional*, defaults to `True`): should always be True
+ num_centroids (`list`, *optional*, defaults to `[-1, -1]`): 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: tuple = [-1, -1],
+ num_res_centroids: tuple = [-1, -1],
+ out_features: int = -1,
+ outlier_size: int = 0,
+ vector_lens: tuple = [-1, -1],
+ **kwargs,
+ ):
+ self.enable_norm = enable_norm
+ self.enable_perm = enable_perm
+ self.group_num = group_num
+ self.group_size = group_size
+ self.in_features = in_features
+ self.indices_as_float = indices_as_float
+ self.is_indice_packed = is_indice_packed
+ self.num_centroids = num_centroids
+ self.num_res_centroids = num_res_centroids
+ self.out_features = out_features
+ self.outlier_size = outlier_size
+ self.vector_lens = vector_lens
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ if self.is_indice_packed is False:
+ raise ValueError("is_indice_packed should always be True")
+
+
+@dataclass
+class VptqConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about `vptq` parameters.
+
+ Args:
+ enable_proxy_error (`bool`, *optional*, defaults to `False`): calculate proxy error for each layer
+ config_for_layers (`Dict`, *optional*, defaults to `{}`): quantization params for each layer
+ shared_layer_config (`Dict`, *optional*, defaults to `{}`): shared quantization params among layers
+ modules_to_not_convert (`list`, *optional*, default to `None`):
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have
+ some modules left in their original precision (e.g. Whisper encoder, Llava encoder, Mixtral gate layers).
+ kwargs (`dict[str, Any]`, *optional*):
+ Additional parameters from which to initialize the configuration object.
+ """
+
+ def __init__(
+ self,
+ enable_proxy_error: bool = False,
+ config_for_layers: dict[str, Any] = {},
+ shared_layer_config: dict[str, Any] = {},
+ modules_to_not_convert: Optional[list] = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.VPTQ
+ self.enable_proxy_error = enable_proxy_error
+ self.config_for_layers: dict[str, Any] = config_for_layers
+ self.shared_layer_config: dict[str, Any] = shared_layer_config
+ self.modules_to_not_convert = modules_to_not_convert
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ for layer_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: Optional[list] = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.QUANTO
+ self.weights = weights
+ self.activations = activations
+ self.modules_to_not_convert = modules_to_not_convert
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ accepted_weights = ["float8", "int8", "int4", "int2"]
+ accepted_activations = [None, "int8", "float8"]
+ if self.weights not in accepted_weights:
+ raise ValueError(f"Only support weights in {accepted_weights} but found {self.weights}")
+ if self.activations not in accepted_activations:
+ raise ValueError(f"Only support weights in {accepted_activations} but found {self.activations}")
+
+
+@dataclass
+class EetqConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
+ loaded using `eetq`.
+
+ Args:
+ weights (`str`, *optional*, defaults to `"int8"`):
+ The target dtype for the weights. Supported value is only "int8"
+ modules_to_not_convert (`list`, *optional*, default to `None`):
+ The list of modules to not quantize, useful for quantizing models that explicitly require to have
+ some modules left in their original precision.
+ """
+
+ def __init__(
+ self,
+ weights: str = "int8",
+ modules_to_not_convert: Optional[list] = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.EETQ
+ self.weights = weights
+ self.modules_to_not_convert = modules_to_not_convert
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ accepted_weights = ["int8"]
+ if self.weights not in accepted_weights:
+ raise ValueError(f"Only support weights in {accepted_weights} but found {self.weights}")
+
+
+class CompressedTensorsConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class that handles compressed-tensors quantization config options.
+ It is a wrapper around `compressed_tensors.QuantizationConfig`
+ Args:
+ config_groups (`typing.dict[str, typing.Union[ForwardRef('QuantizationScheme'), typing.list[str]]]`, *optional*):
+ dictionary mapping group name to a quantization scheme definition
+ format (`str`, *optional*, defaults to `"dense"`):
+ format the model is represented as. Set `run_compressed` True to execute model as the
+ compressed format if not `dense`
+ quantization_status (`QuantizationStatus`, *optional*, defaults to `"initialized"`):
+ status of model in the quantization lifecycle, ie 'initialized', 'calibration', 'frozen'
+ kv_cache_scheme (`typing.Union[QuantizationArgs, NoneType]`, *optional*):
+ specifies quantization of the kv cache. If None, kv cache is not quantized.
+ global_compression_ratio (`typing.Union[float, NoneType]`, *optional*):
+ 0-1 float percentage of model compression
+ ignore (`typing.Union[typing.list[str], NoneType]`, *optional*):
+ layer names or types to not quantize, supports regex prefixed by 're:'
+ sparsity_config (`typing.dict[str, typing.Any]`, *optional*):
+ configuration for sparsity compression
+ quant_method (`str`, *optional*, defaults to `"compressed-tensors"`):
+ do not override, should be compressed-tensors
+ run_compressed (`bool`, *optional*, defaults to `True`): alter submodules (usually linear) in order to
+ emulate compressed model execution if True, otherwise use default submodule
+ """
+
+ def __init__(
+ self,
+ config_groups: Optional[dict[str, Union["QuantizationScheme", list[str]]]] = None, # noqa: F821
+ format: str = "dense",
+ quantization_status: "QuantizationStatus" = "initialized", # noqa: F821
+ kv_cache_scheme: Optional["QuantizationArgs"] = None, # noqa: F821
+ global_compression_ratio: Optional[float] = None,
+ ignore: Optional[list[str]] = None,
+ sparsity_config: Optional[dict[str, Any]] = None,
+ quant_method: str = "compressed-tensors",
+ run_compressed: bool = True,
+ **kwargs,
+ ):
+ if is_compressed_tensors_available():
+ from compressed_tensors.config import SparsityCompressionConfig
+ from compressed_tensors.quantization import QuantizationConfig
+ else:
+ raise ImportError(
+ "compressed_tensors is not installed and is required for compressed-tensors quantization. Please install it with `pip install compressed-tensors`."
+ )
+ self.quantization_config = None
+ self.sparsity_config = None
+
+ self.run_compressed = run_compressed
+
+ # parse from dict to load nested QuantizationScheme objects
+ if config_groups or kv_cache_scheme:
+ self.quantization_config = QuantizationConfig.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
+
+ return self.is_quantized and self.quantization_config.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: Optional[list] = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.FBGEMM_FP8
+ self.activation_scale_ub = activation_scale_ub
+ self.modules_to_not_convert = modules_to_not_convert
+
+ def get_loading_attributes(self):
+ 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: Optional[list[str]] = None,
+ hadamard_size: int = 512,
+ group_size: int = 256,
+ tune_metadata: Optional[dict[str, Any]] = None,
+ **kwargs,
+ ):
+ if tune_metadata is None:
+ tune_metadata = {}
+ self.quant_method = QuantizationMethod.HIGGS
+ self.bits = bits
+ self.p = p
+ self.modules_to_not_convert = modules_to_not_convert
+ self.hadamard_size = hadamard_size
+ self.group_size = group_size
+ self.tune_metadata = tune_metadata
+
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
+ """
+ if self.bits not in [2, 3, 4]:
+ raise ValueError("bits must be 2, 3, or 4")
+ if self.p not in [1, 2]:
+ raise ValueError("p must be 1 or 2. 2 is always better in practice")
+ if self.group_size not in [64, 128, 256]:
+ raise ValueError("group_size must be 64, 128, or 256")
+ if self.hadamard_size % self.group_size != 0:
+ raise ValueError("hadamard_size must be divisible by group_size")
+
+
+@dataclass
+class FPQuantConfig(QuantizationConfigMixin):
+ """
+ FPQuantConfig is a configuration class for quantization using the FPQuant method.
+
+ Args:
+ forward_dtype (`str`, *optional*, defaults to `"mxfp4"`):
+ 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*, defaults to 32):
+ The group size for the hadamard transform before quantization for `"quest"` it matches the MXFP4 group size (32).
+ 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.
+ 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 = "mxfp4",
+ forward_method: str = "abs_max",
+ backward_dtype: str = "bf16",
+ store_master_weights: bool = False,
+ hadamard_group_size: int = 32,
+ pseudoquantization: bool = False,
+ modules_to_not_convert: Optional[list[str]] = 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.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.forward_dtype not in ["mxfp4"]:
+ raise ValueError("Only 'mxfp4' is supported for forward_dtype for now.")
+ if self.forward_method not in ["abs_max", "quest"]:
+ raise ValueError("Only 'abs_max' and 'quest' are supported for forward_method for now.")
+ if self.backward_dtype not in ["bf16"]:
+ raise ValueError("Only 'bf16' is supported for backward_dtype for now.")
+ if self.hadamard_group_size not in [32]:
+ raise ValueError("Only a hadamard_group_size of 32 is supported for now.")
+ 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: Optional[list]
+ 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)
+
+ # autoquant
+ # `autoquant` is a convenient way for users to search for the best quantization for each layer
+ # `min_sqnr` is an option to control the accuracy of the model, higher value means the model is more
+ # accurate, we can start with 30 and adjust it to larger or smaller (e.g. 40, 20)
+ # defaults to None, which means we'll try to get the best performing quantized model without
+ # considering accuracy
+ quantization_config = TorchAoConfig("autoquant", min_sqnr=30)
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cuda", dtype=torch.bfloat16, quantization_config=quantization_config)
+ # run through example inputs, quantization methods will be selected based on the shape of example input
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
+ input_text = "What are we having for dinner?"
+ input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
+ MAX_NEW_TOKENS = 1000
+ model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation="static")
+ # manually ran finalize_autoquant if needed
+ if hasattr(quantized_model, "finalize_autoquant"):
+ print("finalizing autoquant")
+ quantized_model.finalize_autoquant()
+
+ ```
+ """
+
+ def __init__(
+ self,
+ quant_type: Union[str, "AOBaseConfig"], # noqa: F821
+ modules_to_not_convert: Optional[list] = 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 (
+ autoquant,
+ int4_weight_only,
+ int8_dynamic_activation_int8_weight,
+ int8_weight_only,
+ )
+
+ return {
+ "int4_weight_only": int4_weight_only,
+ "int8_weight_only": int8_weight_only,
+ "int8_dynamic_activation_int8_weight": int8_dynamic_activation_int8_weight,
+ "autoquant": autoquant,
+ }
+
+ 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: Optional[list] = None,
+ linear_class: Optional[str] = "bitlinear",
+ quantization_mode: Optional[str] = "offline",
+ use_rms_norm: Optional[bool] = False,
+ rms_norm_eps: Optional[float] = 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
+ """
+ pass
+
+
+@dataclass
+class SpQRConfig(QuantizationConfigMixin):
+ """
+ This is a wrapper class about `spqr` parameters. Refer to the original publication for more details.
+
+ Args:
+ bits (`int`, *optional*, defaults to 3):
+ Specifies the bit count for the weights and first order zero-points and scales.
+ Currently only bits = 3 is supported.
+ beta1 (`int`, *optional*, defaults to 16):
+ SpQR tile width. Currently only beta1 = 16 is supported.
+ beta2 (`int`, *optional*, defaults to 16):
+ SpQR tile height. Currently only beta2 = 16 is supported.
+ shapes (`Optional`, *optional*):
+ A dictionary holding the shape of each object. We need this because it's impossible
+ to deduce the exact size of the parameters just from bits, beta1, beta2.
+ modules_to_not_convert (`Optional[list[str]]`, *optional*):
+ Optionally, provides a list of full paths of `nn.Linear` weight parameters that shall not be quantized.
+ Defaults to None.
+ kwargs (`dict[str, Any]`, *optional*):
+ Additional parameters from which to initialize the configuration object.
+ """
+
+ def __init__(
+ self,
+ bits: int = 3,
+ beta1: int = 16,
+ beta2: int = 16,
+ shapes: Optional[dict[str, int]] = None,
+ modules_to_not_convert: Optional[list[str]] = None,
+ **kwargs,
+ ):
+ if shapes is None:
+ shapes = {}
+ self.shapes = shapes
+ self.quant_method = QuantizationMethod.SPQR
+ self.bits = bits
+ self.beta1 = beta1
+ self.beta2 = beta2
+ self.modules_to_not_convert = modules_to_not_convert
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
+ """
+ if not isinstance(self.bits, int):
+ raise TypeError("bits must be an int")
+ if not isinstance(self.beta1, int):
+ raise TypeError("beta1 must be an int")
+ if not isinstance(self.beta2, int):
+ raise TypeError("beta2 must be an int")
+
+ if self.bits != 3:
+ raise ValueError("SpQR currently only supports bits = 3")
+ if self.beta1 != 16:
+ raise ValueError("SpQR currently only supports beta1 = 16")
+ if self.beta2 != 16:
+ raise ValueError("SpQR currently only supports beta2 = 16")
+ if not isinstance(self.shapes, dict):
+ raise TypeError("shapes must be a dict")
+
+
+@dataclass
+class FineGrainedFP8Config(QuantizationConfigMixin):
+ """
+ FineGrainedFP8Config is a configuration class for fine-grained FP8 quantization used mainly for deepseek models.
+
+ Args:
+ activation_scheme (`str`, *optional*, defaults to `"dynamic"`):
+ The scheme used for activation, the defaults and only support scheme for now is "dynamic".
+ weight_block_size (`typing.tuple[int, int]`, *optional*, defaults to `(128, 128)`):
+ The size of the weight blocks for quantization, default is (128, 128).
+ modules_to_not_convert (`list`, *optional*):
+ A list of module names that should not be converted during quantization.
+ """
+
+ def __init__(
+ self,
+ activation_scheme: str = "dynamic",
+ weight_block_size: tuple[int, int] = (128, 128),
+ modules_to_not_convert: Optional[list] = None,
+ **kwargs,
+ ):
+ self.quant_method = QuantizationMethod.FP8
+ self.modules_to_not_convert = modules_to_not_convert
+ self.activation_scheme = activation_scheme
+ self.weight_block_size = weight_block_size
+ self.post_init()
+
+ def post_init(self):
+ r"""
+ Safety checker that arguments are correct
+ """
+ self.activation_scheme = self.activation_scheme.lower()
+ if self.activation_scheme not in ["dynamic"]:
+ raise ValueError(f"Activation scheme {self.activation_scheme} not supported")
+ if len(self.weight_block_size) != 2:
+ raise ValueError("weight_block_size must be a tuple of two integers")
+ if self.weight_block_size[0] <= 0 or self.weight_block_size[1] <= 0:
+ raise ValueError("weight_block_size must be a tuple of two positive integers")
+
+
+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: Optional[list] = 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}
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/sentencepiece_model_pb2.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/sentencepiece_model_pb2.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f063575fd7af2ae65d3d55b054b856ca8b77fe8
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/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/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/sentencepiece_model_pb2_new.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/sentencepiece_model_pb2_new.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ea4f4d64ce660b3d59d60c0650f5849e4fd2251
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/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/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/versions.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/versions.py
new file mode 100644
index 0000000000000000000000000000000000000000..85dabec8b659022655ce570b4642febd715b6d52
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/transformers/utils/versions.py
@@ -0,0 +1,117 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Utilities for working with package versions
+"""
+
+import importlib.metadata
+import operator
+import re
+import sys
+from typing import Optional
+
+from packaging import version
+
+
+ops = {
+ "<": operator.lt,
+ "<=": operator.le,
+ "==": operator.eq,
+ "!=": operator.ne,
+ ">=": operator.ge,
+ ">": operator.gt,
+}
+
+
+def _compare_versions(op, got_ver, want_ver, requirement, pkg, hint):
+ if got_ver is None or want_ver is None:
+ raise ValueError(
+ f"Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider"
+ f" reinstalling {pkg}."
+ )
+ if not ops[op](version.parse(got_ver), version.parse(want_ver)):
+ raise ImportError(
+ f"{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}"
+ )
+
+
+def require_version(requirement: str, hint: Optional[str] = None) -> None:
+ """
+ Perform a runtime check of the dependency versions, using the exact same syntax used by pip.
+
+ The installed module version comes from the *site-packages* dir via *importlib.metadata*.
+
+ Args:
+ requirement (`str`): pip style definition, e.g., "tokenizers==0.9.4", "tqdm>=4.27", "numpy"
+ hint (`str`, *optional*): what suggestion to print in case of requirements not being met
+
+ Example:
+
+ ```python
+ require_version("pandas>1.1.2")
+ require_version("numpy>1.18.5", "this is important to have for whatever reason")
+ ```"""
+
+ hint = f"\n{hint}" if hint is not None else ""
+
+ # non-versioned check
+ if re.match(r"^[\w_\-\d]+$", requirement):
+ pkg, op, want_ver = requirement, None, None
+ else:
+ match = re.findall(r"^([^!=<>\s]+)([\s!=<>]{1,2}.+)", requirement)
+ if not match:
+ raise ValueError(
+ "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but"
+ f" got {requirement}"
+ )
+ pkg, want_full = match[0]
+ want_range = want_full.split(",") # there could be multiple requirements
+ wanted = {}
+ for w in want_range:
+ match = re.findall(r"^([\s!=<>]{1,2})(.+)", w)
+ if not match:
+ raise ValueError(
+ "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,"
+ f" but got {requirement}"
+ )
+ op, want_ver = match[0]
+ wanted[op] = want_ver
+ if op not in ops:
+ raise ValueError(f"{requirement}: need one of {list(ops.keys())}, but got {op}")
+
+ # special case
+ if pkg == "python":
+ got_ver = ".".join([str(x) for x in sys.version_info[:3]])
+ for op, want_ver in wanted.items():
+ _compare_versions(op, got_ver, want_ver, requirement, pkg, hint)
+ return
+
+ # check if any version is installed
+ try:
+ got_ver = importlib.metadata.version(pkg)
+ except importlib.metadata.PackageNotFoundError:
+ raise importlib.metadata.PackageNotFoundError(
+ f"The '{requirement}' distribution was not found and is required by this application. {hint}"
+ )
+
+ # check that the right version is installed if version number or a range was provided
+ if want_ver is not None:
+ for op, want_ver in wanted.items():
+ _compare_versions(op, got_ver, want_ver, requirement, pkg, hint)
+
+
+def require_version_core(requirement):
+ """require_version wrapper which emits a core-specific hint on failure"""
+ hint = "Try: `pip install transformers -U` or `pip install -e '.[dev]'` if you're working with git main"
+ return require_version(requirement, hint)
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/INSTALLER b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/METADATA b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..72653461b9c91b5a5482666dce798f6867dfe130
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/METADATA
@@ -0,0 +1,47 @@
+Metadata-Version: 2.4
+Name: triton
+Version: 3.4.0
+Summary: A language and compiler for custom Deep Learning operations
+Home-page: https://github.com/triton-lang/triton/
+Author: Philippe Tillet
+Author-email: phil@openai.com
+Keywords: Compiler,Deep Learning
+Classifier: Development Status :: 4 - Beta
+Classifier: Intended Audience :: Developers
+Classifier: Topic :: Software Development :: Build Tools
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Requires-Python: >=3.9,<3.14
+License-File: LICENSE
+Requires-Dist: setuptools>=40.8.0
+Requires-Dist: importlib-metadata; python_version < "3.10"
+Provides-Extra: build
+Requires-Dist: cmake<4.0,>=3.20; extra == "build"
+Requires-Dist: lit; extra == "build"
+Provides-Extra: tests
+Requires-Dist: autopep8; extra == "tests"
+Requires-Dist: isort; extra == "tests"
+Requires-Dist: numpy; extra == "tests"
+Requires-Dist: pytest; extra == "tests"
+Requires-Dist: pytest-forked; extra == "tests"
+Requires-Dist: pytest-xdist; extra == "tests"
+Requires-Dist: scipy>=1.7.1; extra == "tests"
+Requires-Dist: llnl-hatchet; extra == "tests"
+Provides-Extra: tutorials
+Requires-Dist: matplotlib; extra == "tutorials"
+Requires-Dist: pandas; extra == "tutorials"
+Requires-Dist: tabulate; extra == "tutorials"
+Dynamic: author
+Dynamic: author-email
+Dynamic: classifier
+Dynamic: home-page
+Dynamic: keywords
+Dynamic: license-file
+Dynamic: provides-extra
+Dynamic: requires-dist
+Dynamic: requires-python
+Dynamic: summary
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/RECORD b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..3cf897e6f15e93860c30897e627bdb9748e390e3
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/RECORD
@@ -0,0 +1,453 @@
+../../../bin/proton,sha256=PCyBM0K5D6M403OZyilNVyn30QFwMJBYsJb_SiHtVag,243
+../../../bin/proton-viewer,sha256=NdFMQRaIKDaE7s0-IVr-lMzNQMVGm7AJYquEBrelvCI,243
+triton-3.4.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+triton-3.4.0.dist-info/METADATA,sha256=hJa1e-zW8P5zK_gVcDMDg_JeK8VypUvexFZxoj4dsYk,1695
+triton-3.4.0.dist-info/RECORD,,
+triton-3.4.0.dist-info/WHEEL,sha256=Obtqci3x5vy5ZivY2BiOH9GHO8-xQ0d4HFhTOtXMNhw,152
+triton-3.4.0.dist-info/entry_points.txt,sha256=js6289FRk18_JLmbNfGsmtKP77D6aYawJOSIHv3X89I,176
+triton-3.4.0.dist-info/licenses/LICENSE,sha256=kmQPuXIi_Qppj_KM4MN4LBcmI_jWxgm1V2NqgPKPuUY,1132
+triton-3.4.0.dist-info/top_level.txt,sha256=WBiIZyv6n9Y7MIh-HPHSv2w1RDk7EFL__7ZgQRrmHYs,7
+triton/FileCheck,sha256=tu9gCl1mk-6JR5qSJzg7it2Ucw4YTwtR3jZQZ7wI728,1078376
+triton/_C/libproton.so,sha256=Df7RmCCYQDm9ADlsH5E1ayryhvrjT4Sz9DkayLHwRJk,12378896
+triton/_C/libtriton.so,sha256=QBzIpHtIHEt061XduozgO6HMktsGUq9UHnxU7h0XqZU,352634712
+triton/__init__.py,sha256=CEQdOZ6zLHuEVGoJ7kl2YwcfBBIPBkOQzzDjHr6ibOM,1464
+triton/__pycache__/__init__.cpython-310.pyc,,
+triton/__pycache__/_filecheck.cpython-310.pyc,,
+triton/__pycache__/_internal_testing.cpython-310.pyc,,
+triton/__pycache__/_utils.cpython-310.pyc,,
+triton/__pycache__/errors.cpython-310.pyc,,
+triton/__pycache__/knobs.cpython-310.pyc,,
+triton/__pycache__/testing.cpython-310.pyc,,
+triton/_filecheck.py,sha256=iWl8uL4LJeV4En4h4mzUbDnrmXB4jXeEgy4_uqRURH8,2845
+triton/_internal_testing.py,sha256=MpXYuQlvJUYtFAmFcfzlU7dyIDEQB_XirJ96IRujMTA,6326
+triton/_utils.py,sha256=XTYb3qDDaVmbhmXbm6ChMTYTW9jeE538jZwJE_eliQg,3539
+triton/backends/__init__.py,sha256=X7290kf96Fk9QnfLScsX4UDG3zPyH_-31E4A7pVOijM,1612
+triton/backends/__pycache__/__init__.cpython-310.pyc,,
+triton/backends/__pycache__/compiler.cpython-310.pyc,,
+triton/backends/__pycache__/driver.cpython-310.pyc,,
+triton/backends/amd/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+triton/backends/amd/__pycache__/__init__.cpython-310.pyc,,
+triton/backends/amd/__pycache__/compiler.cpython-310.pyc,,
+triton/backends/amd/__pycache__/driver.cpython-310.pyc,,
+triton/backends/amd/compiler.py,sha256=yaF0MqfZ81-fL1Jb5aDxGGGXs2j-pVOVpneWQT6DOUs,19966
+triton/backends/amd/driver.c,sha256=hu5_QLMJVmeyR5zYDWfDAklZckISaAFM7kKOg9MpuWE,8612
+triton/backends/amd/driver.py,sha256=_6eatc73GE1yz6RbsWSO0iNs49_kgHjH3Pe9DsMbKgc,23664
+triton/backends/amd/include/hip/amd_detail/amd_channel_descriptor.h,sha256=_2myGIdBTE0plFbGKOSx8HUqGZd0UBHo-YvKe2xkpbU,11708
+triton/backends/amd/include/hip/amd_detail/amd_device_functions.h,sha256=1TwUYh4RJhoiz850vLNicO1fFxFHR-vC-16ttDGDGGw,31367
+triton/backends/amd/include/hip/amd_detail/amd_hip_atomic.h,sha256=KfiNN5FjV6mqSAOam6VJDu9tI7l8uaRUrQ5EMiP5Ymw,50830
+triton/backends/amd/include/hip/amd_detail/amd_hip_bf16.h,sha256=AWsz68vSfi9PnCsIIMOQkCStRLbEat7f6om9_J2Ahj4,61352
+triton/backends/amd/include/hip/amd_detail/amd_hip_bfloat16.h,sha256=cFJlQEELGau_9geACeuiiFHyuAWCD6-VuSqcTnqajX0,9484
+triton/backends/amd/include/hip/amd_detail/amd_hip_common.h,sha256=dzkuIzuklqTRaNJjKLqfFEm6Fh4tK_FkTjYHFsZkmCI,1370
+triton/backends/amd/include/hip/amd_detail/amd_hip_complex.h,sha256=SEygl8X_MCXDVXxNIBm5Ds0eWwa-ojVXUUW48SIgsX8,5855
+triton/backends/amd/include/hip/amd_detail/amd_hip_cooperative_groups.h,sha256=t8rqzpZS--LGLI1D-pNBNCp7TCKGS0H136ps6m6VOlI,31861
+triton/backends/amd/include/hip/amd_detail/amd_hip_fp16.h,sha256=86Nw97iaiC4QV5xBv8d3Bwc4FioMh5DQuCHj3sh_Yrw,57854
+triton/backends/amd/include/hip/amd_detail/amd_hip_fp8.h,sha256=wc1l471D-BBroLMoV1uEsPXTp-zQjSpq-jF8bqeNZX8,53765
+triton/backends/amd/include/hip/amd_detail/amd_hip_gl_interop.h,sha256=djlpeoEOqtX0gVVRgqqakQZkwNzLudnK_ixbShizU7M,3861
+triton/backends/amd/include/hip/amd_detail/amd_hip_math_constants.h,sha256=u1fIaf-AiWF70ZA1zxVkUIbRqoJLu5lrfYbgt_usySk,5890
+triton/backends/amd/include/hip/amd_detail/amd_hip_runtime.h,sha256=ZvDsQ0AiZnJ178NuAsA7AuHrySXbN3aFs5Z9m2tsIDg,13954
+triton/backends/amd/include/hip/amd_detail/amd_hip_runtime_pt_api.h,sha256=fc4mtHBkWmiSRh8m-dxIxvu9zsweLTwEgohkntYcgJw,9997
+triton/backends/amd/include/hip/amd_detail/amd_hip_unsafe_atomics.h,sha256=w9nJ1S32GRl_ejDiGacteM6Zf84iovIifAzWX8Bze0Q,24202
+triton/backends/amd/include/hip/amd_detail/amd_hip_vector_types.h,sha256=qPdmRJnzlgtjVshkafoHxdHoMLkoYS9U-ZD-TjLznr0,57088
+triton/backends/amd/include/hip/amd_detail/amd_math_functions.h,sha256=46wiaEMStCczEsHtccgHlATfw_0O5j6Z8rlFkC7bmUA,3171
+triton/backends/amd/include/hip/amd_detail/amd_surface_functions.h,sha256=rsQuylNqmNhLb7PZjBz7WbruD_6YIXtOptY2BNJDxVU,11062
+triton/backends/amd/include/hip/amd_detail/amd_warp_functions.h,sha256=-uJy_hBwSxRA9gzGp4UEZ3co8D_UHVNoMr_Rvx19qik,20042
+triton/backends/amd/include/hip/amd_detail/amd_warp_sync_functions.h,sha256=2B25tjpJ_KJGijRBaEy_a2_4HLt_TXQ6eJ57zRNoPOw,11706
+triton/backends/amd/include/hip/amd_detail/concepts.hpp,sha256=7EOkpr2w2-jclUQ115yxtFCkBWJ7btUzhBOe-mR0N0M,1252
+triton/backends/amd/include/hip/amd_detail/device_library_decls.h,sha256=4clSpgf898UVjfZFVnDkcYi75A27crPsuFtLcs1s4KU,7457
+triton/backends/amd/include/hip/amd_detail/functional_grid_launch.hpp,sha256=u7hRB9kQXX575a5C7cV3gKow55DSBUCwO0dTjIswlag,8129
+triton/backends/amd/include/hip/amd_detail/grid_launch.h,sha256=tNS7CQw9gy-z930CElH3n6c5iMvpsQ_WFZK024mNzEo,1830
+triton/backends/amd/include/hip/amd_detail/grid_launch.hpp,sha256=EuAlM3olyrArebqwW5eSxo4gfjvWCGOAGAuLLmFttgw,1370
+triton/backends/amd/include/hip/amd_detail/grid_launch_GGL.hpp,sha256=KpQAuyy1Dyt45WcPaR_x-Ex-onPGEHA01DBbla7TT-k,1219
+triton/backends/amd/include/hip/amd_detail/helpers.hpp,sha256=hi2pW1mXQnbIwvmwWt_nG6A38sqLOd-QP5S9sETTs60,5707
+triton/backends/amd/include/hip/amd_detail/hip_api_trace.hpp,sha256=UMsCaqurHFSRNiHpwjaA8DExAldhh4y0UP_KOxLa25Y,101025
+triton/backends/amd/include/hip/amd_detail/hip_assert.h,sha256=fNsG23KISuY-k5JFoX-5hZ7qGQScisXuHcdEwYlXOqw,3978
+triton/backends/amd/include/hip/amd_detail/hip_cooperative_groups_helper.h,sha256=tQ_XIvGKhvrj1h7gY-IVLmKvIPhsQa0YsBflxdhUHP8,7957
+triton/backends/amd/include/hip/amd_detail/hip_fp16_gcc.h,sha256=BtFsKmTptN4TOHocEicfNbBl2JCdZWKm_bd5mc5OzYY,6660
+triton/backends/amd/include/hip/amd_detail/hip_fp16_math_fwd.h,sha256=63tKWMPdW56qWlH_HbCaF_isVXufm514ol_SxL4YjTQ,5134
+triton/backends/amd/include/hip/amd_detail/hip_ldg.h,sha256=KAEZb9H4z4DDrkaloMOeWzahiDfI2V6c68vWT3jb5fU,3652
+triton/backends/amd/include/hip/amd_detail/hip_prof_str.h,sha256=Xb0M9ztYHRqRLjKFBumbAR2rjbUnoZulweCZKTU8ejU,648748
+triton/backends/amd/include/hip/amd_detail/hip_runtime_prof.h,sha256=eZUI5cscYKb9xC9IqnaY53Jgy1dQjkERwQaw034Bt5g,2758
+triton/backends/amd/include/hip/amd_detail/host_defines.h,sha256=ZyCvaPsp4vcFiEEIt2BhapfYVvWoVI_Q2P9rZHlFmCY,7197
+triton/backends/amd/include/hip/amd_detail/hsa_helpers.hpp,sha256=Os-sJQOFI_0Abh8Ql05s0Rtfruk4NsSMfg7BtugxMgg,3232
+triton/backends/amd/include/hip/amd_detail/macro_based_grid_launch.hpp,sha256=6ocsArNa9_R6D6XCuNy8Zq23KG-j2uYsjqNCtnMrJws,67925
+triton/backends/amd/include/hip/amd_detail/math_fwd.h,sha256=nup5YhceJnngoLJCESI8qX08dNpbZci0i78WKu-wfdI,17000
+triton/backends/amd/include/hip/amd_detail/ockl_image.h,sha256=LzRPGMb515_iIAIIcbb2uQB-bTvT4xOjY51VdARD7lc,10538
+triton/backends/amd/include/hip/amd_detail/program_state.hpp,sha256=8QE9OmB8OKTy7rBr3EYEizJI2s-_1tgXpgU7zCA2Ky0,3154
+triton/backends/amd/include/hip/amd_detail/texture_fetch_functions.h,sha256=Ex1lF2gBWJxtC3yP9pXRSFywMp3gbEmyl0Sw8iL91yM,17787
+triton/backends/amd/include/hip/amd_detail/texture_indirect_functions.h,sha256=KkW5o5gMpoVMTRwzfXHA7-kZ9ynI8OaIw6jJ1EB1s98,18447
+triton/backends/amd/include/hip/channel_descriptor.h,sha256=gTYe7SzIg-m3ThOQY2vr5Rh6-uWvUP_d37v8F4T2Q14,1773
+triton/backends/amd/include/hip/device_functions.h,sha256=vkybrdk6wyZP-T1I5PRjtfcMqGYXDeBpB5jhYj358GU,1589
+triton/backends/amd/include/hip/driver_types.h,sha256=m1HI80HC80qkTeco2Jd07woL_jTy48lz9JiDCV_8zsg,18985
+triton/backends/amd/include/hip/hip_bf16.h,sha256=lLw6K5ltb6AqSuINYTq8flxxsDkBP8Y2zbqmUjBcG9c,1571
+triton/backends/amd/include/hip/hip_bfloat16.h,sha256=Nqoy9VjfjglVx2_NJcp8hyT1sJUukXRWj8XMlidv1yA,1755
+triton/backends/amd/include/hip/hip_common.h,sha256=q5aPhG3DHW0iUJ7ayS5lfM_ZnZQNbMmLmfdHlOwbPdA,3450
+triton/backends/amd/include/hip/hip_complex.h,sha256=TmdzQP5oVPfhBVARJYcR5eyv9HInmKMFuFoQ_1ECk_I,1594
+triton/backends/amd/include/hip/hip_cooperative_groups.h,sha256=gMLvaYQ3b-f1vcoMtEwtkN0hO5__zNfP5p5oBKmv_SE,1878
+triton/backends/amd/include/hip/hip_deprecated.h,sha256=gFLuCuKn7R_xCfum_i_Q-vi3Lg8NWHKphKZKze8DwEo,6340
+triton/backends/amd/include/hip/hip_ext.h,sha256=mlzOesF-X62g9AnWdA4MP99GRu_VtwMbffOJFloLtRc,8609
+triton/backends/amd/include/hip/hip_fp16.h,sha256=vKJh-zgDWUW7NyXxtv2ho6aVLXX8BIPfzCigEQ5d6I4,1523
+triton/backends/amd/include/hip/hip_fp8.h,sha256=C4qn0im7Uhvp226VmL_QbF2b45Hhss2eokdSbqWkBcs,1433
+triton/backends/amd/include/hip/hip_gl_interop.h,sha256=-GwkSFMBneM8akFE7pqlhi0k-Ft2uz5674wGoiaU43Q,1438
+triton/backends/amd/include/hip/hip_hcc.h,sha256=RYrArDlnTEP89xKbzIpW17_bsBY5moCitq00PL-4oWI,1307
+triton/backends/amd/include/hip/hip_math_constants.h,sha256=8bSfve5E7cDuvNAUkFUeQwSLg3iJJHuqhuD4FmHNxEM,1588
+triton/backends/amd/include/hip/hip_profile.h,sha256=sjsNuduu5Jd6s7sJndZvZLlE0RZ0wN1rTVwv5nR7If0,1304
+triton/backends/amd/include/hip/hip_runtime.h,sha256=uy90l8Nep6xNUzeGcHMoDv84BT3hMpieTV-5ijkpL5A,3058
+triton/backends/amd/include/hip/hip_runtime_api.h,sha256=h5-nVJmqq2vr9P5EBimA7DwOE339eC6dt0uzk1DaC58,402475
+triton/backends/amd/include/hip/hip_texture_types.h,sha256=AhkvjG4cDjf_ZFLg5SsSTfBnXG614PBK1XVPa7irZbk,1237
+triton/backends/amd/include/hip/hip_vector_types.h,sha256=6FcBMBkP3ZN1Enalpa9hV0VopxdBJvbUCuaxISgzbTY,1630
+triton/backends/amd/include/hip/hip_version.h,sha256=3MuxlZXlLLrhLllRr-1yrIZyv7l_zknuZrT8bDDtm3g,407
+triton/backends/amd/include/hip/hiprtc.h,sha256=dBxesFd3NCvG-NQ99s61i4fUQXfoHNmYhdF6CtE9QHQ,15904
+triton/backends/amd/include/hip/library_types.h,sha256=tPOJTQedPH5qC9meawLgKpnbFrQC2WKlfo6s0rhKoZc,2370
+triton/backends/amd/include/hip/math_functions.h,sha256=frzdJ4veBG8n9ALO4EmRrdOiDguR6FP6ygLnvOnVVSM,1815
+triton/backends/amd/include/hip/surface_types.h,sha256=uQHjITphDM7k4pnuEoDEupMUxBobzvhJpSy0unpegh4,1959
+triton/backends/amd/include/hip/texture_types.h,sha256=CtmdykZfDikhnrVfdJk3w2VK5X3Af_6rEKzU-VgLu24,6687
+triton/backends/amd/include/hsa/Brig.h,sha256=5H-btCHq40qgjjpwVAoRWf3E0ccf-J6UCPEcKx_hGKw,32705
+triton/backends/amd/include/hsa/amd_hsa_common.h,sha256=q_zN0eq-dwR7FnQ84PcpV3yZyvjHsouIAjJgKltGoX8,3912
+triton/backends/amd/include/hsa/amd_hsa_elf.h,sha256=lBT57uuPT6ra01HQtM1O3RhVKW3n41AjESDSi6KVN7w,17306
+triton/backends/amd/include/hsa/amd_hsa_kernel_code.h,sha256=C55F8a480QsW16-iwN9TIT3cKnGh6GoeoEaEv3aVh4g,12659
+triton/backends/amd/include/hsa/amd_hsa_queue.h,sha256=ZJ-k5wY30heLmQnGB0VUz36XCiVHRmspg5FRNMGIk_U,4766
+triton/backends/amd/include/hsa/amd_hsa_signal.h,sha256=FDegZnWQC04GtnqHjXOBsB-AoVSaqdhNY6Mwbua5FGA,2947
+triton/backends/amd/include/hsa/hsa.h,sha256=msdMXlo7LeNQzpBQXj2yFjZqjcWerqB46vETGGB6jJU,191191
+triton/backends/amd/include/hsa/hsa_amd_tool.h,sha256=pyZSyIVl-UA5AOhte78jvn4V3hCd0dxJAIv7KeADsPs,2843
+triton/backends/amd/include/hsa/hsa_api_trace.h,sha256=GRBMFBWlv2dYJIT8BAWa1y_q-veLIgEVa1uIm-eM-Yw,29602
+triton/backends/amd/include/hsa/hsa_api_trace_version.h,sha256=yU2aATDJyhnCZF-FmgeF2wnp-EvPLE7n5zSuw8CNAqc,3248
+triton/backends/amd/include/hsa/hsa_ext_amd.h,sha256=zfiJ_FLsLVRr3_O4FYyoMQG0zYn02EolUKCh8e8vgeI,118084
+triton/backends/amd/include/hsa/hsa_ext_finalize.h,sha256=sv0AZbDM-B1wIdQ3cHTMlpUtNacQN2PkOgX90IZol_o,20227
+triton/backends/amd/include/hsa/hsa_ext_image.h,sha256=t5YJm_aw9EePCeFL1hoIfQ8ubIjBte-ptfReq6Ts-8Y,54232
+triton/backends/amd/include/hsa/hsa_ven_amd_aqlprofile.h,sha256=IR_vo3kSqcTs-gnRdpXW3JE1RHQ71FBi4S81G8GtpZ4,19823
+triton/backends/amd/include/hsa/hsa_ven_amd_loader.h,sha256=c6cxPAzAox7u6IbFzEkQZfCuRl-Kr39WhY2_w23X1R4,26146
+triton/backends/amd/include/hsa/hsa_ven_amd_pc_sampling.h,sha256=1jQvi96s94-GjOGktmvpqjVRsTGANugOsV6XmgMfivk,18767
+triton/backends/amd/include/roctracer/ext/prof_protocol.h,sha256=6FAcvVD-dNM7uulFs2B-aTxw5xOAWGy6evdD4yUaebA,3849
+triton/backends/amd/include/roctracer/hip_ostream_ops.h,sha256=Si6RFHPn0QtMpSBboKFyfkrcOMYhTiom5oUnDEqRnP0,188184
+triton/backends/amd/include/roctracer/hsa_ostream_ops.h,sha256=jSHN5Ltd_EJtecE59xJS4wL_CuLuNkbO3QMqDgMpunk,69906
+triton/backends/amd/include/roctracer/hsa_prof_str.h,sha256=f0pO8T0JBnG_stZ_Bgawx-5_B2BNS7s9ogvEldA0UFo,124187
+triton/backends/amd/include/roctracer/roctracer.h,sha256=B8sHz2DMNprP7EqNWIGwVLY1KQMpxmhfVy4UoR8dzzY,23849
+triton/backends/amd/include/roctracer/roctracer_ext.h,sha256=vLaZ8peAxSy0cwrdEalKnUApkKspfa04iw1Mr_Zcio0,2940
+triton/backends/amd/include/roctracer/roctracer_hcc.h,sha256=NlF3R8JQ9oX9lGpm0b2n-EWJ0r3y9sP9wbwnoucaCuY,1303
+triton/backends/amd/include/roctracer/roctracer_hip.h,sha256=RCzYuNw1vLR7xK4rb06TtM9TU546UYKHJ83IMHmZEm8,1432
+triton/backends/amd/include/roctracer/roctracer_hsa.h,sha256=M8APM64XNAWSslxQisM-pcmKoUQaUdTMaKvSACyt0Ag,4108
+triton/backends/amd/include/roctracer/roctracer_plugin.h,sha256=8GGE1zDbdPCVJtbmwOCYq7X0mwFjfWRtzDYKLD4cKys,4786
+triton/backends/amd/include/roctracer/roctracer_roctx.h,sha256=gBjBk5vb0l3PbBSQ7V9iFtaM_RzkIDJEW1A_PXBihBM,2014
+triton/backends/amd/include/roctracer/roctx.h,sha256=RhJXUXRhSJ5LRE_1gm7E6-bjEMrfcFBLDLuf3UxAIh8,6717
+triton/backends/amd/lib/asanrtl.bc,sha256=1xv2RlU3WvbdsghHlmhwiHewGM2B5dKts5bERM6S89o,24508
+triton/backends/amd/lib/ockl.bc,sha256=wQKCzkKukIHbu0lyjKUYlhndc7S27xto6L54J0Bn-C0,246124
+triton/backends/amd/lib/ocml.bc,sha256=UPNTXW0gCXUNB-c6orSYwb-mz9_mjUc7zny_vfFza44,205964
+triton/backends/compiler.py,sha256=MY2_cQG26p68z8VwRv2Nlj_h2DfEhwBbN-30caMgep0,2840
+triton/backends/driver.py,sha256=AN60upJlPgia0JwvZ8vIVgLITNPuI0fdz8zMIIHPpF4,1450
+triton/backends/nvidia/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+triton/backends/nvidia/__pycache__/__init__.cpython-310.pyc,,
+triton/backends/nvidia/__pycache__/compiler.cpython-310.pyc,,
+triton/backends/nvidia/__pycache__/driver.cpython-310.pyc,,
+triton/backends/nvidia/bin/cuobjdump,sha256=rR0PBpn0ZgNBbrWOe5_fmik-lfkxLJ33_W_aVqbDDUE,569008
+triton/backends/nvidia/bin/nvdisasm,sha256=EIC8kJowIHYf9MeKm3vZtJN725wJeHCcvlI4HeYSofI,5894744
+triton/backends/nvidia/bin/ptxas,sha256=yWCk8jixfVxdPAGtK7wevSxa7MRZy00iO_8QtF-bj8o,31912192
+triton/backends/nvidia/compiler.py,sha256=cDz_7DSBiGww3FmTq8xCXf9tL9_M4lKLfMyZYJnEoRo,19210
+triton/backends/nvidia/driver.c,sha256=HoLBXJUFGTaQBVR7b4FhgQwoAVUMr2oeBU2NejTEnSQ,16281
+triton/backends/nvidia/driver.py,sha256=RIwj3aWIizepevosHWiDWMUT4IfE2s-kHOgmgnx2AvU,25397
+triton/backends/nvidia/include/Openacc/cupti_openacc.h,sha256=Z0OM5e_hbd3cxdXyn3SCHqBBQawLg4QORnlm57Cr2-M,3513
+triton/backends/nvidia/include/Openmp/cupti_openmp.h,sha256=E1WNmeb_7HaUSmBegtUNe4IV1i7pXeNxgzIlyKn1zrM,3491
+triton/backends/nvidia/include/Openmp/omp-tools.h,sha256=AmuC_xPC7VPu3B-W4PmXuCNufFawhY8PjNXePaQFAOg,37403
+triton/backends/nvidia/include/builtin_types.h,sha256=JxT9Vf2q2snxTBOL9ACzNmYzTWACO2VOVUu1KdFt7_g,3150
+triton/backends/nvidia/include/channel_descriptor.h,sha256=oZIDO1kdexPb9jltUx1AsXAFknvRWAAr1456925Pqig,21846
+triton/backends/nvidia/include/common_functions.h,sha256=22LTZRVcPZzEH6MJda7nNMCvMgIjSTe0OKR7sEQj6kc,3410
+triton/backends/nvidia/include/cooperative_groups.h,sha256=y2cFxa6e-saEFA9aW22ZuTwi0wud7eEHq7XN3v30LT0,60684
+triton/backends/nvidia/include/cooperative_groups/details/async.h,sha256=xsEHCZP3nuEY3l2p8SU2d1226XiXumUvDP_Gyh8PdVY,19122
+triton/backends/nvidia/include/cooperative_groups/details/coalesced_reduce.h,sha256=pBQgFY7i64V87XNATg1UEIQHVNYOItQtHjS5B4yn8pc,4257
+triton/backends/nvidia/include/cooperative_groups/details/coalesced_scan.h,sha256=DfZv5d5W0XJv-tZVhgrIdjLjs6aCx_u0oy1lDIpjo1Q,7314
+triton/backends/nvidia/include/cooperative_groups/details/driver_abi.h,sha256=v-ZUb4UgGKJk6NR2WCWHD3x_42y-togI1urFn70Gi-g,3964
+triton/backends/nvidia/include/cooperative_groups/details/functional.h,sha256=2BV8i8Bidz0kgxuYkJCAbwFxOIZRyzHgG-c_rVKhRzc,8905
+triton/backends/nvidia/include/cooperative_groups/details/helpers.h,sha256=K9jvxnXc5-6Fum1KG4EQKJJrVZ4BhHOSAJbZR4uDL0c,26476
+triton/backends/nvidia/include/cooperative_groups/details/info.h,sha256=FOrp3Ltt4PcbK2fAM5UX9jssFZtj_LqVShzLFcKiSaY,12465
+triton/backends/nvidia/include/cooperative_groups/details/invoke.h,sha256=Osq3K-tZuXHVCMQJ708PjPo-BwMhjhjApO4b0TYLFJg,8616
+triton/backends/nvidia/include/cooperative_groups/details/memory.h,sha256=hES3SfgXIBsj2MFrC_M5COXlOirSBuuhPMAJnWoI92w,5606
+triton/backends/nvidia/include/cooperative_groups/details/partitioning.h,sha256=AQz-TheqX3onqX2RmIUipzYUVB273zhLlHJw_kX9D2U,7153
+triton/backends/nvidia/include/cooperative_groups/details/reduce.h,sha256=MjqMDwT0TyWZk4JWcF3WHw8xtwMqyizA4C3zy7f8ee0,23296
+triton/backends/nvidia/include/cooperative_groups/details/scan.h,sha256=-Ttwb2AfEEY_tsmqJjR2dojkPpoRx387SoqxgvfdBtQ,17166
+triton/backends/nvidia/include/cooperative_groups/details/sync.h,sha256=Ed4K9QrPZi43ddSqZwv1X8NG_CTsXUowSQndoUv82LU,10795
+triton/backends/nvidia/include/cooperative_groups/memcpy_async.h,sha256=erOIHuObdfxRhBWfrXE3wsZF4B2GUuqwzQrsPwKPpbg,2960
+triton/backends/nvidia/include/cooperative_groups/reduce.h,sha256=B0hgDkqM-6ueqTTgb3b34A0RH4vGz8mBf5e2jT1dJ1o,2949
+triton/backends/nvidia/include/cooperative_groups/scan.h,sha256=2EU6T5cWNwftm2B7FicV31PojoI61yo5fHXGRYkGk40,2940
+triton/backends/nvidia/include/crt/common_functions.h,sha256=-U44f4yUGmwDPwd7Q_3Cz5if05xHGPSlAzz5zMylLSQ,13559
+triton/backends/nvidia/include/crt/cudacc_ext.h,sha256=KW6n0ImOZKS0VqVmBHWTXtHI816hh88YeEgUg2aYdVU,3224
+triton/backends/nvidia/include/crt/device_double_functions.h,sha256=A1vB3g0qwnNEfcpT1d9RiGDaxqPXXgYr-Vxe2oMHyxY,39938
+triton/backends/nvidia/include/crt/device_double_functions.hpp,sha256=YYIbqYhb5Qmf8c4YfcC_jytg4FRwcXPjv3TFTwhb24E,8568
+triton/backends/nvidia/include/crt/device_fp128_functions.h,sha256=3iCKrdmPp1NIjrlGR47dCZOgV9X6MmdfmjugrF6DEts,51047
+triton/backends/nvidia/include/crt/device_functions.h,sha256=T4INuRBIlLmd3JEA8H6B5XHVANGV6j8gwyUTj5h_F18,137919
+triton/backends/nvidia/include/crt/device_functions.hpp,sha256=OVHiqBjday_aUFnDKJxTeI0VDZI8ZA6JIdUKeAKR4pA,37991
+triton/backends/nvidia/include/crt/func_macro.h,sha256=EOpDlaM917bh9cwBiFBPF689DCMBw5hFarxLxFt-i74,1755
+triton/backends/nvidia/include/crt/host_config.h,sha256=1eki3w5xuY00gIkdYbmSfZO2SoI8giZWYSTRIL2uFs0,12169
+triton/backends/nvidia/include/crt/host_defines.h,sha256=fDU_0cQdtIvEdM0zZFKY0OboMANEMgHLblifPalPGLk,10102
+triton/backends/nvidia/include/crt/host_runtime.h,sha256=lOpmkxFZVkEp8dcMAGEZRITsh-19o9jy39kdSNLc3Ng,10284
+triton/backends/nvidia/include/crt/math_functions.h,sha256=LyGJ0XUthi6WEi-YVITInha9A6SFoB4fEUUU9zii7U8,238284
+triton/backends/nvidia/include/crt/math_functions.hpp,sha256=u-CGbd0R2FZWdKG-6bdmGSor9KT_wnmISj63lPQKASM,100207
+triton/backends/nvidia/include/crt/mma.h,sha256=BooWALDWATvZupJaL7-GFQRQYOotNe_Fy11I5NGh2FA,62695
+triton/backends/nvidia/include/crt/mma.hpp,sha256=spo0LX71tUCipxK517Bssj0nc-ZHf8oMWzvHoYYB_6I,66599
+triton/backends/nvidia/include/crt/nvfunctional,sha256=FDM0zqWO6bl9jpJKz9U8CMbjt6iTKh18tQalxAvRsag,16900
+triton/backends/nvidia/include/crt/sm_100_rt.h,sha256=3cBiCU11OcjGYpr85edCN1q4m2z91FaGhBtuO0is4To,8987
+triton/backends/nvidia/include/crt/sm_100_rt.hpp,sha256=vbI2CNCY08dDI7zXwp6BNceZKl0ceXG1lveq4w-VNao,6855
+triton/backends/nvidia/include/crt/sm_70_rt.h,sha256=Kf830xymA-zmF7LsunFHLSNyhhT5UiJMocgoHBQeNns,6837
+triton/backends/nvidia/include/crt/sm_70_rt.hpp,sha256=3a_rU-Y0MSB4htBDFY4PCQ_jXiWFTe7WT1ZyhMuCJOA,7837
+triton/backends/nvidia/include/crt/sm_80_rt.h,sha256=MdJHWCRzLM__nDDf1go61rDsl9ydOW3oi6SZBfjUyc8,7743
+triton/backends/nvidia/include/crt/sm_80_rt.hpp,sha256=o-rJu-jpehCeyABGgv-8dYRB7oJTCwuNdvSCq0VURdE,6705
+triton/backends/nvidia/include/crt/sm_90_rt.h,sha256=an47m0XFBaJ3pUX9MlE4-nktP1jb3eJUXhQ3ntZtzc8,11445
+triton/backends/nvidia/include/crt/sm_90_rt.hpp,sha256=YuqVygGV6rgtWtx1J9cPpEI3BXKQBII-Ez6oZFP3wrE,9228
+triton/backends/nvidia/include/crt/storage_class.h,sha256=dzcOZ16pLaN8ejqHaXw4iHbBJ6fXWxfaU-sj2QjYzzg,4791
+triton/backends/nvidia/include/cuComplex.h,sha256=WpcgpaiPhU_o9sTPMcNTEZuyXDIc8x3sz4dUWSztL2g,12186
+triton/backends/nvidia/include/cuda.h,sha256=RWjMnnoyHkdwfNZAOYDyGsLi5VFwUA0OCj9U_rA6mss,1156988
+triton/backends/nvidia/include/cudaEGL.h,sha256=iruZU9xSGAcJ29OEX4K_Uo1o4NGP9hggv2fiOZOfDQo,39955
+triton/backends/nvidia/include/cudaEGLTypedefs.h,sha256=xF_FAN1Kar9oyHJ3cCU7jztTpxX8WylpiuYyYpGGHek,5645
+triton/backends/nvidia/include/cudaGL.h,sha256=gMT1HPGa-siuji0gAsKYr4X45Lc29HKglC_ttNSGyUM,22501
+triton/backends/nvidia/include/cudaGLTypedefs.h,sha256=dClpQI-LuXgF9rPSBsj7OkIg8g_fXDjT0hLZS8TGpOg,6576
+triton/backends/nvidia/include/cudaProfilerTypedefs.h,sha256=F2aWLIKv_AhNbxNOaZVcRsxIh0kuscnV8UMWWxkBAlY,3297
+triton/backends/nvidia/include/cudaTypedefs.h,sha256=SKfAvTOj19zxsiLGKhoxXPiopKqoe5hjj5iXkR2_v6E,115169
+triton/backends/nvidia/include/cudaVDPAU.h,sha256=Np7Nc2Wjaz--hkpbhW6f9aapr-NbcPDAgkot0sJerco,12694
+triton/backends/nvidia/include/cudaVDPAUTypedefs.h,sha256=wz8nyOUdwM9mH9JO3QZW-A9dyxt-IufSX7nggSXpCNs,4144
+triton/backends/nvidia/include/cuda_awbarrier.h,sha256=3ZH-ZlXODhSiwSY9rqSni_EQwi25QMHP6Tm-zOdxBwE,9340
+triton/backends/nvidia/include/cuda_awbarrier_helpers.h,sha256=OCskCts5bCKl_RKBe9M74zKSIsVpePn44S_aJp1tFXE,12489
+triton/backends/nvidia/include/cuda_awbarrier_primitives.h,sha256=n5__E1jYYDhlgH-f3u8MQjtz57UZ7v5VshhMye1eicM,4699
+triton/backends/nvidia/include/cuda_bf16.h,sha256=TVoq2IrbF5g67wUF7W7SoGA0l8ecEDu6gskoMB6hIxA,204512
+triton/backends/nvidia/include/cuda_bf16.hpp,sha256=OukWXoN6bgRlC-p8CFbhUN0G0uAJb_zos1mCPagscnI,136544
+triton/backends/nvidia/include/cuda_device_runtime_api.h,sha256=54l66QbwerX0wPKoJC2y7qCdGP8nv1_GgdmMV8A0x4k,46986
+triton/backends/nvidia/include/cuda_egl_interop.h,sha256=awWBBEYvUFM7AURNp2mND8H7_5kGQLRswRveXYBy-3s,37509
+triton/backends/nvidia/include/cuda_fp16.h,sha256=jrFgCo4uM9QFcr_-cAGif2BGp0lJ2ANT_gLPiLJWPdo,206851
+triton/backends/nvidia/include/cuda_fp16.hpp,sha256=o1ITDmuN67N8YUGUcvTpV3IdpS-6wwlm65M_H-8LYKs,120927
+triton/backends/nvidia/include/cuda_fp4.h,sha256=pTEQf5rLfiaU_UMXgnnsS13NH5H9FtHgdeiNuW_NkHY,13823
+triton/backends/nvidia/include/cuda_fp4.hpp,sha256=YYaUu-YRgYdj9xYu4ZDh_uPVffxkDlEr0CD_bhlF8BE,35423
+triton/backends/nvidia/include/cuda_fp6.h,sha256=6xh0E4SNmjmJZD3H5_HoZe08bQ0loUE8y3cbO19-Ad4,13963
+triton/backends/nvidia/include/cuda_fp6.hpp,sha256=qa838buZeLP32xBVqbo71uFSW5RnBWx9qp5D-SR_xc0,56455
+triton/backends/nvidia/include/cuda_fp8.h,sha256=QSTMRb9l7I9mnvT1_8KXNqLO48wWaWEgG97bDjEh1ic,18072
+triton/backends/nvidia/include/cuda_fp8.hpp,sha256=6AABZPfPlK-jmQyMdbTEE0PZTlULjuLOrsQ0Z_cubBw,97230
+triton/backends/nvidia/include/cuda_gl_interop.h,sha256=VQEswFeOBF6JN6Q0pdlkvc5WT7bD1FnTfKewvANulCc,19150
+triton/backends/nvidia/include/cuda_occupancy.h,sha256=0HavrMIWXGxIujaq72iX31-73Zprx0WBYdiln3ZNP2w,71302
+triton/backends/nvidia/include/cuda_pipeline.h,sha256=0enXG49wN4JajlQi3ahbp2ei_ufTY_Mznic7zfWmKHM,8130
+triton/backends/nvidia/include/cuda_pipeline_helpers.h,sha256=bo1L7e6vCuM-K3Il8K1z4wJUja5DyXQKdo_hSWUME-E,13852
+triton/backends/nvidia/include/cuda_pipeline_primitives.h,sha256=FnJJtuV6rHr6LgL56XDwilcSbFr6W1Hj6mf1AJaMI20,8675
+triton/backends/nvidia/include/cuda_runtime.h,sha256=GqqE7SrECGrN-Qg5Dk90LSjs-xvKlHZpRLlpH7LUehM,98570
+triton/backends/nvidia/include/cuda_runtime_api.h,sha256=EWhSESFT_vV5eYZpTBEu4EvgNtE9rhmHP503XnIGHIs,655943
+triton/backends/nvidia/include/cuda_stdint.h,sha256=XbFOk9CtJjKqk7PpYNqbSVsDxAsVM8avA4rWpPi0BjQ,4093
+triton/backends/nvidia/include/cuda_surface_types.h,sha256=Mw5Lo4b8Q-f9mogOvATGyHhu9d2t2K6XOxuqtZrSh3A,3688
+triton/backends/nvidia/include/cuda_texture_types.h,sha256=ITbX-JNnP7Rm-JSgNVdJ9pq6k8FVor8RbnruDsKq6sk,3688
+triton/backends/nvidia/include/cuda_vdpau_interop.h,sha256=bXQanWc2IFXZAKWNGl2xAz9nLvFmQpWyGrsDvfeS9FA,7727
+triton/backends/nvidia/include/cudart_platform.h,sha256=YN6sKhB0b9w5tGX1IYL7ulJVPrWAiX9A44qLv4EtW5Q,2717
+triton/backends/nvidia/include/cupti.h,sha256=JkVyAGTIMYzwm62dfVqas3nMcILhgP_Wdz6fh4_NED0,4697
+triton/backends/nvidia/include/cupti_activity.h,sha256=gJKGlG2JifW36Lx-ujJcKBlnUrNOoTxar51k28GrUtU,229848
+triton/backends/nvidia/include/cupti_activity_deprecated.h,sha256=B0p4zbll2vUn1j0ImTG6QIbpp6Hiw8y-X021Zmf7flE,137602
+triton/backends/nvidia/include/cupti_callbacks.h,sha256=aZ-SE0YMFfT9R-Uh5MHboPg0ypHMjeSSAJw3zdP7OCs,29689
+triton/backends/nvidia/include/cupti_checkpoint.h,sha256=rTz8JoWxqESBXyZWUhZJGm4xeYcx4OJOtJ7Ld13T_b0,5264
+triton/backends/nvidia/include/cupti_common.h,sha256=85m74bxUgXp3tEaPQpezeazmpsNMw41PsjNSYmQdT20,3514
+triton/backends/nvidia/include/cupti_driver_cbid.h,sha256=mkBNPYkLfcExhQZFDo0iYHlaHJWGD2vOMdtzaV-lEUk,77280
+triton/backends/nvidia/include/cupti_events.h,sha256=81wcvFvvHj8RmECbbEp5FfgjJIQDoC_81FhvqznFupY,51923
+triton/backends/nvidia/include/cupti_metrics.h,sha256=zmfZxq5VkUJp6Tj7oXEkP9oycRNw1zB9VNhoQlbhiN4,32175
+triton/backends/nvidia/include/cupti_nvtx_cbid.h,sha256=_azPtR1g4qivvX7qbvHRUg0RHCWF7iEOJyHMN9qZe9E,5912
+triton/backends/nvidia/include/cupti_pcsampling.h,sha256=ycJHT36DmPIaVzHsB3xxjXkhFyEfMCJOl3LbCsHFgyA,32144
+triton/backends/nvidia/include/cupti_pcsampling_util.h,sha256=lx8CaNXowJe5Zvc06LE-u_Zry_jODs1mM6j9Q5WIX9E,12430
+triton/backends/nvidia/include/cupti_pmsampling.h,sha256=U95hKOwIkZSbGNVP11QSmMawB8qdJsljY_tUJY4vedc,20440
+triton/backends/nvidia/include/cupti_profiler_host.h,sha256=MkkfXlKBRrRL4NfaPFiuE4D4z_gpmxiBWWTBixyyMTk,22155
+triton/backends/nvidia/include/cupti_profiler_target.h,sha256=MdLutIefwdMTI7wsce0LO3NuCm3FRgFR3GxAkqadMs4,32294
+triton/backends/nvidia/include/cupti_range_profiler.h,sha256=ue5bUA-3xCwAtQGyDe5O1d5rAmRbVbcrXKfITd4xM1I,18779
+triton/backends/nvidia/include/cupti_result.h,sha256=xQqBsZRoicBSWdk1lZAE_WeZj88MLH6ClTo58oshx-8,13114
+triton/backends/nvidia/include/cupti_runtime_cbid.h,sha256=BZJnzsvf2RjRlHKEhPjCk0CdjLI9_L-nClTwe4v9NUc,48372
+triton/backends/nvidia/include/cupti_sass_metrics.h,sha256=3RW9snJuFQdOhrEn3wDJOru05q0V_zssWrqD7tvVJKw,19674
+triton/backends/nvidia/include/cupti_target.h,sha256=x4Vz1Upb6m9ixmVpmGaKQldDWYQI3OZ-ocEXGzNK0EE,1263
+triton/backends/nvidia/include/cupti_version.h,sha256=KFXmjB4o-iZGvO8la9Sf9Urg4q4srmEimnxbPCyd2N8,4506
+triton/backends/nvidia/include/device_atomic_functions.h,sha256=OR2jNSfSKzaFri74zh4Vtz5M0z9UDBU3rKeC1rYaVQs,9500
+triton/backends/nvidia/include/device_atomic_functions.hpp,sha256=0e7MOiNNUnnloXpB_r9WT5YOws5cxgzQQAzRCYvgaFA,10486
+triton/backends/nvidia/include/device_double_functions.h,sha256=KUxId5Z1fx8SWfLRTxPD7RB-zN7zslzb4n7JaJLfL3I,3452
+triton/backends/nvidia/include/device_functions.h,sha256=bWSrhTYE9NQlss7xMSMEVusvto9j2fgUDXWVH2W_cOA,3410
+triton/backends/nvidia/include/device_launch_parameters.h,sha256=H1_CC-vvAaS26ys4XsTFkMgTxUTciAjdjswjizkisvQ,3846
+triton/backends/nvidia/include/device_types.h,sha256=2LFxoZBJPoA5V0H1EbKTEaXDi3GDJPtzOPdRHDaucIQ,3588
+triton/backends/nvidia/include/driver_functions.h,sha256=cN3IjRAz2Mj2Pj35SyxJIkZNDDusnJqaqzBdMzpQKbA,4625
+triton/backends/nvidia/include/driver_types.h,sha256=mMNbiIwg5E3k7Sk685YCSvnKYmfQ3bxWv3bkEgzOtNU,200083
+triton/backends/nvidia/include/fatbinary_section.h,sha256=NnuUfy358yGJx4enq0pBnetjv17UWa-nOlgYToUitrw,1809
+triton/backends/nvidia/include/generated_cudaGL_meta.h,sha256=dfd2QuaRdEjbStOKvaQLi1Md_qrpRQh8PfyZznJ8bWY,3115
+triton/backends/nvidia/include/generated_cudaVDPAU_meta.h,sha256=fAedsoQxaU3hIAApAWDOKsa9kgcuQw4tdyf8klLm-3k,1453
+triton/backends/nvidia/include/generated_cuda_gl_interop_meta.h,sha256=LXOqvQCej0sCgAT1LUKKYZ466EFxN4hIwf9oIhXOLF0,2250
+triton/backends/nvidia/include/generated_cuda_meta.h,sha256=DDdgfW84GVtsGbr7daNJchmmZDS_xfvDHvFCm3I1OEc,98664
+triton/backends/nvidia/include/generated_cuda_runtime_api_meta.h,sha256=CuziaDwO2Mh33paCLGKqi73PQfYNmzp38wYrhAK-fng,72208
+triton/backends/nvidia/include/generated_cuda_vdpau_interop_meta.h,sha256=8OLqWN26aEYpTWUXtbHJvA5GYhVv3ybYVOTW7yK37z8,1367
+triton/backends/nvidia/include/generated_cudart_removed_meta.h,sha256=X3I5WXmhtsJNNlgY7coJ5vg4t11G5FRR6Xo7MboIeck,5172
+triton/backends/nvidia/include/generated_nvtx_meta.h,sha256=YHb_RD8g3s4m8PJn7Z0wnxvUHarl7BOAX5ADr-BL3HI,7513
+triton/backends/nvidia/include/host_config.h,sha256=BscH_GazAZbbotddVzL5RmafbQ-QjRx8f-I1O01IBW8,3380
+triton/backends/nvidia/include/host_defines.h,sha256=bBQwQF5C1N1c2qpLV56g1c-weu9Ysgz-gIf2Kn3uz_A,3386
+triton/backends/nvidia/include/library_types.h,sha256=i-GFcw92wvcixs2bQjOj4I_q26HYY_VY4DpDvHWQCjY,5156
+triton/backends/nvidia/include/math_constants.h,sha256=cV6hAyQe8X7f7MBtaKjjIJq3BycOUDp6I5cizJX5HLw,7608
+triton/backends/nvidia/include/math_functions.h,sha256=5XcC6j-fJKttvhwc4hZNoLHNw808a2ZYIOtZ7ry7yd0,3398
+triton/backends/nvidia/include/mma.h,sha256=IY_VenxuEncwGq92MhrWUb-Xswh0ekAXLy9Rbxhxa2Y,2932
+triton/backends/nvidia/include/nvPTXCompiler.h,sha256=lF1ssKlrjsNWCsp0UdhbB6GyOgFCDO1q0ZBDzOswlj0,14471
+triton/backends/nvidia/include/nvfunctional,sha256=IkFoCi_Q4OhP9nEuBI-5jWwFlR_PfG05hJH7lSMsfWc,2975
+triton/backends/nvidia/include/nvperf_common.h,sha256=ykeTJ5I6c0z8KqMQh13hlJaMaHiqqVUB60oGXOCu7Bg,17255
+triton/backends/nvidia/include/nvperf_cuda_host.h,sha256=gC0JWoUdTyAOJs8y4uoJIhie9Xq4yF4HzoumLsYNVzU,7562
+triton/backends/nvidia/include/nvperf_host.h,sha256=wCB4mR8aIHWiqT1TsxztQgWBRh_yiq5ABFm8sb3_jwg,49197
+triton/backends/nvidia/include/nvperf_target.h,sha256=jRqQtuNLTrCzPDdyeANkTrPEijSCTjLy2A1qjKu0SdM,23607
+triton/backends/nvidia/include/sm_20_atomic_functions.h,sha256=x4ycINVq__l9B4SQPD-I48jQbKxxdBmgp8Vf2GO0Qfg,4478
+triton/backends/nvidia/include/sm_20_atomic_functions.hpp,sha256=1l5NLM8DhDbqYZ_E51LoqElQJXObkbwo57d3r-4uEbE,4107
+triton/backends/nvidia/include/sm_20_intrinsics.h,sha256=axeDr7y6nT1V6LzrSWNSaHUwXgiNjPbXn1T6Uh7hlNM,57702
+triton/backends/nvidia/include/sm_20_intrinsics.hpp,sha256=mJTejRhw1prNiP_ax1OPbkYlhEqBqO4nVI3DRDXIzpo,8392
+triton/backends/nvidia/include/sm_30_intrinsics.h,sha256=b6W8Vxp9vD9OCJI6lZuGyZYXEdQ3Ei8PTAloHNkwCcQ,16978
+triton/backends/nvidia/include/sm_30_intrinsics.hpp,sha256=yX0ebd265tJ-BDhvluP2BhadPuWXpRZPI2eeQFFt5ys,24567
+triton/backends/nvidia/include/sm_32_atomic_functions.h,sha256=HGnZgQHACE2AAb6zabGUURc53IsVZelc2BSJqvs9OgY,5703
+triton/backends/nvidia/include/sm_32_atomic_functions.hpp,sha256=CQTTvOEYp-s5hqAgLvAon11vLYDrDp8cTHdel-XRzBQ,6592
+triton/backends/nvidia/include/sm_32_intrinsics.h,sha256=Xdkogdsjy1vh8u3eGu0i5xTmHxBGAjj6_vVGR-spdOE,33539
+triton/backends/nvidia/include/sm_32_intrinsics.hpp,sha256=Gl8aSLDLcit4W3pKQS19GsDG8RYcwD65HwYB_CeZe8M,70616
+triton/backends/nvidia/include/sm_35_atomic_functions.h,sha256=a3XoEsKRCEOf0Q_5Y__rMfmC4pScv4VkUggVgVJVn44,2909
+triton/backends/nvidia/include/sm_35_intrinsics.h,sha256=0mS5-LCgvZiTvL7-MG_4YwI-zWGvM-s4xyRuMkunMC8,2664
+triton/backends/nvidia/include/sm_60_atomic_functions.h,sha256=_anfNaJsvQpDEorYeUKIkbizYkwrinBcG_ZCiECtLqI,13178
+triton/backends/nvidia/include/sm_60_atomic_functions.hpp,sha256=cgIKddDn2B3QzYlzeBILAP1IRys74QCCxsH0QqaVGls,22903
+triton/backends/nvidia/include/sm_61_intrinsics.h,sha256=h_MBL1UUDxQX_qOddSImzqyFjcrhhm_63G97pGDyreU,10902
+triton/backends/nvidia/include/sm_61_intrinsics.hpp,sha256=N-nQvcBsPMT2Umy5zR69c9K1q366W-Jqe7NpoLTqTmg,6787
+triton/backends/nvidia/include/surface_functions.h,sha256=b1O82SAvEgWWxA9uZTWQcGimzZUoem2QbAET3wh3fZc,6782
+triton/backends/nvidia/include/surface_indirect_functions.h,sha256=vy9QuFVV-ezZP-x2RT9RLp2qIUgdngACOCmalSfVFPA,10877
+triton/backends/nvidia/include/surface_types.h,sha256=XkFXD1nHbeSMgajR-UJE9uQ7TByzJnjdnUL4-yGiufk,4530
+triton/backends/nvidia/include/texture_fetch_functions.h,sha256=KLCmUxf5aY5_UalX8tSFB6e4TrjA8hyUPxLOkMFltAo,12468
+triton/backends/nvidia/include/texture_indirect_functions.h,sha256=lH_y3Ni-hq4RZ0_PMFbBM0th5-OmTn3TtqtpkHHhA8w,21163
+triton/backends/nvidia/include/texture_types.h,sha256=73ntVyg8r8fzKy5VIk6yuvC45GDeWepaLIqIk-M3Ri8,6360
+triton/backends/nvidia/include/vector_functions.h,sha256=WypGkL-IDbGOlay7g_G0p3HO7OLGRE0Do__JtiFoWxY,8003
+triton/backends/nvidia/include/vector_functions.hpp,sha256=afXhNSd3LFTZo96EPtesTLfvxd4nTmLVzgkj967rTRg,10060
+triton/backends/nvidia/include/vector_types.h,sha256=6CJ4yt3KD7zQVfm1NhrgqNYYEDEIZWwaivlFx12nhNg,13396
+triton/backends/nvidia/lib/cupti/libcheckpoint.so,sha256=BrqCvQkje5NM8W2iFy7VlDxYLKo1x5tSz8_rD_cfclA,1644872
+triton/backends/nvidia/lib/cupti/libcupti.so,sha256=_M3F_MfDL4z0s-2bF_fxh6GFpvoKW8wG40NMvRaHyAg,7595792
+triton/backends/nvidia/lib/cupti/libcupti.so.12,sha256=_M3F_MfDL4z0s-2bF_fxh6GFpvoKW8wG40NMvRaHyAg,7595792
+triton/backends/nvidia/lib/cupti/libcupti.so.2025.1.1,sha256=_M3F_MfDL4z0s-2bF_fxh6GFpvoKW8wG40NMvRaHyAg,7595792
+triton/backends/nvidia/lib/cupti/libcupti_static.a,sha256=q22dskj52HUn40wsJ6-5g9AFD_aYtOSqIlNJrbRqOko,43563448
+triton/backends/nvidia/lib/cupti/libnvperf_host.so,sha256=YJ9UBjwlPa_277p5_kklL90jJDCKsP-5kcwSXT6aHqs,25825936
+triton/backends/nvidia/lib/cupti/libnvperf_host_static.a,sha256=sTLoX5YG81JXBoSKm3fLo0RAdP3HqISmgtx8L47XF-4,33480030
+triton/backends/nvidia/lib/cupti/libnvperf_target.so,sha256=LxDhEJ_DQaV0NMKOQAa0WokkeAHiD1rOE1wwLBc-B3A,5275312
+triton/backends/nvidia/lib/cupti/libpcsamplingutil.so,sha256=5vongwd5dPsnZb-py66_mAc233Tuv5lMWcdZaYiuyDs,970064
+triton/backends/nvidia/lib/libdevice.10.bc,sha256=XC-uN8huaMOjhgWpX1EtfRLV89uYYxC-R_VzBKpype4,473728
+triton/compiler/__init__.py,sha256=0NEunzjGCNEVOhYZLDI4pDi_zAaYAgTXNm8U5uxbdL0,242
+triton/compiler/__pycache__/__init__.cpython-310.pyc,,
+triton/compiler/__pycache__/code_generator.cpython-310.pyc,,
+triton/compiler/__pycache__/compiler.cpython-310.pyc,,
+triton/compiler/__pycache__/errors.cpython-310.pyc,,
+triton/compiler/__pycache__/make_launcher.cpython-310.pyc,,
+triton/compiler/code_generator.py,sha256=Rj5tFwqfjMR1-cr2CxOr3nP3Ez2V4EE3ENKQAp66uXc,66887
+triton/compiler/compiler.py,sha256=Y7nu59gv7ql1fTWCWAWD6lwuUSuuzRybookKKdugua4,21524
+triton/compiler/errors.py,sha256=I9Y15pDWcL9heY4SWWdLeMDtW6Iiq2pFXzKfJ6dY_C0,1732
+triton/compiler/make_launcher.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+triton/errors.py,sha256=8WfnuRKLG578mgY6cBA3ECruVMf9ULEKFNgRcJ6IhWM,89
+triton/experimental/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+triton/experimental/__pycache__/__init__.cpython-310.pyc,,
+triton/experimental/gluon/__init__.py,sha256=e2NX3d9SND2hKGmMDCix8_Sg12BMpK3zR3NWHy-fioQ,76
+triton/experimental/gluon/__pycache__/__init__.cpython-310.pyc,,
+triton/experimental/gluon/__pycache__/_compiler.cpython-310.pyc,,
+triton/experimental/gluon/__pycache__/_runtime.cpython-310.pyc,,
+triton/experimental/gluon/_compiler.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+triton/experimental/gluon/_runtime.py,sha256=b9KD4D-CuuYxwCwj2YPPpT_JnB9e1G4_ztaESaQjgHw,3395
+triton/experimental/gluon/language/__init__.py,sha256=EEDociOXDeGu9y2FwRKUoGNxJKu7eg2jIi94j7TQxx8,451
+triton/experimental/gluon/language/__pycache__/__init__.cpython-310.pyc,,
+triton/experimental/gluon/language/__pycache__/_core.cpython-310.pyc,,
+triton/experimental/gluon/language/__pycache__/_layouts.cpython-310.pyc,,
+triton/experimental/gluon/language/__pycache__/_math.cpython-310.pyc,,
+triton/experimental/gluon/language/__pycache__/_semantic.cpython-310.pyc,,
+triton/experimental/gluon/language/__pycache__/_standard.cpython-310.pyc,,
+triton/experimental/gluon/language/_core.py,sha256=8QyCvlTYQnqIDDrVa1AG84u7K3zaBAS_81QaJg3RfqE,8911
+triton/experimental/gluon/language/_layouts.py,sha256=H3Zkjmkl-IwJxCC4pnPxsBw-2mGNCNfn9MbY1c1l6s0,8975
+triton/experimental/gluon/language/_math.py,sha256=R9fMFusmpDy3rdA-zwxIIB5nigEg08MeTnSdslA0DQA,329
+triton/experimental/gluon/language/_semantic.py,sha256=SKRJPTtnhfWpuz-deaun845FpHvBvpeW2erGqO-UkdQ,13898
+triton/experimental/gluon/language/_standard.py,sha256=gunBiUjdix_LDVONM-OZ5wuR0i8O5fZLXHmOBEyvbLk,1063
+triton/experimental/gluon/language/nvidia/__init__.py,sha256=SFBuACK5P2XoYcutHEnKjqgRTboU4CPDmJz0hT6dFRQ,80
+triton/experimental/gluon/language/nvidia/__pycache__/__init__.cpython-310.pyc,,
+triton/experimental/gluon/language/nvidia/blackwell/__init__.py,sha256=KHmHVhgmvhLQXsPfwExi_O9AfjQzpKYmqb3zWSy6W4Q,7599
+triton/experimental/gluon/language/nvidia/blackwell/__pycache__/__init__.cpython-310.pyc,,
+triton/experimental/gluon/language/nvidia/blackwell/__pycache__/tma.cpython-310.pyc,,
+triton/experimental/gluon/language/nvidia/blackwell/tma.py,sha256=15xbiY2QmgjVPHvXPJ3MKrAkbqcaZjgx-V3B-kCgo9w,1086
+triton/experimental/gluon/language/nvidia/hopper/__init__.py,sha256=NVReVRoDY3OuXQUrKokuxY86z0QehVSje63H52u-5hs,295
+triton/experimental/gluon/language/nvidia/hopper/__pycache__/__init__.cpython-310.pyc,,
+triton/experimental/gluon/language/nvidia/hopper/__pycache__/mbarrier.cpython-310.pyc,,
+triton/experimental/gluon/language/nvidia/hopper/__pycache__/tma.cpython-310.pyc,,
+triton/experimental/gluon/language/nvidia/hopper/mbarrier.py,sha256=MezUtSQr-FzYM1kbuto1xNE4NimSBZIxP25xkn7nnp8,1603
+triton/experimental/gluon/language/nvidia/hopper/tma.py,sha256=Jih4obM2oGcUU7DYg0T7nSindQQd40zgQh0e1MeLh6A,3508
+triton/experimental/gluon/nvidia/__init__.py,sha256=ISXB4RV7RcCLsU-JhcRFeA29gCBDVk8cTwO2j99ivLc,80
+triton/experimental/gluon/nvidia/__pycache__/__init__.cpython-310.pyc,,
+triton/experimental/gluon/nvidia/__pycache__/blackwell.cpython-310.pyc,,
+triton/experimental/gluon/nvidia/__pycache__/hopper.cpython-310.pyc,,
+triton/experimental/gluon/nvidia/blackwell.py,sha256=cllwlUCE5_YKWqySQZk7wt7Fierz345E5VwztxNRGMs,69
+triton/experimental/gluon/nvidia/hopper.py,sha256=SKDi2fPCB87vMZAF6Em3gfZgif95U4Omeiexn7c969o,1518
+triton/instrumentation/libGPUInstrumentationTestLib.so,sha256=m_fw5-fZSA7eA3_OFseOPWinX2Uz9dDjI8M7u-GB1HQ,6407104
+triton/instrumentation/libPrintLoadStoreMemSpaces.so,sha256=r4lcWXzUV1Y3diI0538D1SoqUO-Gx7c0BAY0zJ0HnZ8,8941080
+triton/knobs.py,sha256=7v1XpeHJtJsT5qshOFVHEf7bYoMyWDn2kgY0k8jNqq0,14524
+triton/language/__init__.py,sha256=XJPQq1rq0SoPcfqkw9YVln7XqP0I25nIGzTa-QmMpiY,6418
+triton/language/__pycache__/__init__.cpython-310.pyc,,
+triton/language/__pycache__/core.cpython-310.pyc,,
+triton/language/__pycache__/math.cpython-310.pyc,,
+triton/language/__pycache__/random.cpython-310.pyc,,
+triton/language/__pycache__/semantic.cpython-310.pyc,,
+triton/language/__pycache__/standard.cpython-310.pyc,,
+triton/language/core.py,sha256=UsbrSmv92MdNW9JfKkyDhDOAZI8drrS1PK7Av2un7A4,116128
+triton/language/extra/__init__.py,sha256=XRXFvr7416pRsh_Rh-X6qV66SiEyVDVbxp4GSAE1mfc,655
+triton/language/extra/__pycache__/__init__.cpython-310.pyc,,
+triton/language/extra/__pycache__/libdevice.cpython-310.pyc,,
+triton/language/extra/cuda/__init__.py,sha256=MBBu2EUYxsp6ygjiwO4Yh1X1EswMstfaiRTMSMGtbcw,407
+triton/language/extra/cuda/__pycache__/__init__.cpython-310.pyc,,
+triton/language/extra/cuda/__pycache__/gdc.cpython-310.pyc,,
+triton/language/extra/cuda/__pycache__/libdevice.cpython-310.pyc,,
+triton/language/extra/cuda/__pycache__/utils.cpython-310.pyc,,
+triton/language/extra/cuda/gdc.py,sha256=QAqc_E1INKjYlW6ERSnb9uWoEBDAQlnxkn2yiIWHJPQ,2185
+triton/language/extra/cuda/libdevice.py,sha256=J7Kl0ejbAIus7-YBn2OSK71lkm3pC7G1J-5ZdHfS82U,56764
+triton/language/extra/cuda/utils.py,sha256=phDcXCFViaq3p4ThwHrO8-FtU-8A8I3nk4mZZJVvTio,4426
+triton/language/extra/hip/__init__.py,sha256=ieSER4LeX9_0horChGUUVwpuKAprkuka8uGAkEBDyDM,49
+triton/language/extra/hip/__pycache__/__init__.cpython-310.pyc,,
+triton/language/extra/hip/__pycache__/libdevice.cpython-310.pyc,,
+triton/language/extra/hip/libdevice.py,sha256=Rf-AmBzcO6ORVzSxSuLXOy0lpoZTsnRAuTvjSF83r-E,17313
+triton/language/extra/libdevice.py,sha256=Dki14elRNmQsz-Ytw9CnOaLCCnte4T6cI8bOzWjN63A,6318
+triton/language/math.py,sha256=CKvuIc5iMKhz7Qgx9w-VcLfOOZadv5svKK4aGZLuHMc,7399
+triton/language/random.py,sha256=jkuFmfgZ8yvKuub9EY27zPvsC6nhkJIk05xf4y-7SR8,7102
+triton/language/semantic.py,sha256=ERQftF6yeuTMmPO722GWpfwug7r9ZDWhxThL1kwLfmI,96950
+triton/language/standard.py,sha256=EwpxORaDOiOdT4QgCnxiFXrsC652no7RptVoF9OszN0,16152
+triton/profiler/__init__.py,sha256=gbZ92q4T_35F5Ub8HalI7AR4p2A00rhkof5-Uo5Fo9A,278
+triton/profiler/__pycache__/__init__.cpython-310.pyc,,
+triton/profiler/__pycache__/context.cpython-310.pyc,,
+triton/profiler/__pycache__/flags.cpython-310.pyc,,
+triton/profiler/__pycache__/hook.cpython-310.pyc,,
+triton/profiler/__pycache__/language.cpython-310.pyc,,
+triton/profiler/__pycache__/profile.cpython-310.pyc,,
+triton/profiler/__pycache__/proton.cpython-310.pyc,,
+triton/profiler/__pycache__/scope.cpython-310.pyc,,
+triton/profiler/__pycache__/specs.cpython-310.pyc,,
+triton/profiler/__pycache__/state.cpython-310.pyc,,
+triton/profiler/__pycache__/viewer.cpython-310.pyc,,
+triton/profiler/context.py,sha256=LsH0trahuaG57C7RXIedizPQzllQXP1Umd4qdYBgEtU,517
+triton/profiler/flags.py,sha256=BFBKQnozRN9Jp18_S5MuIeu5CJMW7_I38pM55qOg2oQ,604
+triton/profiler/hook.py,sha256=FjckK6FpII9JUXRc4PZRB6PjLImjeBcF6qnoeExKsWk,1158
+triton/profiler/language.py,sha256=15at1vlFT4czkt9XZudcfTBD07SH050hKD9XZUhKfaI,446
+triton/profiler/profile.py,sha256=6hz_8EzR2wjsAoILIzq4mFDuTqYa9NaSSYVW6BKRjYI,7146
+triton/profiler/proton.py,sha256=u9--f28vWGJj5dqvlrUop3ZSrk9WjnV-Nmd5kkgT_dU,3864
+triton/profiler/scope.py,sha256=0FdPkga2fOEv8DIan0Vu0BNB6RIspEhqRELq-mLIY9I,3661
+triton/profiler/specs.py,sha256=6qG4YpV29pe3cA-7bgyBNgUlMEo1OXm2C9jAuuUTqVU,1933
+triton/profiler/state.py,sha256=Mp5kcU4xTwZopfXrsgjEE5bQ2HJZR3242e0KkmVw-EQ,1346
+triton/profiler/viewer.py,sha256=5iPuvaYPj_WqRryJ6kaQDtqtsTl_sAVpzNF_v3Vm0oQ,17519
+triton/runtime/__init__.py,sha256=mKL5cqIBDUw2WO80NRCh4s1G8KYaqgM59TTAbTkPPjQ,621
+triton/runtime/__pycache__/__init__.cpython-310.pyc,,
+triton/runtime/__pycache__/_allocation.cpython-310.pyc,,
+triton/runtime/__pycache__/autotuner.cpython-310.pyc,,
+triton/runtime/__pycache__/build.cpython-310.pyc,,
+triton/runtime/__pycache__/cache.cpython-310.pyc,,
+triton/runtime/__pycache__/driver.cpython-310.pyc,,
+triton/runtime/__pycache__/errors.cpython-310.pyc,,
+triton/runtime/__pycache__/interpreter.cpython-310.pyc,,
+triton/runtime/__pycache__/jit.cpython-310.pyc,,
+triton/runtime/_allocation.py,sha256=zaW4B7I7c-2rkVuN7IZaUB6IQSI1t4FvnTPZH-r7DTk,798
+triton/runtime/autotuner.py,sha256=oRfvawx8fdcyLu6QA_Z8HTcFlR2i9NMnCVL0vjcyoTI,20228
+triton/runtime/build.py,sha256=vb6F1-d9-jTxPfxeLGVBmgS-avlhRKxw-CV_1CmLwsY,3784
+triton/runtime/cache.py,sha256=b-qRzNFJiwQanN_q0W3eVhy-GgNAvKu4bWdCcT39tn8,9366
+triton/runtime/driver.py,sha256=seGhU4efCFPVN0KVzd4gmZ1x5s0I_sFyM5NC8brXWF8,1798
+triton/runtime/errors.py,sha256=CwfJXciwel_-K3BfQfKUpLPDWrSyTnGsfJkqJojrdfQ,1052
+triton/runtime/interpreter.py,sha256=IJ0kLHhnoRd9-lwtPk7l8IDs_reaDzLpIBJaH-h3S8g,60811
+triton/runtime/jit.py,sha256=M1bqBguYaMuztS3hH4-T5CI8UrvADyEC2mVuuwKVrvg,36766
+triton/testing.py,sha256=vbEQRNrOnnzRQvVVSaiZrUo8AC0XPV40GJxfvkKYLh0,20276
+triton/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+triton/tools/__pycache__/__init__.cpython-310.pyc,,
+triton/tools/__pycache__/build_extern.cpython-310.pyc,,
+triton/tools/__pycache__/compile.cpython-310.pyc,,
+triton/tools/__pycache__/disasm.cpython-310.pyc,,
+triton/tools/__pycache__/link.cpython-310.pyc,,
+triton/tools/__pycache__/mxfp.cpython-310.pyc,,
+triton/tools/__pycache__/tensor_descriptor.cpython-310.pyc,,
+triton/tools/build_extern.py,sha256=jCr-2hu3nLGBIJhCGUQ1jAyzLttughjkiPGEwRFjLR0,13673
+triton/tools/compile.py,sha256=CP_-yqEd55ejkc2_OYVE7q0Eyh9xErk8KJy2BcdCV0Y,7129
+triton/tools/disasm.py,sha256=T9jiTkdK_0nI3R_4uea0zvfioYdcR-zIZwTfuucgw6g,5026
+triton/tools/extra/cuda/compile.c,sha256=Me7beHPc6WNTwjg85H84DUMCRu4KJdVK2hNNgvlhBZ4,2126
+triton/tools/extra/cuda/compile.h,sha256=n9QKIFZTL4RSsiXtAxBP9XGSnxjyaevQQ9bBpwDsvAg,332
+triton/tools/link.py,sha256=u7qtfZRLriZkAMEGNvj8YF-k1cthmLL7BwHYqBgT63E,11871
+triton/tools/mxfp.py,sha256=YQdpBrGkOVNOtnLeRjMCeVFHWkSwUubGeWsItIjO8TU,11737
+triton/tools/tensor_descriptor.py,sha256=mt4iVVRcNg0gjoytb6iCP4l5vt-H2V3MGeAQfJcStJo,1289
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/WHEEL b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..12e67ca29ff180ca4133d9ec4769226edb266ce4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/WHEEL
@@ -0,0 +1,6 @@
+Wheel-Version: 1.0
+Generator: setuptools (80.9.0)
+Root-Is-Purelib: false
+Tag: cp310-cp310-manylinux_2_27_x86_64
+Tag: cp310-cp310-manylinux_2_28_x86_64
+
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/entry_points.txt b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..d8d06486be664b9cd4a7e4e0fddbc18703fed64a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/entry_points.txt
@@ -0,0 +1,7 @@
+[console_scripts]
+proton = triton.profiler.proton:main
+proton-viewer = triton.profiler.viewer:main
+
+[triton.backends]
+amd = triton.backends.amd
+nvidia = triton.backends.nvidia
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/licenses/LICENSE b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..1d0238e86b1b43e123c9eb136eb0b2c0e1658d63
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/licenses/LICENSE
@@ -0,0 +1,23 @@
+/*
+* Copyright 2018-2020 Philippe Tillet
+* Copyright 2020-2022 OpenAI
+*
+* 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.
+*/
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/top_level.txt b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..a59a965090a6473278f0cf9e7fd1d3cb9cb385c9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton-3.4.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+triton
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/FileCheck b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/FileCheck
new file mode 100644
index 0000000000000000000000000000000000000000..e62f5027b29fc298f8568528ffc9fd1ecf5fcf1f
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/FileCheck
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b6ef600a5d6693ee89479a9227383b8add94730e184f0b51de365067bc08ef6f
+size 1078376
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/_C/libproton.so b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/_C/libproton.so
new file mode 100644
index 0000000000000000000000000000000000000000..3ae418c12fdec41ea2e006d8f8cb8ccba1674074
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/_C/libproton.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:0dfed19820984039bd00396c1f91356b2af286fae34f84b3f4391ac8b1f04499
+size 12378896
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/_C/libtriton.so b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/_C/libtriton.so
new file mode 100644
index 0000000000000000000000000000000000000000..5832d200154dcb05cb097c6182924c2a108fac00
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/_C/libtriton.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:401cc8a47b481c4b74eb55ddba8ce03ba1cc92db0652af541e7c54ee1d17a995
+size 352634712
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..63ee791a2ee90a885d71295d558368fd0229c668
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/__init__.py
@@ -0,0 +1,76 @@
+"""isort:skip_file"""
+__version__ = '3.4.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 jit
+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__ = [
+ "autotune",
+ "cdiv",
+ "CompilationError",
+ "compile",
+ "Config",
+ "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
+# -------------------------------------
+
+
+def cdiv(x: int, y: int):
+ return (x + y - 1) // y
+
+
+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/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/_filecheck.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/_filecheck.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a857d8f14f80b171237469e6a2144e1d6be5f2a
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/_filecheck.py
@@ -0,0 +1,87 @@
+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._C.libtriton import ir
+
+# ===-----------------------------------------------------------------------===#
+# filecheck_test
+# ===-----------------------------------------------------------------------===#
+
+# Stub target for testing the frontend.
+stub_target = GPUTarget("cuda", 100, 32)
+stub_backend = make_backend(stub_target)
+
+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],
+ stderr=subprocess.STDOUT)
+ except subprocess.CalledProcessError as error:
+ decoded = error.output.decode('unicode_escape')
+ raise ValueError(decoded)
+
+
+def run_parser(kernel_fn):
+ sigkeys = [x.name for x in kernel_fn.params]
+ sigvals = [f"arg{i}" for i in range(len(sigkeys))]
+ signature = {k: v for (k, v) in zip(sigkeys, sigvals)}
+ source_cls = GluonASTSource if kernel_fn.is_gluon() else ASTSource
+ src = source_cls(fn=kernel_fn, signature=signature)
+
+ context = ir.context()
+ ir.load_dialects(context)
+ stub_backend.load_dialects(context)
+
+ extra_options = src.parse_options()
+ options = stub_backend.parse_options(dict(**extra_options))
+ codegen_fns = stub_backend.get_codegen_implementation(options)
+ module_map = stub_backend.get_module_map()
+ module = src.make_ir(options, codegen_fns, module_map, context)
+ assert module.verify()
+ 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):
+
+ def test_fn():
+ run_filecheck_test(fn)
+
+ return test_fn
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/_internal_testing.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/_internal_testing.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a2bc944166911233e5932f6d5a3f0efe403648b
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/_internal_testing.py
@@ -0,0 +1,189 @@
+import os
+import re
+import numpy as np
+import torch
+import triton
+import triton.language as tl
+from triton import knobs
+import pytest
+
+from numpy.random import RandomState
+from typing import Optional, Union
+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_hopper():
+ return is_cuda() and torch.cuda.get_device_capability()[0] >= 9
+
+
+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_gfx12():
+ target = get_current_target()
+ print(target.arch)
+ return target is not None and target.backend == 'hip' and 'gfx12' in target.arch
+
+
+def is_hip_cdna():
+ return is_hip_cdna2() or is_hip_cdna3() or is_hip_cdna4()
+
+
+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])
+
+
+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 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
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/_utils.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..1da8d692b97cf935a8523e786d8c9828cac1b7e4
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/_utils.py
@@ -0,0 +1,124 @@
+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):
+ assert len(path) != 0
+ prev = iterable if len(path) == 1 else get_iterable_path(iterable, path[:-1])
+ prev[path[-1]] = val # type: ignore[index]
+
+
+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]
+
+
+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]
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..69a8dab0a3616754b2531d619d8336153917c27d
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/__init__.py
@@ -0,0 +1,47 @@
+import importlib
+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()
+ 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/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/__init__.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/compiler.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/compiler.py
new file mode 100644
index 0000000000000000000000000000000000000000..bff54c2604bd6762563bb5dca2bef69cf1609126
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/compiler.py
@@ -0,0 +1,453 @@
+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 subprocess
+import functools
+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):
+ return (arch == "gfx942") 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 = 1
+ num_stages: int = 2
+ num_ctas: int = 1
+ extern_libs: dict = None
+ cluster_dims: tuple = (1, 1, 1)
+ debug: bool = False
+ sanitize_overflow: bool = True
+ arch: str = None
+ supported_fp8_dtypes: Tuple[str] = ("fp8e5", )
+ deprecated_fp8_dot_operand_dtypes: Tuple[str] = ()
+ default_dot_input_precision: str = "ieee"
+ allowed_dot_input_precisions: Tuple[str] = ("ieee", )
+ 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'
+
+ # 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:
+ #
+ # local-prefetch: implements instruction scheduling similar to the one from the ROCm Composable
+ # Kernel library. Note, this variant requires the use of buffer load/store ops
+ # and a special software pipelining style - i.e., 1x LDS and 1x register
+ # prefetch buffers for each GEMM tile.
+ # 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
+ 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':
+ assert self.kpack == 1, "gfx950 only accepts 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):
+
+ @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}
+
+ # 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:
+ supported_fp8_dtypes = set(HIPOptions.supported_fp8_dtypes)
+ if self.target.arch == 'gfx942':
+ supported_fp8_dtypes.update({'fp8e4nv', 'fp8e4b8', 'fp8e5b16'})
+ elif self.target.arch == 'gfx950':
+ supported_fp8_dtypes.update({'fp8e4nv', 'fp8e5'})
+ elif 'gfx12' in self.target.arch:
+ supported_fp8_dtypes.update({'fp8e4nv', 'fp8e5'})
+ args["supported_fp8_dtypes"] = tuple(sorted(supported_fp8_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,
+ metadata.cluster_dims[0],
+ metadata.cluster_dims[1],
+ metadata.cluster_dims[2],
+ )
+
+ 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)
+
+ @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_arg_specialization(arg, ty, **kwargs):
+ ret = BaseBackend.get_arg_specialization(arg, ty, **kwargs)
+ # Only attempt to do buffer ops specialization if buffer ops are enabled.
+ # Otherwise the is_within_2gb check is unnecessary overhead.
+ if knobs.amd.use_buffer_ops and ty == "tensor" and HIPBackend.is_within_2gb(arg):
+ ret += "S"
+ return ret
+
+ @staticmethod
+ def path_to_rocm_lld():
+ # Check env path for ld.lld
+ lld_env_path = knobs.amd.lld_path
+ if lld_env_path is not None:
+ lld = Path(lld_env_path)
+ if lld.is_file():
+ return lld
+ # Check backend for ld.lld (used for pytorch wheels)
+ lld = Path(__file__).parent / "llvm/bin/ld.lld"
+ if lld.is_file():
+ return lld
+ lld = Path("/opt/rocm/llvm/bin/ld.lld")
+ if lld.is_file():
+ return lld
+ lld = Path("/usr/bin/ld.lld")
+ if lld.is_file():
+ return lld
+ raise Exception("ROCm linker /opt/rocm/llvm/bin/ld.lld not found. Set 'TRITON_HIP_LLD_PATH' to its path.")
+
+ @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)
+ 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)
+ pm = ir.pass_manager(mod.context)
+ pm.enable_debug()
+ passes.ttgpuir.add_coalesce(pm)
+ 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)
+ passes.ttgpuir.add_optimize_dot_operands(pm, True)
+ 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)
+
+ global_prefetch = knobs.amd.global_prefetch
+ local_prefetch = knobs.amd.local_prefetch
+ use_async_copy = knobs.amd.use_async_copy
+
+ # The `local-prefetch` scheduling variant requires turning on buffer ops.
+ if options.schedule_hint == "local-prefetch":
+ global_prefetch = local_prefetch = 1
+
+ amd.passes.ttgpuir.add_stream_pipeline(pm, options.num_stages, global_prefetch, local_prefetch, use_async_copy)
+ 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":
+ amd.passes.ttgpuir.insert_instruction_sched_hints(pm, options.schedule_hint)
+ passes.ttgpuir.add_optimize_dot_operands(pm, True)
+ 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)
+ use_block_pingpong = is_pingpong_schedule_enabled(options.arch)
+ if use_block_pingpong and options.num_stages == 2:
+ 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)
+
+ amd.passes.ttgpuir.add_fold_true_cmpi(pm)
+ passes.common.add_canonicalizer(pm)
+ passes.common.add_cse(pm)
+ passes.common.add_symbol_dce(pm)
+ if use_async_copy:
+ amd.passes.ttgpuir.add_update_async_wait_count(pm, options.arch)
+ pm.run(mod)
+ return mod
+
+ @staticmethod
+ def ttgir_opt(src, metadata, options):
+ mod = src
+ pm = ir.pass_manager(mod.context)
+ pm.enable_debug()
+
+ passes.ttgpuir.add_inliner(pm)
+ passes.common.add_sccp(pm)
+ passes.ttir.add_loop_aware_cse(pm)
+ passes.ttgpuir.add_canonicalizer(pm)
+ passes.ttgpuir.add_combine_tensor_select_and_if(pm)
+
+ pm.run(mod)
+ return mod
+
+ @staticmethod
+ def make_llir(src, metadata, options):
+ mod = src
+ # TritonGPU -> LLVM-IR (MLIR)
+ pm = ir.pass_manager(mod.context)
+ pm.enable_debug()
+ # 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.convert.add_index_to_llvmir(pm)
+
+ passes.ttgpuir.add_allocate_shared_memory(pm)
+ ## __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)
+ if not knobs.compilation.disable_line_info:
+ passes.llvmir.add_di_scope(pm)
+ amd.passes.ttgpuir.add_builtin_func_to_llvmir(pm, __HIP_FTZ)
+ pm.run(mod)
+
+ # 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}")
+ # 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 greater than 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).
+ fns[0].add_fn_attr("amdgpu-waves-per-eu", f"{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)]
+ llvm.link_extern_libs(llvm_mod, paths)
+
+ llvm.optimize_module(llvm_mod, llvm.OPTIMIZE_O3, options.arch, '', [], options.enable_fp_fusion)
+
+ 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")
+
+ 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 = []
+ # The sink-insts-to-avoid-spills flag asks LLVM backend to sink instructions
+ # into loops to avoid register spills in the MachineSinking pass, while it
+ # can also lead to regression in some cases. But from current observation,
+ # the regression is not significant. It would be better to have some heuristics.
+ if options.schedule_hint == 'attention':
+ flags.append('sink-insts-to-avoid-spills')
+ amdgcn = llvm.translate_to_asm(src, amd.TARGET_TRIPLE, options.arch, '', 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)
+
+ rocm_path = HIPBackend.path_to_rocm_lld()
+ 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)
+ subprocess.check_call([rocm_path, '-flavor', 'gnu', '-shared', tmp_in.name, '-o', 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.ttgir_opt(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)
+
+ @functools.lru_cache()
+ def hash(self):
+ version = subprocess.check_output([HIPBackend.path_to_rocm_lld(), "--version"], encoding='utf-8')
+ return f'{version}-{self.target}'
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/driver.c b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/driver.c
new file mode 100644
index 0000000000000000000000000000000000000000..5d2355059d884d942257967fe36c3404c941eff1
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/driver.c
@@ -0,0 +1,214 @@
+#define __HIP_PLATFORM_AMD__
+// clang-format off
+// hip_depreated.h needs definitions from hip_runtime.h.
+#include
+#include
+// clang-format on
+#define PY_SSIZE_T_CLEAN
+#include
+#include
+#include
+#include
+
+// 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 *.
+//
+// HIP 6.0 introduced an updated hipGetDeviceProperties API under a new symbol,
+// hipGetDevicePropertiesR0600. However, the associated hipDeviceProp_t was
+// directly updated with breaking changes to match hipGetDevicePropertiesR0600
+// in the header file. We include the header file from HIP 6.0. So here if we
+// use hipGetDeviceProperties together with hipDeviceProp_t we will use the
+// old API with a new struct definition and mess up the interpretation.
+//
+// This is a known issue: https://github.com/ROCm/ROCm/issues/2728.
+//
+// For now explicitly defer to the old hipDeviceProp_t struct. This should work
+// for both 5.x and 6.x. In the long term we need to switch to use
+// hipGetProcAddress once available:
+// https://github.com/ROCm/clr/commit/0479cdb3dd30ef58718cad44e424bd793c394cc0
+#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_tR0000 *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)
+
+// 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;
+
+bool initSymbolTable() {
+ // Use the HIP runtime library loaded into the existing process if it exits.
+ void *lib = dlopen("libamdhip64.so", RTLD_NOLOAD);
+ if (lib) {
+ // printf("[triton] chosen loaded libamdhip64.so in the process\n");
+ }
+
+ // 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;
+ // printf("[triton] chosen %s\n", hipLibSearchPaths[i]);
+ }
+ }
+ }
+ if (!lib) {
+ PyErr_SetString(PyExc_RuntimeError, "cannot open libamdhip64.so");
+ return false;
+ }
+
+ // Resolve all symbols we are interested in.
+ dlerror(); // Clear existing errors
+ const char *error = NULL;
+#define QUERY_EACH_FN(hipSymbolName, ...) \
+ *(void **)&hipSymbolTable.hipSymbolName = dlsym(lib, #hipSymbolName); \
+ error = dlerror(); \
+ if (error) { \
+ PyErr_SetString(PyExc_RuntimeError, \
+ "cannot query " #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);
+ 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_tR0000 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 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"},
+ {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);
+
+ return m;
+}
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/driver.py b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/driver.py
new file mode 100644
index 0000000000000000000000000000000000000000..e29ac5f7ae4867bfc9f1985fc7b2789886b6db95
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/driver.py
@@ -0,0 +1,645 @@
+import functools
+import os
+import subprocess
+import re
+from pathlib import Path
+from triton import knobs
+from triton.backends.compiler import GPUTarget
+from triton.backends.driver import GPUDriver
+from triton.runtime.build import compile_module_from_src
+from triton.tools.tensor_descriptor import TensorDescriptor
+
+dirname = os.path.dirname(os.path.realpath(__file__))
+include_dirs = [os.path.join(dirname, "include")]
+
+
+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)
+
+ # Afterwards try to search the loader dynamic library resolution paths.
+ libs = subprocess.check_output(["/sbin/ldconfig", "-p"]).decode()
+ # 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
+
+
+# -------------------- Launcher ----------------------------
+def ty_to_cpp(ty):
+ if ty[0] == '*':
+ return "hipDeviceptr_t"
+ return {
+ "i1": "int32_t",
+ "i8": "int8_t",
+ "i16": "int16_t",
+ "i32": "int32_t",
+ "i64": "int64_t",
+ "u1": "uint32_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 = "piiiKKOOOO"
+
+
+def make_launcher(constants, signature, warp_size):
+
+ def _expand_signature(signature):
+ output = []
+ # Expand tensor descriptor arguments into base pointer, shape, and
+ # strides
+ for sig in signature:
+ if isinstance(sig, str) and sig.startswith("tensordesc"):
+ ndim = sig.count(",") + 1
+ dtype = re.match("tensordesc<([^[>]*)", sig).group()
+
+ output.append("*" + dtype)
+ for _ in range(2 * ndim):
+ output.append("i64")
+ # Currently the host side tensor descriptors get passed in as a
+ # 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.
+ 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[0] == '*':
+ 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[0] == '*':
+ 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[0] == "*":
+ internal_args_list.append(f"ptr_info{i}.dev_ptr")
+ elif ty in FLOAT_STORAGE_TYPE:
+ internal_args_list.append(f"_arg{i}_storage")
+ elif ty != "constexpr":
+ internal_args_list.append(f"_arg{i}")
+
+ 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")
+ src = f"""
+#define __HIP_PLATFORM_AMD__
+#include
+#include
+#include
+#include
+#include
+
+// 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(hipGetErrorString, hipError_t hipError) \\
+ FOR_EACH_ERR_FN(hipModuleLaunchKernel, 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, 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, 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, ...) \\
+ 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;
+
+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;
+ }}
+
+ // Resolve all symbols we are interested in.
+ dlerror(); // Clear existing errors
+ const char *error = NULL;
+#define QUERY_EACH_FN(hipSymbolName, ...) \\
+ *(void **)&hipSymbolTable.hipSymbolName = dlsym(lib, #hipSymbolName); \\
+ error = dlerror(); \\
+ if (error) {{ \\
+ PyErr_SetString(PyExc_RuntimeError, \\
+ "cannot query " #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 clusterDimX, int clusterDimY, int clusterDimZ, int shared_memory, hipStream_t stream, hipFunction_t function{', ' + arg_decls if len(arg_decls) > 0 else ''}) {{
+ hipDeviceptr_t global_scratch = 0;
+ void *params[] = {{ {', '.join(params)} }};
+ if (gridX*gridY*gridZ > 0 && launch_cooperative_grid) {{
+ HIP_CHECK(hipSymbolTable.hipModuleLaunchCooperativeKernel(function, gridX, gridY, gridZ, {warp_size}*num_warps, 1, 1, shared_memory, stream, params, 0));
+ return;
+ }}
+ if (gridX*gridY*gridZ > 0) {{
+ 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 inline DevicePtrInfo getPointer(PyObject *obj, int idx) {{
+ DevicePtrInfo ptr_info;
+ 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 *ptr = PyObject_GetAttrString(obj, "data_ptr");
+ if(ptr){{
+ PyObject *empty_tuple = PyTuple_New(0);
+ PyObject *ret = PyObject_Call(ptr, empty_tuple, NULL);
+ Py_DECREF(empty_tuple);
+ Py_DECREF(ptr);
+ if (!PyLong_Check(ret)) {{
+ PyErr_SetString(PyExc_TypeError, "data_ptr method of Pointer object must return 64-bit int");
+ ptr_info.valid = false;
+ return ptr_info;
+ }}
+ ptr_info.dev_ptr = (hipDeviceptr_t)PyLong_AsUnsignedLongLong(ret);
+ if(!ptr_info.dev_ptr)
+ return ptr_info;
+ uint64_t dev_ptr;
+ hipError_t 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;
+ }}
+ ptr_info.dev_ptr = (hipDeviceptr_t)dev_ptr;
+ Py_DECREF(ret);
+ return ptr_info;
+ }}
+ PyErr_SetString(PyExc_TypeError, "Pointer argument must be either uint64 or have data_ptr method");
+ return ptr_info;
+}}
+
+static uint16_t pack_fp16(double f) {{
+ uint16_t result;
+ // from https://github.com/python/pythoncapi-compat
+#if 0x030600B1 <= PY_VERSION_HEX && PY_VERSION_HEX <= 0x030B00A1 && !defined(PYPY_VERSION)
+ _PyFloat_Pack2(f, (unsigned char*)&result, 1);
+#else
+ PyFloat_Pack2(f, (unsigned 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 *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,
+ &kernel_metadata, &launch_metadata,
+ &launch_enter_hook, &launch_exit_hook {args_list})) {{
+ return NULL;
+ }}
+
+ {' '.join(float_storage_decls)}
+
+ // extract kernel metadata
+ int num_warps, num_ctas, shared_memory, clusterDimX, clusterDimY, clusterDimZ;
+ if (!PyArg_ParseTuple(kernel_metadata, \"iiiiii\", &num_warps, &num_ctas, &shared_memory, &clusterDimX, &clusterDimY, &clusterDimZ)) {{
+ return NULL;
+ }}
+ // extract launch metadata
+ if (launch_enter_hook != Py_None){{
+ PyObject* args = Py_BuildValue("(O)", launch_metadata);
+ PyObject* ret = PyObject_CallObject(launch_enter_hook, args);
+ Py_DECREF(args);
+ if (!ret)
+ return NULL;
+ Py_DECREF(ret);
+ }}
+
+
+ // raise exception asap
+ {"; ".join([f"DevicePtrInfo ptr_info{i} = getPointer(_arg{i}, {i}); if (!ptr_info{i}.valid) return NULL;" if ty[0] == "*" else "" for i, ty in signature.items()])};
+ _launch(gridX, gridY, gridZ, num_warps, num_ctas, launch_cooperative_grid, clusterDimX, clusterDimY, clusterDimZ, shared_memory, (hipStream_t)_stream, (hipFunction_t)_function{', ' + ', '.join(internal_args_list) if len(internal_args_list) > 0 else ''});
+
+ if(launch_exit_hook != Py_None){{
+ PyObject* args = Py_BuildValue("(O)", launch_metadata);
+ PyObject* ret = PyObject_CallObject(launch_exit_hook, args);
+ Py_DECREF(args);
+ if (!ret)
+ return NULL;
+ Py_DECREF(ret);
+ }}
+
+ if(PyErr_Occurred()) {{
+ return NULL;
+ }}
+ // return None
+ Py_INCREF(Py_None);
+ return Py_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;
+ }}
+ PyModule_AddFunctions(m, ModuleMethods);
+ return m;
+}}
+"""
+ return src
+
+
+def wrap_handle_tensor_descriptor(launcher):
+ """
+ Replace all tensor descriptors with the base ptr, shape, and strides
+ """
+
+ def inner(*args):
+ meta_args = args[:len(_BASE_ARGS_FORMAT)]
+ raw_kernel_args = args[len(_BASE_ARGS_FORMAT):]
+ final_args = []
+ for arg in raw_kernel_args:
+ if isinstance(arg, TensorDescriptor):
+ # 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.
+ final_args.extend([arg.base, *arg.shape, *arg.strides, *arg.shape, *arg.strides])
+ 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()}
+ src = make_launcher(constants, signature, metadata.warp_size)
+ mod = compile_module_from_src(src=src, name="__triton_launcher", include_dirs=include_dirs)
+ has_tensor_desc_arg = any(isinstance(sig, str) and sig.startswith("tensordesc") for sig in signature.values())
+
+ self.launch = wrap_handle_tensor_descriptor(mod.launch) if has_tensor_desc_arg else mod.launch
+ self.launch_cooperative_grid = metadata.launch_cooperative_grid
+
+ def __call__(self, *args):
+ self.launch(self.launch_cooperative_grid, *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 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/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_channel_descriptor.h b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_channel_descriptor.h
new file mode 100644
index 0000000000000000000000000000000000000000..c6b150d4b32237468a947b9c0e31843560751357
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_channel_descriptor.h
@@ -0,0 +1,358 @@
+/*
+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() {
+ int e = (int)sizeof(unsigned char) * 8;
+ return hipCreateChannelDesc(e, e, 0, 0, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed char) * 8;
+ return hipCreateChannelDesc(e, e, 0, 0, hipChannelFormatKindSigned);
+}
+
+#ifndef __GNUC__ // vector3 is the same as vector4
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned char) * 8;
+ return hipCreateChannelDesc(e, e, e, 0, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed char) * 8;
+ return hipCreateChannelDesc(e, e, e, 0, hipChannelFormatKindSigned);
+}
+#endif
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned char) * 8;
+ return hipCreateChannelDesc(e, e, e, e, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed char) * 8;
+ return hipCreateChannelDesc(e, e, e, e, hipChannelFormatKindSigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned short) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed short) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindSigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned short) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed short) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindSigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned short) * 8;
+ return hipCreateChannelDesc(e, e, 0, 0, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed short) * 8;
+ return hipCreateChannelDesc(e, e, 0, 0, hipChannelFormatKindSigned);
+}
+
+#ifndef __GNUC__
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned short) * 8;
+ return hipCreateChannelDesc(e, e, e, 0, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed short) * 8;
+ return hipCreateChannelDesc(e, e, e, 0, hipChannelFormatKindSigned);
+}
+#endif
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned short) * 8;
+ return hipCreateChannelDesc(e, e, e, e, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed short) * 8;
+ return hipCreateChannelDesc(e, e, e, e, hipChannelFormatKindSigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned int) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed int) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindSigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned int) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed int) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindSigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned int) * 8;
+ return hipCreateChannelDesc(e, e, 0, 0, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed int) * 8;
+ return hipCreateChannelDesc(e, e, 0, 0, hipChannelFormatKindSigned);
+}
+
+#ifndef __GNUC__
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned int) * 8;
+ return hipCreateChannelDesc(e, e, e, 0, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed int) * 8;
+ return hipCreateChannelDesc(e, e, e, 0, hipChannelFormatKindSigned);
+}
+#endif
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned int) * 8;
+ return hipCreateChannelDesc(e, e, e, e, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed int) * 8;
+ return hipCreateChannelDesc(e, e, e, e, hipChannelFormatKindSigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(float) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindFloat);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(float) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindFloat);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(float) * 8;
+ return hipCreateChannelDesc(e, e, 0, 0, hipChannelFormatKindFloat);
+}
+
+#ifndef __GNUC__
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(float) * 8;
+ return hipCreateChannelDesc(e, e, e, 0, hipChannelFormatKindFloat);
+}
+#endif
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(float) * 8;
+ return hipCreateChannelDesc(e, e, e, e, hipChannelFormatKindFloat);
+}
+
+#if !defined(__LP64__)
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned long) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed long) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindSigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned long) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed long) * 8;
+ return hipCreateChannelDesc(e, 0, 0, 0, hipChannelFormatKindSigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned long) * 8;
+ return hipCreateChannelDesc(e, e, 0, 0, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed long) * 8;
+ return hipCreateChannelDesc(e, e, 0, 0, hipChannelFormatKindSigned);
+}
+
+#ifndef __GNUC__
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned long) * 8;
+ return hipCreateChannelDesc(e, e, e, 0, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed long) * 8;
+ return hipCreateChannelDesc(e, e, e, 0, hipChannelFormatKindSigned);
+}
+#endif
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(unsigned long) * 8;
+ return hipCreateChannelDesc(e, e, e, e, hipChannelFormatKindUnsigned);
+}
+
+template <>
+inline hipChannelFormatDesc hipCreateChannelDesc() {
+ int e = (int)sizeof(signed long) * 8;
+ return hipCreateChannelDesc(e, e, e, e, hipChannelFormatKindSigned);
+}
+#endif /* !__LP64__ */
+
+#else
+
+struct hipChannelFormatDesc hipCreateChannelDesc(int x, int y, int z, int w,
+ enum hipChannelFormatKind f);
+
+#endif /* __cplusplus */
+
+#endif /* !HIP_INCLUDE_HIP_AMD_DETAIL_CHANNEL_DESCRIPTOR_H */
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_device_functions.h b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_device_functions.h
new file mode 100644
index 0000000000000000000000000000000000000000..c4837ad64c4d87d02f22406a9953ecc43011e476
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_device_functions.h
@@ -0,0 +1,1010 @@
+/*
+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_DEVICE_FUNCTIONS_H
+#define HIP_INCLUDE_HIP_AMD_DETAIL_DEVICE_FUNCTIONS_H
+
+#if !defined(__HIPCC_RTC__)
+#include
+#include
+#include
+#include "host_defines.h"
+#include "math_fwd.h"
+#include
+#include
+#include
+#endif // !defined(__HIPCC_RTC__)
+
+#if defined(__clang__) && defined(__HIP__)
+extern "C" __device__ int printf(const char *fmt, ...);
+#else
+template
+static inline __device__ void printf(const char* format, All... all) {}
+#endif
+
+extern "C" __device__ unsigned long long __ockl_steadyctr_u64();
+
+/*
+Integer Intrinsics
+*/
+
+// integer intrinsic function __poc __clz __ffs __brev
+__device__ static inline unsigned int __popc(unsigned int input) {
+ return __builtin_popcount(input);
+}
+__device__ static inline unsigned int __popcll(unsigned long long int input) {
+ return __builtin_popcountll(input);
+}
+
+__device__ static inline int __clz(int input) {
+ return __ockl_clz_u32((uint)input);
+}
+
+__device__ static inline int __clzll(long long int input) {
+ return __ockl_clz_u64((uint64_t)input);
+}
+
+__device__ static inline unsigned int __ffs(unsigned int input) {
+ return ( input == 0 ? -1 : __builtin_ctz(input) ) + 1;
+}
+
+__device__ static inline unsigned int __ffsll(unsigned long long int input) {
+ return ( input == 0 ? -1 : __builtin_ctzll(input) ) + 1;
+}
+
+__device__ static inline unsigned int __ffs(int input) {
+ return ( input == 0 ? -1 : __builtin_ctz(input) ) + 1;
+}
+
+__device__ static inline unsigned int __ffsll(long long int input) {
+ return ( input == 0 ? -1 : __builtin_ctzll(input) ) + 1;
+}
+
+// Given a 32/64-bit value exec mask and an integer value base (between 0 and WAVEFRONT_SIZE),
+// find the n-th (given by offset) set bit in the exec mask from the base bit, and return the bit position.
+// If not found, return -1.
+__device__ static int32_t __fns64(uint64_t mask, uint32_t base, int32_t offset) {
+ uint64_t temp_mask = mask;
+ int32_t temp_offset = offset;
+
+ if (offset == 0) {
+ temp_mask &= (1 << base);
+ temp_offset = 1;
+ }
+ else if (offset < 0) {
+ temp_mask = __builtin_bitreverse64(mask);
+ base = 63 - base;
+ temp_offset = -offset;
+ }
+
+ temp_mask = temp_mask & ((~0ULL) << base);
+ if (__builtin_popcountll(temp_mask) < temp_offset)
+ return -1;
+ int32_t total = 0;
+ for (int i = 0x20; i > 0; i >>= 1) {
+ uint64_t temp_mask_lo = temp_mask & ((1ULL << i) - 1);
+ int32_t pcnt = __builtin_popcountll(temp_mask_lo);
+ if (pcnt < temp_offset) {
+ temp_mask = temp_mask >> i;
+ temp_offset -= pcnt;
+ total += i;
+ }
+ else {
+ temp_mask = temp_mask_lo;
+ }
+ }
+ if (offset < 0)
+ return 63 - total;
+ else
+ return total;
+}
+
+__device__ static int32_t __fns32(uint64_t mask, uint32_t base, int32_t offset) {
+ uint64_t temp_mask = mask;
+ int32_t temp_offset = offset;
+ if (offset == 0) {
+ temp_mask &= (1 << base);
+ temp_offset = 1;
+ }
+ else if (offset < 0) {
+ temp_mask = __builtin_bitreverse64(mask);
+ base = 63 - base;
+ temp_offset = -offset;
+ }
+ temp_mask = temp_mask & ((~0ULL) << base);
+ if (__builtin_popcountll(temp_mask) < temp_offset)
+ return -1;
+ int32_t total = 0;
+ for (int i = 0x20; i > 0; i >>= 1) {
+ uint64_t temp_mask_lo = temp_mask & ((1ULL << i) - 1);
+ int32_t pcnt = __builtin_popcountll(temp_mask_lo);
+ if (pcnt < temp_offset) {
+ temp_mask = temp_mask >> i;
+ temp_offset -= pcnt;
+ total += i;
+ }
+ else {
+ temp_mask = temp_mask_lo;
+ }
+ }
+ if (offset < 0)
+ return 63 - total;
+ else
+ return total;
+}
+__device__ static inline unsigned int __brev(unsigned int input) {
+ return __builtin_bitreverse32(input);
+}
+
+__device__ static inline unsigned long long int __brevll(unsigned long long int input) {
+ return __builtin_bitreverse64(input);
+}
+
+__device__ static inline unsigned int __lastbit_u32_u64(uint64_t input) {
+ return input == 0 ? -1 : __builtin_ctzl(input);
+}
+
+__device__ static inline unsigned int __bitextract_u32(unsigned int src0, unsigned int src1, unsigned int src2) {
+ uint32_t offset = src1 & 31;
+ uint32_t width = src2 & 31;
+ return width == 0 ? 0 : (src0 << (32 - offset - width)) >> (32 - width);
+}
+
+__device__ static inline uint64_t __bitextract_u64(uint64_t src0, unsigned int src1, unsigned int src2) {
+ uint64_t offset = src1 & 63;
+ uint64_t width = src2 & 63;
+ return width == 0 ? 0 : (src0 << (64 - offset - width)) >> (64 - width);
+}
+
+__device__ static inline unsigned int __bitinsert_u32(unsigned int src0, unsigned int src1, unsigned int src2, unsigned int src3) {
+ uint32_t offset = src2 & 31;
+ uint32_t width = src3 & 31;
+ uint32_t mask = (1 << width) - 1;
+ return ((src0 & ~(mask << offset)) | ((src1 & mask) << offset));
+}
+
+__device__ static inline uint64_t __bitinsert_u64(uint64_t src0, uint64_t src1, unsigned int src2, unsigned int src3) {
+ uint64_t offset = src2 & 63;
+ uint64_t width = src3 & 63;
+ uint64_t mask = (1ULL << width) - 1;
+ return ((src0 & ~(mask << offset)) | ((src1 & mask) << offset));
+}
+
+__device__ inline unsigned int __funnelshift_l(unsigned int lo, unsigned int hi, unsigned int shift)
+{
+ uint32_t mask_shift = shift & 31;
+ return mask_shift == 0 ? hi : __builtin_amdgcn_alignbit(hi, lo, 32 - mask_shift);
+}
+
+__device__ inline unsigned int __funnelshift_lc(unsigned int lo, unsigned int hi, unsigned int shift)
+{
+ uint32_t min_shift = shift >= 32 ? 32 : shift;
+ return min_shift == 0 ? hi : __builtin_amdgcn_alignbit(hi, lo, 32 - min_shift);
+}
+
+__device__ inline unsigned int __funnelshift_r(unsigned int lo, unsigned int hi, unsigned int shift)
+{
+ return __builtin_amdgcn_alignbit(hi, lo, shift);
+}
+
+__device__ inline unsigned int __funnelshift_rc(unsigned int lo, unsigned int hi, unsigned int shift)
+{
+ return shift >= 32 ? hi : __builtin_amdgcn_alignbit(hi, lo, shift);
+}
+
+__device__ static unsigned int __byte_perm(unsigned int x, unsigned int y, unsigned int s);
+__device__ static unsigned int __hadd(int x, int y);
+__device__ static int __mul24(int x, int y);
+__device__ static long long int __mul64hi(long long int x, long long int y);
+__device__ static int __mulhi(int x, int y);
+__device__ static int __rhadd(int x, int y);
+__device__ static unsigned int __sad(int x, int y,unsigned int z);
+__device__ static unsigned int __uhadd(unsigned int x, unsigned int y);
+__device__ static int __umul24(unsigned int x, unsigned int y);
+__device__ static unsigned long long int __umul64hi(unsigned long long int x, unsigned long long int y);
+__device__ static unsigned int __umulhi(unsigned int x, unsigned int y);
+__device__ static unsigned int __urhadd(unsigned int x, unsigned int y);
+__device__ static unsigned int __usad(unsigned int x, unsigned int y, unsigned int z);
+
+struct ucharHolder {
+ union {
+ unsigned char c[4];
+ unsigned int ui;
+ };
+} __attribute__((aligned(4)));
+
+struct uchar2Holder {
+ union {
+ unsigned int ui[2];
+ unsigned char c[8];
+ };
+} __attribute__((aligned(8)));
+
+__device__
+static inline unsigned int __byte_perm(unsigned int x, unsigned int y, unsigned int s) {
+ struct uchar2Holder cHoldVal;
+ struct ucharHolder cHoldKey;
+ cHoldKey.ui = s;
+ cHoldVal.ui[0] = x;
+ cHoldVal.ui[1] = y;
+ unsigned int result;
+ result = cHoldVal.c[cHoldKey.c[0] & 0x07];
+ result += (cHoldVal.c[(cHoldKey.c[0] & 0x70) >> 4] << 8);
+ result += (cHoldVal.c[cHoldKey.c[1] & 0x07] << 16);
+ result += (cHoldVal.c[(cHoldKey.c[1] & 0x70) >> 4] << 24);
+ return result;
+}
+
+__device__ static inline unsigned int __hadd(int x, int y) {
+ int z = x + y;
+ int sign = z & 0x8000000;
+ int value = z & 0x7FFFFFFF;
+ return ((value) >> 1 || sign);
+}
+
+__device__ static inline int __mul24(int x, int y) {
+ return __ockl_mul24_i32(x, y);
+}
+
+__device__ static inline long long __mul64hi(long long int x, long long int y) {
+ unsigned long long x0 = (unsigned long long)x & 0xffffffffUL;
+ long long x1 = x >> 32;
+ unsigned long long y0 = (unsigned long long)y & 0xffffffffUL;
+ long long y1 = y >> 32;
+ unsigned long long z0 = x0*y0;
+ long long t = x1*y0 + (z0 >> 32);
+ long long z1 = t & 0xffffffffL;
+ long long z2 = t >> 32;
+ z1 = x0*y1 + z1;
+ return x1*y1 + z2 + (z1 >> 32);
+}
+
+__device__ static inline int __mulhi(int x, int y) {
+ return __ockl_mul_hi_i32(x, y);
+}
+
+__device__ static inline int __rhadd(int x, int y) {
+ int z = x + y + 1;
+ int sign = z & 0x8000000;
+ int value = z & 0x7FFFFFFF;
+ return ((value) >> 1 || sign);
+}
+__device__ static inline unsigned int __sad(int x, int y, unsigned int z) {
+ return x > y ? x - y + z : y - x + z;
+}
+__device__ static inline unsigned int __uhadd(unsigned int x, unsigned int y) {
+ return (x + y) >> 1;
+}
+__device__ static inline int __umul24(unsigned int x, unsigned int y) {
+ return __ockl_mul24_u32(x, y);
+}
+
+__device__
+static inline unsigned long long __umul64hi(unsigned long long int x, unsigned long long int y) {
+ unsigned long long x0 = x & 0xffffffffUL;
+ unsigned long long x1 = x >> 32;
+ unsigned long long y0 = y & 0xffffffffUL;
+ unsigned long long y1 = y >> 32;
+ unsigned long long z0 = x0*y0;
+ unsigned long long t = x1*y0 + (z0 >> 32);
+ unsigned long long z1 = t & 0xffffffffUL;
+ unsigned long long z2 = t >> 32;
+ z1 = x0*y1 + z1;
+ return x1*y1 + z2 + (z1 >> 32);
+}
+
+__device__ static inline unsigned int __umulhi(unsigned int x, unsigned int y) {
+ return __ockl_mul_hi_u32(x, y);
+}
+__device__ static inline unsigned int __urhadd(unsigned int x, unsigned int y) {
+ return (x + y + 1) >> 1;
+}
+__device__ static inline unsigned int __usad(unsigned int x, unsigned int y, unsigned int z) {
+ return __ockl_sadd_u32(x, y, z);
+}
+
+__device__
+static inline unsigned int __mbcnt_lo(unsigned int x, unsigned int y) {return __builtin_amdgcn_mbcnt_lo(x,y);};
+
+__device__
+static inline unsigned int __mbcnt_hi(unsigned int x, unsigned int y) {return __builtin_amdgcn_mbcnt_hi(x,y);};
+
+/*
+HIP specific device functions
+*/
+
+#if !defined(__HIPCC_RTC__)
+#include "amd_warp_functions.h"
+#include "amd_warp_sync_functions.h"
+#endif
+
+#define MASK1 0x00ff00ff
+#define MASK2 0xff00ff00
+
+__device__ static inline char4 __hip_hc_add8pk(char4 in1, char4 in2) {
+ char4 out;
+ unsigned one1 = in1.w & MASK1;
+ unsigned one2 = in2.w & MASK1;
+ out.w = (one1 + one2) & MASK1;
+ one1 = in1.w & MASK2;
+ one2 = in2.w & MASK2;
+ out.w = out.w | ((one1 + one2) & MASK2);
+ return out;
+}
+
+__device__ static inline char4 __hip_hc_sub8pk(char4 in1, char4 in2) {
+ char4 out;
+ unsigned one1 = in1.w & MASK1;
+ unsigned one2 = in2.w & MASK1;
+ out.w = (one1 - one2) & MASK1;
+ one1 = in1.w & MASK2;
+ one2 = in2.w & MASK2;
+ out.w = out.w | ((one1 - one2) & MASK2);
+ return out;
+}
+
+__device__ static inline char4 __hip_hc_mul8pk(char4 in1, char4 in2) {
+ char4 out;
+ unsigned one1 = in1.w & MASK1;
+ unsigned one2 = in2.w & MASK1;
+ out.w = (one1 * one2) & MASK1;
+ one1 = in1.w & MASK2;
+ one2 = in2.w & MASK2;
+ out.w = out.w | ((one1 * one2) & MASK2);
+ return out;
+}
+
+__device__ static inline float __double2float_rd(double x) {
+ return __ocml_cvtrtn_f32_f64(x);
+}
+__device__ static inline float __double2float_rn(double x) { return x; }
+__device__ static inline float __double2float_ru(double x) {
+ return __ocml_cvtrtp_f32_f64(x);
+}
+__device__ static inline float __double2float_rz(double x) {
+ return __ocml_cvtrtz_f32_f64(x);
+}
+
+__device__ static inline int __double2hiint(double x) {
+ static_assert(sizeof(double) == 2 * sizeof(int), "");
+
+ int tmp[2];
+ __builtin_memcpy(tmp, &x, sizeof(tmp));
+
+ return tmp[1];
+}
+__device__ static inline int __double2loint(double x) {
+ static_assert(sizeof(double) == 2 * sizeof(int), "");
+
+ int tmp[2];
+ __builtin_memcpy(tmp, &x, sizeof(tmp));
+
+ return tmp[0];
+}
+
+__device__ static inline int __double2int_rd(double x) { return (int)__ocml_floor_f64(x); }
+__device__ static inline int __double2int_rn(double x) { return (int)__ocml_rint_f64(x); }
+__device__ static inline int __double2int_ru(double x) { return (int)__ocml_ceil_f64(x); }
+__device__ static inline int __double2int_rz(double x) { return (int)x; }
+
+__device__ static inline long long int __double2ll_rd(double x) {
+ return (long long)__ocml_floor_f64(x);
+}
+__device__ static inline long long int __double2ll_rn(double x) {
+ return (long long)__ocml_rint_f64(x);
+}
+__device__ static inline long long int __double2ll_ru(double x) {
+ return (long long)__ocml_ceil_f64(x);
+}
+__device__ static inline long long int __double2ll_rz(double x) { return (long long)x; }
+
+__device__ static inline unsigned int __double2uint_rd(double x) {
+ return (unsigned int)__ocml_floor_f64(x);
+}
+__device__ static inline unsigned int __double2uint_rn(double x) {
+ return (unsigned int)__ocml_rint_f64(x);
+}
+__device__ static inline unsigned int __double2uint_ru(double x) {
+ return (unsigned int)__ocml_ceil_f64(x);
+}
+__device__ static inline unsigned int __double2uint_rz(double x) { return (unsigned int)x; }
+
+__device__ static inline unsigned long long int __double2ull_rd(double x) {
+ return (unsigned long long int)__ocml_floor_f64(x);
+}
+__device__ static inline unsigned long long int __double2ull_rn(double x) {
+ return (unsigned long long int)__ocml_rint_f64(x);
+}
+__device__ static inline unsigned long long int __double2ull_ru(double x) {
+ return (unsigned long long int)__ocml_ceil_f64(x);
+}
+__device__ static inline unsigned long long int __double2ull_rz(double x) {
+ return (unsigned long long int)x;
+}
+__device__ static inline long long int __double_as_longlong(double x) {
+ static_assert(sizeof(long long) == sizeof(double), "");
+
+ long long tmp;
+ __builtin_memcpy(&tmp, &x, sizeof(tmp));
+
+ return tmp;
+}
+
+/*
+__device__ unsigned short __float2half_rn(float x);
+__device__ float __half2float(unsigned short);
+
+The above device function are not a valid .
+Use
+__device__ __half __float2half_rn(float x);
+__device__ float __half2float(__half);
+from hip_fp16.h
+
+CUDA implements half as unsigned short whereas, HIP doesn't.
+
+*/
+
+__device__ static inline int __float2int_rd(float x) { return (int)__ocml_floor_f32(x); }
+__device__ static inline int __float2int_rn(float x) { return (int)__ocml_rint_f32(x); }
+__device__ static inline int __float2int_ru(float x) { return (int)__ocml_ceil_f32(x); }
+__device__ static inline int __float2int_rz(float x) { return (int)__ocml_trunc_f32(x); }
+
+__device__ static inline long long int __float2ll_rd(float x) {
+ return (long long int)__ocml_floor_f32(x);
+}
+__device__ static inline long long int __float2ll_rn(float x) {
+ return (long long int)__ocml_rint_f32(x);
+}
+__device__ static inline long long int __float2ll_ru(float x) {
+ return (long long int)__ocml_ceil_f32(x);
+}
+__device__ static inline long long int __float2ll_rz(float x) { return (long long int)x; }
+
+__device__ static inline unsigned int __float2uint_rd(float x) {
+ return (unsigned int)__ocml_floor_f32(x);
+}
+__device__ static inline unsigned int __float2uint_rn(float x) {
+ return (unsigned int)__ocml_rint_f32(x);
+}
+__device__ static inline unsigned int __float2uint_ru(float x) {
+ return (unsigned int)__ocml_ceil_f32(x);
+}
+__device__ static inline unsigned int __float2uint_rz(float x) { return (unsigned int)x; }
+
+__device__ static inline unsigned long long int __float2ull_rd(float x) {
+ return (unsigned long long int)__ocml_floor_f32(x);
+}
+__device__ static inline unsigned long long int __float2ull_rn(float x) {
+ return (unsigned long long int)__ocml_rint_f32(x);
+}
+__device__ static inline unsigned long long int __float2ull_ru(float x) {
+ return (unsigned long long int)__ocml_ceil_f32(x);
+}
+__device__ static inline unsigned long long int __float2ull_rz(float x) {
+ return (unsigned long long int)x;
+}
+
+__device__ static inline int __float_as_int(float x) {
+ static_assert(sizeof(int) == sizeof(float), "");
+
+ int tmp;
+ __builtin_memcpy(&tmp, &x, sizeof(tmp));
+
+ return tmp;
+}
+
+__device__ static inline unsigned int __float_as_uint(float x) {
+ static_assert(sizeof(unsigned int) == sizeof(float), "");
+
+ unsigned int tmp;
+ __builtin_memcpy(&tmp, &x, sizeof(tmp));
+
+ return tmp;
+}
+
+__device__ static inline double __hiloint2double(int hi, int lo) {
+ static_assert(sizeof(double) == sizeof(uint64_t), "");
+
+ uint64_t tmp0 = (static_cast(hi) << 32ull) | static_cast(lo);
+ double tmp1;
+ __builtin_memcpy(&tmp1, &tmp0, sizeof(tmp0));
+
+ return tmp1;
+}
+
+__device__ static inline double __int2double_rn(int x) { return (double)x; }
+
+__device__ static inline float __int2float_rd(int x) {
+ return __ocml_cvtrtn_f32_s32(x);
+}
+__device__ static inline float __int2float_rn(int x) { return (float)x; }
+__device__ static inline float __int2float_ru(int x) {
+ return __ocml_cvtrtp_f32_s32(x);
+}
+__device__ static inline float __int2float_rz(int x) {
+ return __ocml_cvtrtz_f32_s32(x);
+}
+
+__device__ static inline float __int_as_float(int x) {
+ static_assert(sizeof(float) == sizeof(int), "");
+
+ float tmp;
+ __builtin_memcpy(&tmp, &x, sizeof(tmp));
+
+ return tmp;
+}
+
+__device__ static inline double __ll2double_rd(long long int x) {
+ return __ocml_cvtrtn_f64_s64(x);
+}
+__device__ static inline double __ll2double_rn(long long int x) { return (double)x; }
+__device__ static inline double __ll2double_ru(long long int x) {
+ return __ocml_cvtrtp_f64_s64(x);
+}
+__device__ static inline double __ll2double_rz(long long int x) {
+ return __ocml_cvtrtz_f64_s64(x);
+}
+
+__device__ static inline float __ll2float_rd(long long int x) {
+ return __ocml_cvtrtn_f32_s64(x);
+}
+__device__ static inline float __ll2float_rn(long long int x) { return (float)x; }
+__device__ static inline float __ll2float_ru(long long int x) {
+ return __ocml_cvtrtp_f32_s64(x);
+}
+__device__ static inline float __ll2float_rz(long long int x) {
+ return __ocml_cvtrtz_f32_s64(x);
+}
+
+__device__ static inline double __longlong_as_double(long long int x) {
+ static_assert(sizeof(double) == sizeof(long long), "");
+
+ double tmp;
+ __builtin_memcpy(&tmp, &x, sizeof(tmp));
+
+ return tmp;
+}
+
+__device__ static inline double __uint2double_rn(unsigned int x) { return (double)x; }
+
+__device__ static inline float __uint2float_rd(unsigned int x) {
+ return __ocml_cvtrtn_f32_u32(x);
+}
+__device__ static inline float __uint2float_rn(unsigned int x) { return (float)x; }
+__device__ static inline float __uint2float_ru(unsigned int x) {
+ return __ocml_cvtrtp_f32_u32(x);
+}
+__device__ static inline float __uint2float_rz(unsigned int x) {
+ return __ocml_cvtrtz_f32_u32(x);
+}
+
+__device__ static inline float __uint_as_float(unsigned int x) {
+ static_assert(sizeof(float) == sizeof(unsigned int), "");
+
+ float tmp;
+ __builtin_memcpy(&tmp, &x, sizeof(tmp));
+
+ return tmp;
+}
+
+__device__ static inline double __ull2double_rd(unsigned long long int x) {
+ return __ocml_cvtrtn_f64_u64(x);
+}
+__device__ static inline double __ull2double_rn(unsigned long long int x) { return (double)x; }
+__device__ static inline double __ull2double_ru(unsigned long long int x) {
+ return __ocml_cvtrtp_f64_u64(x);
+}
+__device__ static inline double __ull2double_rz(unsigned long long int x) {
+ return __ocml_cvtrtz_f64_u64(x);
+}
+
+__device__ static inline float __ull2float_rd(unsigned long long int x) {
+ return __ocml_cvtrtn_f32_u64(x);
+}
+__device__ static inline float __ull2float_rn(unsigned long long int x) { return (float)x; }
+__device__ static inline float __ull2float_ru(unsigned long long int x) {
+ return __ocml_cvtrtp_f32_u64(x);
+}
+__device__ static inline float __ull2float_rz(unsigned long long int x) {
+ return __ocml_cvtrtz_f32_u64(x);
+}
+
+#if defined(__clang__) && defined(__HIP__)
+
+// Clock functions
+__device__ long long int __clock64();
+__device__ long long int __clock();
+__device__ long long int clock64();
+__device__ long long int clock();
+__device__ long long int wall_clock64();
+// hip.amdgcn.bc - named sync
+__device__ void __named_sync();
+
+#ifdef __HIP_DEVICE_COMPILE__
+
+// Clock function to return GPU core cycle count.
+// GPU can change its core clock frequency at runtime. The maximum frequency can be queried
+// through hipDeviceAttributeClockRate attribute.
+__device__
+inline __attribute((always_inline))
+long long int __clock64() {
+#if __has_builtin(__builtin_amdgcn_s_memtime)
+ // Exists on gfx8, gfx9, gfx10.1, gfx10.2, gfx10.3
+ return (long long int) __builtin_amdgcn_s_memtime();
+#else
+ // Subject to change when better solution available
+ return (long long int) __builtin_readcyclecounter();
+#endif
+}
+
+__device__
+inline __attribute((always_inline))
+long long int __clock() { return __clock64(); }
+
+// Clock function to return wall clock count at a constant frequency that can be queried
+// through hipDeviceAttributeWallClockRate attribute.
+__device__
+inline __attribute__((always_inline))
+long long int wall_clock64() {
+ return (long long int) __ockl_steadyctr_u64();
+}
+
+__device__
+inline __attribute__((always_inline))
+long long int clock64() { return __clock64(); }
+
+__device__
+inline __attribute__((always_inline))
+long long int clock() { return __clock(); }
+
+// hip.amdgcn.bc - named sync
+__device__
+inline
+void __named_sync() { __builtin_amdgcn_s_barrier(); }
+
+#endif // __HIP_DEVICE_COMPILE__
+
+// hip.amdgcn.bc - lanemask
+__device__
+inline
+uint64_t __lanemask_gt()
+{
+ uint32_t lane = __ockl_lane_u32();
+ if (lane == 63)
+ return 0;
+ uint64_t ballot = __ballot64(1);
+ uint64_t mask = (~((uint64_t)0)) << (lane + 1);
+ return mask & ballot;
+}
+
+__device__
+inline
+uint64_t __lanemask_lt()
+{
+ uint32_t lane = __ockl_lane_u32();
+ int64_t ballot = __ballot64(1);
+ uint64_t mask = ((uint64_t)1 << lane) - (uint64_t)1;
+ return mask & ballot;
+}
+
+__device__
+inline
+uint64_t __lanemask_eq()
+{
+ uint32_t lane = __ockl_lane_u32();
+ int64_t mask = ((uint64_t)1 << lane);
+ return mask;
+}
+
+
+__device__ inline void* __local_to_generic(void* p) { return p; }
+
+#ifdef __HIP_DEVICE_COMPILE__
+__device__
+inline
+void* __get_dynamicgroupbaseptr()
+{
+ // Get group segment base pointer.
+ return (char*)__local_to_generic((void*)__to_local(__builtin_amdgcn_groupstaticsize()));
+}
+#else
+__device__
+void* __get_dynamicgroupbaseptr();
+#endif // __HIP_DEVICE_COMPILE__
+
+__device__
+inline
+void *__amdgcn_get_dynamicgroupbaseptr() {
+ return __get_dynamicgroupbaseptr();
+}
+
+// Memory Fence Functions
+__device__
+inline
+static void __threadfence()
+{
+ __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "agent");
+}
+
+__device__
+inline
+static void __threadfence_block()
+{
+ __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup");
+}
+
+__device__
+inline
+static void __threadfence_system()
+{
+ __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "");
+}
+__device__ inline static void __work_group_barrier(__cl_mem_fence_flags flags) {
+ if (flags) {
+ __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup");
+ __builtin_amdgcn_s_barrier();
+ __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup");
+ } else {
+ __builtin_amdgcn_s_barrier();
+ }
+}
+
+__device__
+inline
+static void __barrier(int n)
+{
+ __work_group_barrier((__cl_mem_fence_flags)n);
+}
+
+__device__
+inline
+__attribute__((convergent))
+void __syncthreads()
+{
+ __barrier(__CLK_LOCAL_MEM_FENCE);
+}
+
+__device__
+inline
+__attribute__((convergent))
+int __syncthreads_count(int predicate)
+{
+ return __ockl_wgred_add_i32(!!predicate);
+}
+
+__device__
+inline
+__attribute__((convergent))
+int __syncthreads_and(int predicate)
+{
+ return __ockl_wgred_and_i32(!!predicate);
+}
+
+__device__
+inline
+__attribute__((convergent))
+int __syncthreads_or(int predicate)
+{
+ return __ockl_wgred_or_i32(!!predicate);
+}
+
+// hip.amdgcn.bc - device routine
+/*
+ HW_ID Register bit structure for RDNA2 & RDNA3
+ WAVE_ID 4:0 Wave id within the SIMD.
+ SIMD_ID 9:8 SIMD_ID within the WGP: [0] = row, [1] = column.
+ WGP_ID 13:10 Physical WGP ID.
+ SA_ID 16 Shader Array ID
+ SE_ID 20:18 Shader Engine the wave is assigned to for gfx11
+ SE_ID 19:18 Shader Engine the wave is assigned to for gfx10
+ DP_RATE 31:29 Number of double-precision float units per SIMD
+
+ HW_ID Register bit structure for GCN and CDNA
+ WAVE_ID 3:0 Wave buffer slot number. 0-9.
+ SIMD_ID 5:4 SIMD which the wave is assigned to within the CU.
+ PIPE_ID 7:6 Pipeline from which the wave was dispatched.
+ CU_ID 11:8 Compute Unit the wave is assigned to.
+ SH_ID 12 Shader Array (within an SE) the wave is assigned to.
+ SE_ID 15:13 Shader Engine the wave is assigned to for gfx908, gfx90a, gfx940-942
+ 14:13 Shader Engine the wave is assigned to for Vega.
+ TG_ID 19:16 Thread-group ID
+ VM_ID 23:20 Virtual Memory ID
+ QUEUE_ID 26:24 Queue from which this wave was dispatched.
+ STATE_ID 29:27 State ID (graphics only, not compute).
+ ME_ID 31:30 Micro-engine ID.
+
+ XCC_ID Register bit structure for gfx940
+ XCC_ID 3:0 XCC the wave is assigned to.
+ */
+
+#if (defined (__GFX10__) || defined (__GFX11__))
+ #define HW_ID 23
+#else
+ #define HW_ID 4
+#endif
+
+#if (defined(__GFX10__) || defined(__GFX11__))
+ #define HW_ID_WGP_ID_SIZE 4
+ #define HW_ID_WGP_ID_OFFSET 10
+ #if (defined(__AMDGCN_CUMODE__))
+ #define HW_ID_CU_ID_SIZE 1
+ #define HW_ID_CU_ID_OFFSET 8
+ #endif
+#else
+ #define HW_ID_CU_ID_SIZE 4
+ #define HW_ID_CU_ID_OFFSET 8
+#endif
+
+#if (defined(__gfx908__) || defined(__gfx90a__) || \
+ defined(__GFX11__))
+ #define HW_ID_SE_ID_SIZE 3
+#else //4 SEs/XCC for gfx940-942
+ #define HW_ID_SE_ID_SIZE 2
+#endif
+#if (defined(__GFX10__) || defined(__GFX11__))
+ #define HW_ID_SE_ID_OFFSET 18
+ #define HW_ID_SA_ID_OFFSET 16
+ #define HW_ID_SA_ID_SIZE 1
+#else
+ #define HW_ID_SE_ID_OFFSET 13
+#endif
+
+#if (defined(__gfx940__) || defined(__gfx941__) || defined(__gfx942__))
+ #define XCC_ID 20
+ #define XCC_ID_XCC_ID_SIZE 4
+ #define XCC_ID_XCC_ID_OFFSET 0
+#endif
+
+#if (!defined(__HIP_NO_IMAGE_SUPPORT) && \
+ (defined(__gfx940__) || defined(__gfx941__) || defined(__gfx942__)))
+ #define __HIP_NO_IMAGE_SUPPORT 1
+#endif
+
+/*
+ Encoding of parameter bitmask
+ HW_ID 5:0 HW_ID
+ OFFSET 10:6 Range: 0..31
+ SIZE 15:11 Range: 1..32
+ */
+
+#define GETREG_IMMED(SZ,OFF,REG) (((SZ) << 11) | ((OFF) << 6) | (REG))
+
+/*
+ __smid returns the wave's assigned Compute Unit and Shader Engine.
+ The Compute Unit, CU_ID returned in bits 3:0, and Shader Engine, SE_ID in bits 5:4.
+ Note: the results vary over time.
+ SZ minus 1 since SIZE is 1-based.
+*/
+__device__
+inline
+unsigned __smid(void)
+{
+ unsigned se_id = __builtin_amdgcn_s_getreg(
+ GETREG_IMMED(HW_ID_SE_ID_SIZE-1, HW_ID_SE_ID_OFFSET, HW_ID));
+ #if (defined(__GFX10__) || defined(__GFX11__))
+ unsigned wgp_id = __builtin_amdgcn_s_getreg(
+ GETREG_IMMED(HW_ID_WGP_ID_SIZE - 1, HW_ID_WGP_ID_OFFSET, HW_ID));
+ unsigned sa_id = __builtin_amdgcn_s_getreg(
+ GETREG_IMMED(HW_ID_SA_ID_SIZE - 1, HW_ID_SA_ID_OFFSET, HW_ID));
+ #if (defined(__AMDGCN_CUMODE__))
+ unsigned cu_id = __builtin_amdgcn_s_getreg(
+ GETREG_IMMED(HW_ID_CU_ID_SIZE - 1, HW_ID_CU_ID_OFFSET, HW_ID));
+ #endif
+ #else
+ #if (defined(__gfx940__) || defined(__gfx941__) || defined(__gfx942__))
+ unsigned xcc_id = __builtin_amdgcn_s_getreg(
+ GETREG_IMMED(XCC_ID_XCC_ID_SIZE - 1, XCC_ID_XCC_ID_OFFSET, XCC_ID));
+ #endif
+ unsigned cu_id = __builtin_amdgcn_s_getreg(
+ GETREG_IMMED(HW_ID_CU_ID_SIZE - 1, HW_ID_CU_ID_OFFSET, HW_ID));
+ #endif
+ #if (defined(__GFX10__) || defined(__GFX11__))
+ unsigned temp = se_id;
+ temp = (temp << HW_ID_SA_ID_SIZE) | sa_id;
+ temp = (temp << HW_ID_WGP_ID_SIZE) | wgp_id;
+ #if (defined(__AMDGCN_CUMODE__))
+ temp = (temp << HW_ID_CU_ID_SIZE) | cu_id;
+ #endif
+ return temp;
+ //TODO : CU Mode impl
+ #elif (defined(__gfx940__) || defined(__gfx941__) || defined(__gfx942__))
+ unsigned temp = xcc_id;
+ temp = (temp << HW_ID_SE_ID_SIZE) | se_id;
+ temp = (temp << HW_ID_CU_ID_SIZE) | cu_id;
+ return temp;
+ #else
+ return (se_id << HW_ID_CU_ID_SIZE) + cu_id;
+ #endif
+}
+
+/**
+ * Map HIP_DYNAMIC_SHARED to "extern __shared__" for compatibility with old HIP applications
+ * To be removed in a future release.
+ */
+#define HIP_DYNAMIC_SHARED(type, var) extern __shared__ type var[];
+#define HIP_DYNAMIC_SHARED_ATTRIBUTE
+
+#endif //defined(__clang__) && defined(__HIP__)
+
+
+// loop unrolling
+static inline __device__ void* __hip_hc_memcpy(void* dst, const void* src, size_t size) {
+ auto dstPtr = static_cast(dst);
+ auto srcPtr = static_cast(src);
+
+ while (size >= 4u) {
+ dstPtr[0] = srcPtr[0];
+ dstPtr[1] = srcPtr[1];
+ dstPtr[2] = srcPtr[2];
+ dstPtr[3] = srcPtr[3];
+
+ size -= 4u;
+ srcPtr += 4u;
+ dstPtr += 4u;
+ }
+ switch (size) {
+ case 3:
+ dstPtr[2] = srcPtr[2];
+ case 2:
+ dstPtr[1] = srcPtr[1];
+ case 1:
+ dstPtr[0] = srcPtr[0];
+ }
+
+ return dst;
+}
+
+static inline __device__ void* __hip_hc_memset(void* dst, unsigned char val, size_t size) {
+ auto dstPtr = static_cast(dst);
+
+ while (size >= 4u) {
+ dstPtr[0] = val;
+ dstPtr[1] = val;
+ dstPtr[2] = val;
+ dstPtr[3] = val;
+
+ size -= 4u;
+ dstPtr += 4u;
+ }
+ switch (size) {
+ case 3:
+ dstPtr[2] = val;
+ case 2:
+ dstPtr[1] = val;
+ case 1:
+ dstPtr[0] = val;
+ }
+
+ return dst;
+}
+#ifndef __OPENMP_AMDGCN__
+static inline __device__ void* memcpy(void* dst, const void* src, size_t size) {
+ return __hip_hc_memcpy(dst, src, size);
+}
+
+static inline __device__ void* memset(void* ptr, int val, size_t size) {
+ unsigned char val8 = static_cast(val);
+ return __hip_hc_memset(ptr, val8, size);
+}
+#endif // !__OPENMP_AMDGCN__
+
+#endif
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_atomic.h b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_atomic.h
new file mode 100644
index 0000000000000000000000000000000000000000..d6e4d818690954406975559227fe0c59408a5790
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_atomic.h
@@ -0,0 +1,1638 @@
+/*
+Copyright (c) 2015 - Present 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.
+*/
+
+#pragma once
+
+#if !defined(__HIPCC_RTC__)
+#include "amd_device_functions.h"
+#endif
+
+#if __has_builtin(__hip_atomic_compare_exchange_strong)
+
+template struct Cond_t;
+
+template struct Cond_t { using type = T; };
+template struct Cond_t { using type = F; };
+
+#if !__HIP_DEVICE_COMPILE__
+//TODO: Remove this after compiler pre-defines the following Macros.
+#define __HIP_MEMORY_SCOPE_SINGLETHREAD 1
+#define __HIP_MEMORY_SCOPE_WAVEFRONT 2
+#define __HIP_MEMORY_SCOPE_WORKGROUP 3
+#define __HIP_MEMORY_SCOPE_AGENT 4
+#define __HIP_MEMORY_SCOPE_SYSTEM 5
+#endif
+
+#if !defined(__HIPCC_RTC__)
+#include "amd_hip_unsafe_atomics.h"
+#endif
+
+// Atomic expanders
+template<
+ int mem_order = __ATOMIC_SEQ_CST,
+ int mem_scope= __HIP_MEMORY_SCOPE_SYSTEM,
+ typename T,
+ typename Op,
+ typename F>
+inline
+__attribute__((always_inline, device))
+T hip_cas_expander(T* p, T x, Op op, F f) noexcept
+{
+ using FP = __attribute__((address_space(0))) const void*;
+
+ __device__
+ extern bool is_shared_workaround(FP) asm("llvm.amdgcn.is.shared");
+
+ if (is_shared_workaround((FP)p))
+ return f();
+
+ using U = typename Cond_t<
+ sizeof(T) == sizeof(unsigned int), unsigned int, unsigned long long>::type;
+
+ auto q = reinterpret_cast(p);
+
+ U tmp0{__hip_atomic_load(q, mem_order, mem_scope)};
+ U tmp1;
+ do {
+ tmp1 = tmp0;
+
+ op(reinterpret_cast(tmp1), x);
+ } while (!__hip_atomic_compare_exchange_strong(q, &tmp0, tmp1, mem_order,
+ mem_order, mem_scope));
+
+ return reinterpret_cast(tmp0);
+}
+
+template<
+ int mem_order = __ATOMIC_SEQ_CST,
+ int mem_scope= __HIP_MEMORY_SCOPE_SYSTEM,
+ typename T,
+ typename Cmp,
+ typename F>
+inline
+__attribute__((always_inline, device))
+T hip_cas_extrema_expander(T* p, T x, Cmp cmp, F f) noexcept
+{
+ using FP = __attribute__((address_space(0))) const void*;
+
+ __device__
+ extern bool is_shared_workaround(FP) asm("llvm.amdgcn.is.shared");
+
+ if (is_shared_workaround((FP)p))
+ return f();
+
+ using U = typename Cond_t<
+ sizeof(T) == sizeof(unsigned int), unsigned int, unsigned long long>::type;
+
+ auto q = reinterpret_cast(p);
+
+ U tmp{__hip_atomic_load(q, mem_order, mem_scope)};
+ while (cmp(x, reinterpret_cast(tmp)) &&
+ !__hip_atomic_compare_exchange_strong(q, &tmp, x, mem_order, mem_order,
+ mem_scope));
+
+ return reinterpret_cast(tmp);
+}
+
+__device__
+inline
+int atomicCAS(int* address, int compare, int val) {
+ __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ return compare;
+}
+
+__device__
+inline
+int atomicCAS_system(int* address, int compare, int val) {
+ __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ return compare;
+}
+
+__device__
+inline
+unsigned int atomicCAS(unsigned int* address, unsigned int compare, unsigned int val) {
+ __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ return compare;
+}
+
+__device__
+inline
+unsigned int atomicCAS_system(unsigned int* address, unsigned int compare, unsigned int val) {
+ __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ return compare;
+}
+
+__device__
+inline
+unsigned long atomicCAS(unsigned long* address, unsigned long compare, unsigned long val) {
+ __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ return compare;
+}
+
+__device__
+inline
+unsigned long atomicCAS_system(unsigned long* address, unsigned long compare, unsigned long val) {
+ __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ return compare;
+}
+
+__device__
+inline
+unsigned long long atomicCAS(unsigned long long* address, unsigned long long compare,
+ unsigned long long val) {
+ __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ return compare;
+}
+
+__device__
+inline
+unsigned long long atomicCAS_system(unsigned long long* address, unsigned long long compare,
+ unsigned long long val) {
+ __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ return compare;
+}
+
+__device__
+inline
+float atomicCAS(float* address, float compare, float val) {
+ __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ return compare;
+}
+
+__device__
+inline
+float atomicCAS_system(float* address, float compare, float val) {
+ __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ return compare;
+}
+
+__device__
+inline
+double atomicCAS(double* address, double compare, double val) {
+ __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ return compare;
+}
+
+__device__
+inline
+double atomicCAS_system(double* address, double compare, double val) {
+ __hip_atomic_compare_exchange_strong(address, &compare, val, __ATOMIC_RELAXED, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ return compare;
+}
+
+__device__
+inline
+int atomicAdd(int* address, int val) {
+ return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+}
+
+__device__
+inline
+int atomicAdd_system(int* address, int val) {
+ return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+__device__
+inline
+unsigned int atomicAdd(unsigned int* address, unsigned int val) {
+ return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+}
+
+__device__
+inline
+unsigned int atomicAdd_system(unsigned int* address, unsigned int val) {
+ return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+__device__
+inline
+unsigned long atomicAdd(unsigned long* address, unsigned long val) {
+ return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+}
+
+__device__
+inline
+unsigned long atomicAdd_system(unsigned long* address, unsigned long val) {
+ return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+__device__
+inline
+unsigned long long atomicAdd(unsigned long long* address, unsigned long long val) {
+ return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+}
+
+__device__
+inline
+unsigned long long atomicAdd_system(unsigned long long* address, unsigned long long val) {
+ return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+__device__
+inline
+float atomicAdd(float* address, float val) {
+#if defined(__AMDGCN_UNSAFE_FP_ATOMICS__)
+ return unsafeAtomicAdd(address, val);
+#else
+ return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif
+}
+
+__device__
+inline
+float atomicAdd_system(float* address, float val) {
+ return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+#if !defined(__HIPCC_RTC__)
+DEPRECATED("use atomicAdd instead")
+#endif // !defined(__HIPCC_RTC__)
+__device__
+inline
+void atomicAddNoRet(float* address, float val)
+{
+ __ockl_atomic_add_noret_f32(address, val);
+}
+
+__device__
+inline
+double atomicAdd(double* address, double val) {
+#if defined(__AMDGCN_UNSAFE_FP_ATOMICS__)
+ return unsafeAtomicAdd(address, val);
+#else
+ return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif
+}
+
+__device__
+inline
+double atomicAdd_system(double* address, double val) {
+ return __hip_atomic_fetch_add(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+__device__
+inline
+int atomicSub(int* address, int val) {
+ return __hip_atomic_fetch_add(address, -val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+}
+
+__device__
+inline
+int atomicSub_system(int* address, int val) {
+ return __hip_atomic_fetch_add(address, -val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+__device__
+inline
+unsigned int atomicSub(unsigned int* address, unsigned int val) {
+ return __hip_atomic_fetch_add(address, -val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+}
+
+__device__
+inline
+unsigned int atomicSub_system(unsigned int* address, unsigned int val) {
+ return __hip_atomic_fetch_add(address, -val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+__device__
+inline
+unsigned long atomicSub(unsigned long* address, unsigned long val) {
+ return __hip_atomic_fetch_add(address, -val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+}
+
+__device__
+inline
+unsigned long atomicSub_system(unsigned long* address, unsigned long val) {
+ return __hip_atomic_fetch_add(address, -val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+__device__
+inline
+unsigned long long atomicSub(unsigned long long* address, unsigned long long val) {
+ return __hip_atomic_fetch_add(address, -val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+}
+
+__device__
+inline
+unsigned long long atomicSub_system(unsigned long long* address, unsigned long long val) {
+ return __hip_atomic_fetch_add(address, -val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+__device__
+inline
+float atomicSub(float* address, float val) {
+#if defined(__AMDGCN_UNSAFE_FP_ATOMICS__)
+ return unsafeAtomicAdd(address, -val);
+#else
+ return __hip_atomic_fetch_add(address, -val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif
+}
+
+__device__
+inline
+float atomicSub_system(float* address, float val) {
+ return __hip_atomic_fetch_add(address, -val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+__device__
+inline
+double atomicSub(double* address, double val) {
+#if defined(__AMDGCN_UNSAFE_FP_ATOMICS__)
+ return unsafeAtomicAdd(address, -val);
+#else
+ return __hip_atomic_fetch_add(address, -val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif
+}
+
+__device__
+inline
+double atomicSub_system(double* address, double val) {
+ return __hip_atomic_fetch_add(address, -val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+__device__
+inline
+int atomicExch(int* address, int val) {
+ return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+}
+
+__device__
+inline
+int atomicExch_system(int* address, int val) {
+ return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+__device__
+inline
+unsigned int atomicExch(unsigned int* address, unsigned int val) {
+ return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+}
+
+__device__
+inline
+unsigned int atomicExch_system(unsigned int* address, unsigned int val) {
+ return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+__device__
+inline
+unsigned long atomicExch(unsigned long* address, unsigned long val) {
+ return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+}
+
+__device__
+inline
+unsigned long atomicExch_system(unsigned long* address, unsigned long val) {
+ return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+__device__
+inline
+unsigned long long atomicExch(unsigned long long* address, unsigned long long val) {
+ return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+}
+
+__device__
+inline
+unsigned long long atomicExch_system(unsigned long long* address, unsigned long long val) {
+ return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+__device__
+inline
+float atomicExch(float* address, float val) {
+ return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+}
+
+__device__
+inline
+float atomicExch_system(float* address, float val) {
+ return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+__device__
+inline
+double atomicExch(double* address, double val) {
+ return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+}
+
+__device__
+inline
+double atomicExch_system(double* address, double val) {
+ return __hip_atomic_exchange(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+__device__
+inline
+int atomicMin(int* address, int val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address, val, [](int x, int y) { return x < y; }, [=]() {
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+int atomicMin_system(int* address, int val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address, val, [](int x, int y) { return x < y; }, [=]() {
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned int atomicMin(unsigned int* address, unsigned int val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address, val, [](unsigned int x, unsigned int y) { return x < y; }, [=]() {
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+
+}
+
+__device__
+inline
+unsigned int atomicMin_system(unsigned int* address, unsigned int val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address, val, [](unsigned int x, unsigned int y) { return x < y; }, [=]() {
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long long atomicMin(unsigned long* address, unsigned long val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address,
+ val,
+ [](unsigned long x, unsigned long y) { return x < y; },
+ [=]() {
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long atomicMin_system(unsigned long* address, unsigned long val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address,
+ val,
+ [](unsigned long x, unsigned long y) { return x < y; },
+ [=]() {
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long long atomicMin(unsigned long long* address, unsigned long long val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address,
+ val,
+ [](unsigned long long x, unsigned long long y) { return x < y; },
+ [=]() {
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long long atomicMin_system(unsigned long long* address, unsigned long long val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address,
+ val,
+ [](unsigned long long x, unsigned long long y) { return x < y; },
+ [=]() {
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+long long atomicMin(long long* address, long long val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address, val, [](long long x, long long y) { return x < y; },
+ [=]() {
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+long long atomicMin_system(long long* address, long long val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address, val, [](long long x, long long y) { return x < y; },
+ [=]() {
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_min(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+float atomicMin(float* addr, float val) {
+#if defined(__AMDGCN_UNSAFE_FP_ATOMICS__)
+ return unsafeAtomicMin(addr, val);
+#else
+ typedef union u_hold {
+ float a;
+ unsigned int b;
+ } u_hold_t;
+ u_hold_t u{val};
+ bool neg_zero = 0x80000000U == u.b;
+ #if __has_builtin(__hip_atomic_load) && \
+ __has_builtin(__hip_atomic_compare_exchange_strong)
+ float value = __hip_atomic_load(addr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+ bool done = false;
+ while (!done && (value > val || (neg_zero && value == 0.0f))) {
+ done = __hip_atomic_compare_exchange_strong(addr, &value, val,
+ __ATOMIC_RELAXED, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+ }
+ return value;
+ #else
+ unsigned int *uaddr = (unsigned int *)addr;
+ unsigned int value = __atomic_load_n(uaddr, __ATOMIC_RELAXED);
+ bool done = false;
+ while (!done && (__uint_as_float(value) > val || (neg_zero && __uint_as_float(value) == 0.0f))) {
+ done = __atomic_compare_exchange_n(uaddr, &value, __float_as_uint(val), false,
+ __ATOMIC_RELAXED, __ATOMIC_RELAXED);
+ }
+ return __uint_as_float(value);
+ #endif
+#endif
+}
+
+__device__
+inline
+float atomicMin_system(float* address, float val) {
+ unsigned int* uaddr { reinterpret_cast(address) };
+ #if __has_builtin(__hip_atomic_load)
+ unsigned int tmp {__hip_atomic_load(uaddr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM)};
+ #else
+ unsigned int tmp {__atomic_load_n(uaddr, __ATOMIC_RELAXED)};
+ #endif
+ float value = __uint_as_float(tmp);
+
+ while (val < value) {
+ value = atomicCAS_system(address, value, val);
+ }
+
+ return value;
+}
+
+__device__
+inline
+double atomicMin(double* addr, double val) {
+#if defined(__AMDGCN_UNSAFE_FP_ATOMICS__)
+ return unsafeAtomicMin(addr, val);
+#else
+ typedef union u_hold {
+ double a;
+ unsigned long long b;
+ } u_hold_t;
+ u_hold_t u{val};
+ bool neg_zero = 0x8000000000000000ULL == u.b;
+ #if __has_builtin(__hip_atomic_load) && \
+ __has_builtin(__hip_atomic_compare_exchange_strong)
+ double value = __hip_atomic_load(addr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+ bool done = false;
+ while (!done && (value > val || (neg_zero && value == 0.0))) {
+ done = __hip_atomic_compare_exchange_strong(addr, &value, val,
+ __ATOMIC_RELAXED, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+ }
+ return value;
+ #else
+ unsigned long long *uaddr = (unsigned long long *)addr;
+ unsigned long long value = __atomic_load_n(uaddr, __ATOMIC_RELAXED);
+ bool done = false;
+ while (!done &&
+ (__longlong_as_double(value) > val || (neg_zero && __longlong_as_double(value) == 0.0))) {
+ done = __atomic_compare_exchange_n(uaddr, &value, __double_as_longlong(val), false,
+ __ATOMIC_RELAXED, __ATOMIC_RELAXED);
+ }
+ return __longlong_as_double(value);
+ #endif
+#endif
+}
+
+__device__
+inline
+double atomicMin_system(double* address, double val) {
+ unsigned long long* uaddr { reinterpret_cast(address) };
+ #if __has_builtin(__hip_atomic_load)
+ unsigned long long tmp {__hip_atomic_load(uaddr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM)};
+ #else
+ unsigned long long tmp {__atomic_load_n(uaddr, __ATOMIC_RELAXED)};
+ #endif
+ double value = __longlong_as_double(tmp);
+
+ while (val < value) {
+ value = atomicCAS_system(address, value, val);
+ }
+
+ return value;
+}
+
+__device__
+inline
+int atomicMax(int* address, int val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address, val, [](int x, int y) { return y < x; }, [=]() {
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+int atomicMax_system(int* address, int val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address, val, [](int x, int y) { return y < x; }, [=]() {
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned int atomicMax(unsigned int* address, unsigned int val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address, val, [](unsigned int x, unsigned int y) { return y < x; }, [=]() {
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned int atomicMax_system(unsigned int* address, unsigned int val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address, val, [](unsigned int x, unsigned int y) { return y < x; }, [=]() {
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long atomicMax(unsigned long* address, unsigned long val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address,
+ val,
+ [](unsigned long x, unsigned long y) { return y < x; },
+ [=]() {
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long atomicMax_system(unsigned long* address, unsigned long val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address,
+ val,
+ [](unsigned long x, unsigned long y) { return y < x; },
+ [=]() {
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long long atomicMax(unsigned long long* address, unsigned long long val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address,
+ val,
+ [](unsigned long long x, unsigned long long y) { return y < x; },
+ [=]() {
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long long atomicMax_system(unsigned long long* address, unsigned long long val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address,
+ val,
+ [](unsigned long long x, unsigned long long y) { return y < x; },
+ [=]() {
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+long long atomicMax(long long* address, long long val) {
+ #if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address, val, [](long long x, long long y) { return y < x; },
+ [=]() {
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+long long atomicMax_system(long long* address, long long val) {
+#if defined(__gfx941__)
+ return hip_cas_extrema_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address, val, [](long long x, long long y) { return y < x; },
+ [=]() {
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_max(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+float atomicMax(float* addr, float val) {
+#if defined(__AMDGCN_UNSAFE_FP_ATOMICS__)
+ return unsafeAtomicMax(addr, val);
+#else
+ typedef union u_hold {
+ float a;
+ unsigned int b;
+ } u_hold_t;
+ u_hold_t u{val};
+ bool neg_zero = 0x80000000U == u.b;
+ #if __has_builtin(__hip_atomic_load) && \
+ __has_builtin(__hip_atomic_compare_exchange_strong)
+ float value = __hip_atomic_load(addr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+ bool done = false;
+ while (!done && (value < val || (neg_zero && value == 0.0f))) {
+ done = __hip_atomic_compare_exchange_strong(addr, &value, val,
+ __ATOMIC_RELAXED, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+ }
+ return value;
+ #else
+ unsigned int *uaddr = (unsigned int *)addr;
+ unsigned int value = __atomic_load_n(uaddr, __ATOMIC_RELAXED);
+ bool done = false;
+ while (!done && (__uint_as_float(value) < val || (neg_zero && __uint_as_float(value) == 0.0f))) {
+ done = __atomic_compare_exchange_n(uaddr, &value, __float_as_uint(val), false,
+ __ATOMIC_RELAXED, __ATOMIC_RELAXED);
+ }
+ return __uint_as_float(value);
+ #endif
+#endif
+}
+
+__device__
+inline
+float atomicMax_system(float* address, float val) {
+ unsigned int* uaddr { reinterpret_cast(address) };
+ #if __has_builtin(__hip_atomic_load)
+ unsigned int tmp {__hip_atomic_load(uaddr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM)};
+ #else
+ unsigned int tmp {__atomic_load_n(uaddr, __ATOMIC_RELAXED)};
+ #endif
+ float value = __uint_as_float(tmp);
+
+ while (value < val) {
+ value = atomicCAS_system(address, value, val);
+ }
+
+ return value;
+}
+
+__device__
+inline
+double atomicMax(double* addr, double val) {
+#if defined(__AMDGCN_UNSAFE_FP_ATOMICS__)
+ return unsafeAtomicMax(addr, val);
+#else
+ typedef union u_hold {
+ double a;
+ unsigned long long b;
+ } u_hold_t;
+ u_hold_t u{val};
+ bool neg_zero = 0x8000000000000000ULL == u.b;
+ #if __has_builtin(__hip_atomic_load) && \
+ __has_builtin(__hip_atomic_compare_exchange_strong)
+ double value = __hip_atomic_load(addr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+ bool done = false;
+ while (!done && (value < val || (neg_zero && value == 0.0))) {
+ done = __hip_atomic_compare_exchange_strong(addr, &value, val,
+ __ATOMIC_RELAXED, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+ }
+ return value;
+ #else
+ unsigned long long *uaddr = (unsigned long long *)addr;
+ unsigned long long value = __atomic_load_n(uaddr, __ATOMIC_RELAXED);
+ bool done = false;
+ while (!done &&
+ (__longlong_as_double(value) < val || (neg_zero && __longlong_as_double(value) == 0.0))) {
+ done = __atomic_compare_exchange_n(uaddr, &value, __double_as_longlong(val), false,
+ __ATOMIC_RELAXED, __ATOMIC_RELAXED);
+ }
+ return __longlong_as_double(value);
+ #endif
+#endif
+}
+
+__device__
+inline
+double atomicMax_system(double* address, double val) {
+ unsigned long long* uaddr { reinterpret_cast(address) };
+ #if __has_builtin(__hip_atomic_load)
+ unsigned long long tmp {__hip_atomic_load(uaddr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM)};
+ #else
+ unsigned long long tmp {__atomic_load_n(uaddr, __ATOMIC_RELAXED)};
+ #endif
+ double value = __longlong_as_double(tmp);
+
+ while (value < val) {
+ value = atomicCAS_system(address, value, val);
+ }
+
+ return value;
+}
+
+__device__
+inline
+unsigned int atomicInc(unsigned int* address, unsigned int val)
+{
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address,
+ val,
+ [](unsigned int& x, unsigned int y) { x = (x >= y) ? 0 : (x + 1); },
+ [=]() {
+ return
+ __builtin_amdgcn_atomic_inc32(address, val, __ATOMIC_RELAXED, "agent");
+ });
+#else
+ return __builtin_amdgcn_atomic_inc32(address, val, __ATOMIC_RELAXED, "agent");
+#endif // __gfx941__
+
+}
+
+__device__
+inline
+unsigned int atomicDec(unsigned int* address, unsigned int val)
+{
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address,
+ val,
+ [](unsigned int& x, unsigned int y) { x = (!x || x > y) ? y : (x - 1); },
+ [=]() {
+ return
+ __builtin_amdgcn_atomic_dec32(address, val, __ATOMIC_RELAXED, "agent");
+ });
+#else
+ return __builtin_amdgcn_atomic_dec32(address, val, __ATOMIC_RELAXED, "agent");
+#endif // __gfx941__
+
+}
+
+__device__
+inline
+int atomicAnd(int* address, int val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address, val, [](int& x, int y) { x &= y; }, [=]() {
+ return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+int atomicAnd_system(int* address, int val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address, val, [](int& x, int y) { x &= y; }, [=]() {
+ return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned int atomicAnd(unsigned int* address, unsigned int val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address, val, [](unsigned int& x, unsigned int y) { x &= y; }, [=]() {
+ return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned int atomicAnd_system(unsigned int* address, unsigned int val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address, val, [](unsigned int& x, unsigned int y) { x &= y; }, [=]() {
+ return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long atomicAnd(unsigned long* address, unsigned long val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address, val, [](unsigned long& x, unsigned long y) { x &= y; }, [=]() {
+ return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long atomicAnd_system(unsigned long* address, unsigned long val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address, val, [](unsigned long& x, unsigned long y) { x &= y; }, [=]() {
+ return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long long atomicAnd(unsigned long long* address, unsigned long long val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address,
+ val,
+ [](unsigned long long& x, unsigned long long y) { x &= y; },
+ [=]() {
+ return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long long atomicAnd_system(unsigned long long* address, unsigned long long val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address,
+ val,
+ [](unsigned long long& x, unsigned long long y) { x &= y; },
+ [=]() {
+ return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_and(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+int atomicOr(int* address, int val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address, val, [](int& x, int y) { x |= y; }, [=]() {
+ return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+int atomicOr_system(int* address, int val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address, val, [](int& x, int y) { x |= y; }, [=]() {
+ return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned int atomicOr(unsigned int* address, unsigned int val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address, val, [](unsigned int& x, unsigned int y) { x |= y; }, [=]() {
+ return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned int atomicOr_system(unsigned int* address, unsigned int val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address, val, [](unsigned int& x, unsigned int y) { x |= y; }, [=]() {
+ return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long atomicOr(unsigned long* address, unsigned long val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address, val, [](unsigned long& x, unsigned long y) { x |= y; }, [=]() {
+ return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long atomicOr_system(unsigned long* address, unsigned long val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address, val, [](unsigned long& x, unsigned long y) { x |= y; }, [=]() {
+ return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long long atomicOr(unsigned long long* address, unsigned long long val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address,
+ val,
+ [](unsigned long long& x, unsigned long long y) { x |= y; },
+ [=]() {
+ return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long long atomicOr_system(unsigned long long* address, unsigned long long val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address,
+ val,
+ [](unsigned long long& x, unsigned long long y) { x |= y; },
+ [=]() {
+ return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_or(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+int atomicXor(int* address, int val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address, val, [](int& x, int y) { x ^= y; }, [=]() {
+ return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+int atomicXor_system(int* address, int val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address, val, [](int& x, int y) { x ^= y; }, [=]() {
+ return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned int atomicXor(unsigned int* address, unsigned int val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address, val, [](unsigned int& x, unsigned int y) { x ^= y; }, [=]() {
+ return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned int atomicXor_system(unsigned int* address, unsigned int val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address, val, [](unsigned int& x, unsigned int y) { x ^= y; }, [=]() {
+ return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long atomicXor(unsigned long* address, unsigned long val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address, val, [](unsigned long& x, unsigned long y) { x ^= y; }, [=]() {
+ return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long atomicXor_system(unsigned long* address, unsigned long val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM>(
+ address, val, [](unsigned long& x, unsigned long y) { x ^= y; }, [=]() {
+ return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_SYSTEM);
+ });
+#else
+ return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long long atomicXor(unsigned long long* address, unsigned long long val) {
+#if defined(__gfx941__)
+ return hip_cas_expander<__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT>(
+ address,
+ val,
+ [](unsigned long long& x, unsigned long long y) { x ^= y; },
+ [=]() {
+ return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED,
+ __HIP_MEMORY_SCOPE_AGENT);
+ });
+#else
+ return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+#endif // __gfx941__
+}
+
+__device__
+inline
+unsigned long long atomicXor_system(unsigned long long* address, unsigned long long val) {
+ return __hip_atomic_fetch_xor(address, val, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
+}
+
+#else // __hip_atomic_compare_exchange_strong
+
+__device__
+inline
+int atomicCAS(int* address, int compare, int val)
+{
+ __atomic_compare_exchange_n(
+ address, &compare, val, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED);
+
+ return compare;
+}
+__device__
+inline
+unsigned int atomicCAS(
+ unsigned int* address, unsigned int compare, unsigned int val)
+{
+ __atomic_compare_exchange_n(
+ address, &compare, val, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED);
+
+ return compare;
+}
+__device__
+inline
+unsigned long long atomicCAS(
+ unsigned long long* address,
+ unsigned long long compare,
+ unsigned long long val)
+{
+ __atomic_compare_exchange_n(
+ address, &compare, val, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED);
+
+ return compare;
+}
+
+__device__
+inline
+int atomicAdd(int* address, int val)
+{
+ return __atomic_fetch_add(address, val, __ATOMIC_RELAXED);
+}
+__device__
+inline
+unsigned int atomicAdd(unsigned int* address, unsigned int val)
+{
+ return __atomic_fetch_add(address, val, __ATOMIC_RELAXED);
+}
+__device__
+inline
+unsigned long long atomicAdd(
+ unsigned long long* address, unsigned long long val)
+{
+ return __atomic_fetch_add(address, val, __ATOMIC_RELAXED);
+}
+__device__
+inline
+float atomicAdd(float* address, float val)
+{
+#if defined(__AMDGCN_UNSAFE_FP_ATOMICS__)
+ return unsafeAtomicAdd(address, val);
+#else
+ return __atomic_fetch_add(address, val, __ATOMIC_RELAXED);
+#endif
+}
+
+#if !defined(__HIPCC_RTC__)
+DEPRECATED("use atomicAdd instead")
+#endif // !defined(__HIPCC_RTC__)
+__device__
+inline
+void atomicAddNoRet(float* address, float val)
+{
+ __ockl_atomic_add_noret_f32(address, val);
+}
+
+__device__
+inline
+double atomicAdd(double* address, double val)
+{
+#if defined(__AMDGCN_UNSAFE_FP_ATOMICS__)
+ return unsafeAtomicAdd(address, val);
+#else
+ return __atomic_fetch_add(address, val, __ATOMIC_RELAXED);
+#endif
+}
+
+__device__
+inline
+int atomicSub(int* address, int val)
+{
+ return __atomic_fetch_sub(address, val, __ATOMIC_RELAXED);
+}
+__device__
+inline
+unsigned int atomicSub(unsigned int* address, unsigned int val)
+{
+ return __atomic_fetch_sub(address, val, __ATOMIC_RELAXED);
+}
+
+__device__
+inline
+int atomicExch(int* address, int val)
+{
+ return __atomic_exchange_n(address, val, __ATOMIC_RELAXED);
+}
+__device__
+inline
+unsigned int atomicExch(unsigned int* address, unsigned int val)
+{
+ return __atomic_exchange_n(address, val, __ATOMIC_RELAXED);
+}
+__device__
+inline
+unsigned long long atomicExch(unsigned long long* address, unsigned long long val)
+{
+ return __atomic_exchange_n(address, val, __ATOMIC_RELAXED);
+}
+__device__
+inline
+float atomicExch(float* address, float val)
+{
+ return __uint_as_float(__atomic_exchange_n(
+ reinterpret_cast(address),
+ __float_as_uint(val),
+ __ATOMIC_RELAXED));
+}
+
+__device__
+inline
+int atomicMin(int* address, int val)
+{
+ return __atomic_fetch_min(address, val, __ATOMIC_RELAXED);
+}
+__device__
+inline
+unsigned int atomicMin(unsigned int* address, unsigned int val)
+{
+ return __atomic_fetch_min(address, val, __ATOMIC_RELAXED);
+}
+__device__
+inline
+unsigned long long atomicMin(
+ unsigned long long* address, unsigned long long val)
+{
+ unsigned long long tmp{__atomic_load_n(address, __ATOMIC_RELAXED)};
+ while (val < tmp) {
+ const auto tmp1 = __atomic_load_n(address, __ATOMIC_RELAXED);
+
+ if (tmp1 != tmp) { tmp = tmp1; continue; }
+
+ tmp = atomicCAS(address, tmp, val);
+ }
+
+ return tmp;
+}
+__device__ inline long long atomicMin(long long* address, long long val) {
+ long long tmp{__atomic_load_n(address, __ATOMIC_RELAXED)};
+ while (val < tmp) {
+ const auto tmp1 = __atomic_load_n(address, __ATOMIC_RELAXED);
+
+ if (tmp1 != tmp) {
+ tmp = tmp1;
+ continue;
+ }
+
+ tmp = atomicCAS(address, tmp, val);
+ }
+ return tmp;
+}
+
+__device__
+inline
+int atomicMax(int* address, int val)
+{
+ return __atomic_fetch_max(address, val, __ATOMIC_RELAXED);
+}
+__device__
+inline
+unsigned int atomicMax(unsigned int* address, unsigned int val)
+{
+ return __atomic_fetch_max(address, val, __ATOMIC_RELAXED);
+}
+__device__
+inline
+unsigned long long atomicMax(
+ unsigned long long* address, unsigned long long val)
+{
+ unsigned long long tmp{__atomic_load_n(address, __ATOMIC_RELAXED)};
+ while (tmp < val) {
+ const auto tmp1 = __atomic_load_n(address, __ATOMIC_RELAXED);
+
+ if (tmp1 != tmp) { tmp = tmp1; continue; }
+
+ tmp = atomicCAS(address, tmp, val);
+ }
+
+ return tmp;
+}
+__device__ inline long long atomicMax(long long* address, long long val) {
+ long long tmp{__atomic_load_n(address, __ATOMIC_RELAXED)};
+ while (tmp < val) {
+ const auto tmp1 = __atomic_load_n(address, __ATOMIC_RELAXED);
+
+ if (tmp1 != tmp) {
+ tmp = tmp1;
+ continue;
+ }
+
+ tmp = atomicCAS(address, tmp, val);
+ }
+ return tmp;
+}
+
+__device__
+inline
+unsigned int atomicInc(unsigned int* address, unsigned int val)
+{
+ return __builtin_amdgcn_atomic_inc32(address, val, __ATOMIC_RELAXED, "agent");
+}
+
+__device__
+inline
+unsigned int atomicDec(unsigned int* address, unsigned int val)
+{
+ return __builtin_amdgcn_atomic_dec32(address, val, __ATOMIC_RELAXED, "agent");
+}
+
+__device__
+inline
+int atomicAnd(int* address, int val)
+{
+ return __atomic_fetch_and(address, val, __ATOMIC_RELAXED);
+}
+__device__
+inline
+unsigned int atomicAnd(unsigned int* address, unsigned int val)
+{
+ return __atomic_fetch_and(address, val, __ATOMIC_RELAXED);
+}
+__device__
+inline
+unsigned long long atomicAnd(
+ unsigned long long* address, unsigned long long val)
+{
+ return __atomic_fetch_and(address, val, __ATOMIC_RELAXED);
+}
+
+__device__
+inline
+int atomicOr(int* address, int val)
+{
+ return __atomic_fetch_or(address, val, __ATOMIC_RELAXED);
+}
+__device__
+inline
+unsigned int atomicOr(unsigned int* address, unsigned int val)
+{
+ return __atomic_fetch_or(address, val, __ATOMIC_RELAXED);
+}
+__device__
+inline
+unsigned long long atomicOr(
+ unsigned long long* address, unsigned long long val)
+{
+ return __atomic_fetch_or(address, val, __ATOMIC_RELAXED);
+}
+
+__device__
+inline
+int atomicXor(int* address, int val)
+{
+ return __atomic_fetch_xor(address, val, __ATOMIC_RELAXED);
+}
+__device__
+inline
+unsigned int atomicXor(unsigned int* address, unsigned int val)
+{
+ return __atomic_fetch_xor(address, val, __ATOMIC_RELAXED);
+}
+__device__
+inline
+unsigned long long atomicXor(
+ unsigned long long* address, unsigned long long val)
+{
+ return __atomic_fetch_xor(address, val, __ATOMIC_RELAXED);
+}
+
+#endif // __hip_atomic_compare_exchange_strong
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_bf16.h b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_bf16.h
new file mode 100644
index 0000000000000000000000000000000000000000..cfaa5412a3aa77078313e4b5dcff980c2acc5639
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_bf16.h
@@ -0,0 +1,1814 @@
+/**
+ * MIT License
+ *
+ * Copyright (c) 2019 - 2024 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.
+ */
+
+/**
+ * \file
+ * \brief hip_bf16.h provides struct for __hip_bfloat16 types
+ */
+
+/**
+ * \defgroup HIP_INTRINSIC_BFLOAT16 bfloat16 Precision Intrinsics
+ * This section describes hip_bfloat16 precision intrinsic functions.
+ * To use these functions, include the header file \p hip_bf16.h in your program.
+ */
+
+/**
+ * \defgroup HIP_INTRINSIC_BFLOAT16_ARITH Bfloat16 Arithmetic Functions
+ * \ingroup HIP_INTRINSIC_BFLOAT16
+ * To use these functions, include the header file \p hip_bf16.h in your program.
+ */
+
+/**
+ * \defgroup HIP_INTRINSIC_BFLOAT16_COMP Bfloat16 Comparision Functions
+ * \ingroup HIP_INTRINSIC_BFLOAT16
+ * To use these functions, include the header file \p hip_bf16.h in your program.
+ */
+
+/**
+ * \defgroup HIP_INTRINSIC_BFLOAT162_COMP Bfloat162 Comparision Functions
+ * \ingroup HIP_INTRINSIC_BFLOAT16
+ * To use these functions, include the header file \p hip_bf16.h in your program.
+ */
+
+/**
+ * \defgroup HIP_INTRINSIC_BFLOAT162_ARITH Bfloat162 Arithmetic Functions
+ * \ingroup HIP_INTRINSIC_BFLOAT16
+ * To use these functions, include the header file \p hip_bf16.h in your program.
+ */
+
+/**
+ * \defgroup HIP_INTRINSIC_BFLOAT16_CONV Bfloat16 Conversion Functions
+ * \ingroup HIP_INTRINSIC_BFLOAT16
+ * To use these functions, include the header file \p hip_bf16.h in your program.
+ */
+
+/**
+ * \defgroup HIP_INTRINSIC_BFLOAT162_CONV Bfloat162 Conversion Functions
+ * \ingroup HIP_INTRINSIC_BFLOAT16
+ * To use these functions, include the header file \p hip_bf16.h in your program.
+ */
+
+/**
+ * \defgroup HIP_INTRINSIC_BFLOAT16_MATH Bfloat16 Math Functions
+ * \ingroup HIP_INTRINSIC_BFLOAT16
+ * To use these functions, include the header file \p hip_bf16.h in your program.
+ */
+
+/**
+ * \defgroup HIP_INTRINSIC_BFLOAT162_MATH Bfloat162 Math Functions
+ * \ingroup HIP_INTRINSIC_BFLOAT16
+ * To use these functions, include the header file \p hip_bf16.h in your program.
+ */
+
+/**
+ * \defgroup HIP_INTRINSIC_BFLOAT16_RAW Bfloat16 Raw Struct
+ * \ingroup HIP_INTRINSIC_BFLOAT16
+ * To use these functions, include the header file \p hip_bf16.h in your program.
+ */
+
+/**
+ * \defgroup HIP_INTRINSIC_BFLOAT162_RAW Bfloat162 Raw Struct
+ * \ingroup HIP_INTRINSIC_BFLOAT16
+ * To use these functions, include the header file \p hip_bf16.h in your program.
+ */
+
+#ifndef _HIP_INCLUDE_HIP_AMD_DETAIL_HIP_BF16_H_
+#define _HIP_INCLUDE_HIP_AMD_DETAIL_HIP_BF16_H_
+
+#if !defined(__HIPCC_RTC__)
+#include
+#endif // !defined(__HIPCC_RTC__)
+
+#include "amd_hip_vector_types.h" // float2 etc
+#include "device_library_decls.h" // ocml conversion functions
+#include "math_fwd.h" // ocml device functions
+
+#define __BF16_DEVICE__ __device__
+#if defined(__HIPCC_RTC__)
+#define __BF16_HOST_DEVICE__ __BF16_DEVICE__
+#else
+#include
+#include
+#include
+#define __BF16_HOST_DEVICE__ __host__ __BF16_DEVICE__
+#endif
+#define __BF16_DEVICE_STATIC__ __BF16_DEVICE__ static inline
+#define __BF16_HOST_DEVICE_STATIC__ __BF16_HOST_DEVICE__ static inline
+
+#if defined(__AVX512VL__) and defined(__AVX512BF16__) and not defined(__HIP_DEVICE_COMPILE__)
+// Enable with -mavx512vl -mavx512bf16
+#if defined(__MINGW64__)
+#include
+#else
+#include
+#endif
+#define HIP_BF16_AVX512_OP 1
+static_assert(sizeof(__bf16) == sizeof(unsigned short),
+ "sizeof __bf16 should match sizeof unsigned short");
+#else
+#define HIP_BF16_AVX512_OP 0
+#endif
+
+#define HIPRT_ONE_BF16 __float2bfloat16(1.0f)
+#define HIPRT_ZERO_BF16 __float2bfloat16(0.0f)
+#define HIPRT_INF_BF16 __ushort_as_bfloat16((unsigned short)0x7F80U)
+#define HIPRT_MAX_NORMAL_BF16 __ushort_as_bfloat16((unsigned short)0x7F7FU)
+#define HIPRT_MIN_DENORM_BF16 __ushort_as_bfloat16((unsigned short)0x0001U)
+#define HIPRT_NAN_BF16 __ushort_as_bfloat16((unsigned short)0x7FFFU)
+#define HIPRT_NEG_ZERO_BF16 __ushort_as_bfloat16((unsigned short)0x8000U)
+
+// Since we are using unsigned short to represent data in bfloat16, it can be of different sizes on
+// different machines. These naive checks should prevent some undefined behavior on systems which
+// have different sizes for basic types.
+#if !defined(__HIPCC_RTC__)
+static_assert(CHAR_BIT == 8, "byte size should be of 8 bits");
+#endif
+static_assert(sizeof(unsigned short) == 2, "size of unsigned short should be 2 bytes");
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_RAW
+ * \brief represents raw bfloat16 type
+ */
+typedef struct __attribute__((aligned(2))) {
+ unsigned short x;
+} __hip_bfloat16_raw;
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_RAW
+ * \brief represents raw bfloat16x2 vector type
+ */
+typedef struct __attribute__((aligned(4))) {
+ unsigned short x;
+ unsigned short y;
+} __hip_bfloat162_raw;
+
+/**
+ * \defgroup HIP_INTRINSIC_BFLOAT16_STRUCT
+ * \ingroup HIP_INTRINSIC_BFLOAT16
+ * \brief Struct to represent a 16 bit brain floating point number.
+ * @{
+ */
+struct __attribute__((aligned(2))) __hip_bfloat16 {
+ private:
+ __BF16_HOST_DEVICE_STATIC__ float bfloatraw_2_float(unsigned short val) {
+#if HIP_BF16_AVX512_OP
+ union {
+ unsigned short us;
+ __bf16 bf16;
+ } u = {val};
+ return _mm_cvtsbh_ss(u.bf16);
+#else
+ unsigned int uval = val << 16;
+ union {
+ unsigned int u32;
+ float fp32;
+ } u = {uval};
+ return u.fp32;
+#endif
+ }
+ __BF16_HOST_DEVICE_STATIC__ unsigned short float_2_bfloatraw(float f) {
+#if HIP_BF16_AVX512_OP
+ union {
+ __bf16 bf16;
+ unsigned short us;
+ } u = {_mm_cvtness_sbh(f)};
+ return u.us;
+#else
+ union {
+ float fp32;
+ unsigned int u32;
+ } u = {f};
+ if (~u.u32 & 0x7f800000) {
+ // When the exponent bits are not all 1s, then the value is zero, normal,
+ // or subnormal. We round the bfloat16 mantissa up by adding 0x7FFF, plus
+ // 1 if the least significant bit of the bfloat16 mantissa is 1 (odd).
+ // This causes the bfloat16's mantissa to be incremented by 1 if the 16
+ // least significant bits of the float mantissa are greater than 0x8000,
+ // or if they are equal to 0x8000 and the least significant bit of the
+ // bfloat16 mantissa is 1 (odd). This causes it to be rounded to even when
+ // the lower 16 bits are exactly 0x8000. If the bfloat16 mantissa already
+ // has the value 0x7f, then incrementing it causes it to become 0x00 and
+ // the exponent is incremented by one, which is the next higher FP value
+ // to the unrounded bfloat16 value. When the bfloat16 value is subnormal
+ // with an exponent of 0x00 and a mantissa of 0x7F, it may be rounded up
+ // to a normal value with an exponent of 0x01 and a mantissa of 0x00.
+ // When the bfloat16 value has an exponent of 0xFE and a mantissa of 0x7F,
+ // incrementing it causes it to become an exponent of 0xFF and a mantissa
+ // of 0x00, which is Inf, the next higher value to the unrounded value.
+ u.u32 += 0x7fff + ((u.u32 >> 16) & 1); // Round to nearest, round to even
+ } else if (u.u32 & 0xffff) {
+ // When all of the exponent bits are 1, the value is Inf or NaN.
+ // Inf is indicated by a zero mantissa. NaN is indicated by any nonzero
+ // mantissa bit. Quiet NaN is indicated by the most significant mantissa
+ // bit being 1. Signaling NaN is indicated by the most significant
+ // mantissa bit being 0 but some other bit(s) being 1. If any of the
+ // lower 16 bits of the mantissa are 1, we set the least significant bit
+ // of the bfloat16 mantissa, in order to preserve signaling NaN in case
+ // the bloat16's mantissa bits are all 0.
+ u.u32 |= 0x10000; // Preserve signaling NaN
+ }
+ return static_cast(u.u32 >> 16);
+#endif
+ }
+
+ __BF16_HOST_DEVICE_STATIC__ unsigned short double_2_bfloatraw(double d_in) {
+ union {
+ float fp32;
+ unsigned int u32;
+ } u = {static_cast(d_in)};
+ double d = u.fp32;
+
+ // Round to odd
+ if ((d_in > 0.0 && d > d_in) || (d_in < 0.0 && d < d_in)) {
+ u.u32--;
+ u.u32 |= 1;
+ }
+
+ return float_2_bfloatraw(u.fp32);
+ }
+
+ protected:
+ /*! \brief raw representation of bfloat16 */
+ unsigned short __x;
+
+ public:
+ // TODO: SWDEV-452411
+ // Need to add constructor of __hip_bfloat16 from
+ // unsigned long long
+ // long long
+ // long
+ // unsigned long
+ // Casting directly to double might lead to double rounding.
+
+ /*! \brief create __hip_bfloat16 from an unsigned int */
+ __BF16_HOST_DEVICE__ __hip_bfloat16(unsigned int val)
+ : __x(double_2_bfloatraw(static_cast(val))) {}
+
+ /*! \brief create __hip_bfloat16 from a int */
+ __BF16_HOST_DEVICE__ __hip_bfloat16(int val)
+ : __x(double_2_bfloatraw(static_cast(val))) {}
+
+ /*! \brief create __hip_bfloat16 from an unsigned short */
+ __BF16_HOST_DEVICE__ __hip_bfloat16(unsigned short val)
+ : __x(float_2_bfloatraw(static_cast(val))) {}
+
+ /*! \brief create __hip_bfloat16 from a short */
+ __BF16_HOST_DEVICE__ __hip_bfloat16(short val)
+ : __x(float_2_bfloatraw(static_cast(val))) {}
+
+ /*! \brief create __hip_bfloat16 from a double */
+ __BF16_HOST_DEVICE__ __hip_bfloat16(const double val) : __x(double_2_bfloatraw(val)) {}
+
+ /*! \brief create __hip_bfloat16 from a float */
+ __BF16_HOST_DEVICE__ __hip_bfloat16(const float val) : __x(float_2_bfloatraw(val)) {}
+
+ /*! \brief create __hip_bfloat16 from a __hip_bfloat16_raw */
+ __BF16_HOST_DEVICE__ __hip_bfloat16(const __hip_bfloat16_raw& val) : __x(val.x) {}
+
+ /*! \brief default constructor */
+ __BF16_HOST_DEVICE__ __hip_bfloat16() = default;
+
+ /*! \brief return a __hip_bfloat16_raw */
+ __BF16_HOST_DEVICE__ operator __hip_bfloat16_raw() const { return __hip_bfloat16_raw{__x}; }
+
+ /*! \brief return a __hip_bfloat16_raw cv qualifier */
+ __BF16_HOST_DEVICE__ operator __hip_bfloat16_raw() const volatile {
+ return __hip_bfloat16_raw{__x};
+ }
+
+ /*! \brief return false if bfloat value is +0.0 or -0.0, returns true otherwise */
+ __BF16_HOST_DEVICE__ operator bool() const {
+ auto val = bfloatraw_2_float(__x);
+ return val != 0.0f && val != -0.0f;
+ }
+
+ /*! \brief return a casted char from underlying float val */
+ __BF16_HOST_DEVICE__ operator char() const { return static_cast(bfloatraw_2_float(__x)); }
+
+ /*! \brief return a float */
+ __BF16_HOST_DEVICE__ operator float() const { return bfloatraw_2_float(__x); }
+
+ /*! \brief return a casted int casted from float of underlying bfloat16 value */
+ __BF16_HOST_DEVICE__ operator int() const { return static_cast(bfloatraw_2_float(__x)); }
+
+ /*! \brief return a casted long casted from float of underlying bfloat16 value */
+ __BF16_HOST_DEVICE__ operator long() const { return static_cast(bfloatraw_2_float(__x)); }
+
+ /*! \brief return a casted long long casted from float of underlying bfloat16 value */
+ __BF16_HOST_DEVICE__ operator long long() const {
+ return static_cast(bfloatraw_2_float(__x));
+ }
+
+ /*! \brief return a casted short casted from float of underlying bfloat16 value */
+ __BF16_HOST_DEVICE__ operator short() const { return static_cast(bfloatraw_2_float(__x)); }
+
+ /*! \brief return a casted signed char from float of underlying bfloat16 value */
+ __BF16_HOST_DEVICE__ operator signed char() const {
+ return static_cast(bfloatraw_2_float(__x));
+ }
+
+ /*! \brief return a casted unsigned char casted from float of underlying bfloat16 value */
+ __BF16_HOST_DEVICE__ operator unsigned char() const {
+ return static_cast(bfloatraw_2_float(__x));
+ }
+
+ /*! \brief return a casted unsigned int casted from float of underlying bfloat16 value */
+ __BF16_HOST_DEVICE__ operator unsigned int() const {
+ return static_cast(bfloatraw_2_float(__x));
+ }
+
+ /*! \brief return a casted unsigned from float of underlying bfloat16 value */
+ __BF16_HOST_DEVICE__ operator unsigned long() const {
+ return static_cast(bfloatraw_2_float(__x));
+ }
+
+ /*! \brief return a casted unsigned long long from float of underlying bfloat16 value */
+ __BF16_HOST_DEVICE__ operator unsigned long long() const {
+ return static_cast(bfloatraw_2_float(__x));
+ }
+
+ /*! \brief return a casted unsigned short from float of underlying bfloat16 value */
+ __BF16_HOST_DEVICE__ operator unsigned short() const {
+ return static_cast(bfloatraw_2_float(__x));
+ }
+
+ // TODO: SWDEV-452411 add operator which converts unsigned long long and long long to bfloat
+
+ /*! \brief assign value from an unsigned int */
+ __BF16_HOST_DEVICE__ __hip_bfloat16& operator=(unsigned int val) {
+ __x = float_2_bfloatraw(static_cast(val));
+ return *this;
+ }
+
+ /*! \brief assign value from a int */
+ __BF16_HOST_DEVICE__ __hip_bfloat16& operator=(int val) {
+ __x = float_2_bfloatraw(static_cast(val));
+ return *this;
+ }
+
+ /*! \brief assign value from an unsigned short */
+ __BF16_HOST_DEVICE__ __hip_bfloat16& operator=(unsigned short val) {
+ __x = float_2_bfloatraw(static_cast(val));
+ return *this;
+ }
+
+ /*! \brief assign value from a short int */
+ __BF16_HOST_DEVICE__ __hip_bfloat16& operator=(short val) {
+ __x = float_2_bfloatraw(static_cast(val));
+ return *this;
+ }
+
+ /*! \brief assign value from a double */
+ __BF16_HOST_DEVICE__ __hip_bfloat16& operator=(const double f) {
+ __x = float_2_bfloatraw(static_cast(f));
+ return *this;
+ }
+
+ /*! \brief assign value from a float */
+ __BF16_HOST_DEVICE__ __hip_bfloat16& operator=(const float f) {
+ __x = float_2_bfloatraw(f);
+ return *this;
+ }
+
+ /*! \brief assign value from a __hip_bfloat16_raw */
+ __BF16_HOST_DEVICE__ __hip_bfloat16& operator=(const __hip_bfloat16_raw& hr) {
+ __x = hr.x;
+ return *this;
+ }
+
+ /*! \brief assign value from a __hip_bfloat16_raw volatile */
+ __BF16_HOST_DEVICE__ volatile __hip_bfloat16& operator=(const __hip_bfloat16_raw& hr) volatile {
+ __x = hr.x;
+ return *this;
+ }
+
+ /*! \brief assign value from a __hip_bfloat16_raw cv qualifier */
+ __BF16_HOST_DEVICE__ volatile __hip_bfloat16& operator=(
+ const volatile __hip_bfloat16_raw& hr) volatile {
+ __x = hr.x;
+ return *this;
+ }
+};
+/**@}*/
+
+/**
+ * \defgroup HIP_INTRINSIC_BFLOAT162_STRUCT
+ * \ingroup HIP_INTRINSIC_BFLOAT16
+ * \brief Struct to represent a two 16 bit brain floating point number.
+ * @{
+ */
+struct __attribute__((aligned(4))) __hip_bfloat162 {
+ public:
+ __hip_bfloat16 x; /*! \brief raw representation of bfloat16 */
+ __hip_bfloat16 y; /*! \brief raw representation of bfloat16 */
+
+
+ public:
+ /*! \brief create __hip_bfloat162 from __hip_bfloat162_raw */
+ __BF16_HOST_DEVICE__ __hip_bfloat162(const __hip_bfloat162_raw& h2r)
+ : x(__hip_bfloat16(__hip_bfloat16_raw{h2r.x})),
+ y(__hip_bfloat16(__hip_bfloat16_raw{h2r.y})) {}
+
+ /*! \brief copy constructor of __hip_bfloat162 */
+ __BF16_HOST_DEVICE__ __hip_bfloat162(const __hip_bfloat162& val) {
+ __hip_bfloat162_raw hr = val;
+ x = __hip_bfloat16_raw{hr.x};
+ y = __hip_bfloat16_raw{hr.y};
+ }
+
+ /*! \brief create __hip_bfloat162 from two __hip_bfloat16 */
+ __BF16_HOST_DEVICE__ __hip_bfloat162(const __hip_bfloat16& a, const __hip_bfloat16& b)
+ : x(a), y(b) {}
+
+ /*! \brief default constructor of __hip_bfloat162 */
+ __BF16_HOST_DEVICE__ __hip_bfloat162() = default;
+
+ /*! \brief return a __hip_bfloat162_raw */
+ __BF16_HOST_DEVICE__ operator __hip_bfloat162_raw() const {
+ __hip_bfloat16_raw l = x;
+ __hip_bfloat16_raw r = y;
+ return __hip_bfloat162_raw{l.x, r.x};
+ }
+
+ /*! \brief return a float2 */
+ __BF16_HOST_DEVICE__ operator float2() const {
+#if HIP_BF16_AVX512_OP
+ union {
+ __hip_bfloat162_raw raw2;
+ __bf16 bf162[2];
+ static_assert(sizeof(__bf16[2]) == sizeof(__hip_bfloat162_raw));
+ } u;
+ u.raw2 = *this;
+ __m128bh pbf16{u.bf162[0], u.bf162[1], 0, 0};
+ __m128 pf32 = _mm_cvtpbh_ps(pbf16);
+ float2 ret(pf32[0], pf32[1]);
+#else
+ float2 ret(x, y);
+#endif
+ return ret;
+ }
+
+ /*! \brief assign value from __hip_bfloat162_raw */
+ __BF16_HOST_DEVICE__ __hip_bfloat162& operator=(const __hip_bfloat162_raw& h2r) {
+ x = __hip_bfloat16(__hip_bfloat16_raw{h2r.x});
+ y = __hip_bfloat16(__hip_bfloat16_raw{h2r.y});
+ return *this;
+ }
+
+ /*! \brief assign value from __hip_bfloat162 */
+ __BF16_HOST_DEVICE__ __hip_bfloat162& operator=(const __hip_bfloat162& src) {
+ __hip_bfloat162_raw hr = src;
+ x = __hip_bfloat16(__hip_bfloat16_raw{hr.x});
+ y = __hip_bfloat16(__hip_bfloat16_raw{hr.y});
+ return *this;
+ }
+};
+/**@}*/
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_CONV
+ * \brief Converts bfloat16 to float
+ */
+__BF16_HOST_DEVICE_STATIC__ float __bfloat162float(__hip_bfloat16 a) {
+ float ret = a;
+ return ret;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_CONV
+ * \brief Converts float to bfloat16
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 __float2bfloat16(float f) {
+ __hip_bfloat16 ret{f};
+ return ret;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Converts and moves bfloat162 to float2
+ */
+__BF16_HOST_DEVICE_STATIC__ float2 __bfloat1622float2(const __hip_bfloat162 a) {
+ float2 ret = a;
+ return ret;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Moves bfloat16 value to bfloat162
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __bfloat162bfloat162(const __hip_bfloat16 a) {
+ return __hip_bfloat162(a, a);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Reinterprets bits in a __hip_bfloat16 as a signed short integer
+ */
+__BF16_HOST_DEVICE_STATIC__ short int __bfloat16_as_short(const __hip_bfloat16 h) {
+ short ret = h;
+ return ret;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Reinterprets bits in a __hip_bfloat16 as an unsigned signed short integer
+ */
+__BF16_HOST_DEVICE_STATIC__ unsigned short int __bfloat16_as_ushort(const __hip_bfloat16 h) {
+ unsigned short ret = h;
+ return ret;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Convert double to __hip_bfloat16
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 __double2bfloat16(const double a) {
+ __hip_bfloat16 ret{a};
+ return ret;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Convert float2 to __hip_bfloat162
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __float22bfloat162_rn(const float2 a) {
+ return __hip_bfloat162{__float2bfloat16(a.x), __float2bfloat16(a.y)};
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Combine two __hip_bfloat16 to __hip_bfloat162
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __halves2bfloat162(const __hip_bfloat16 a,
+ const __hip_bfloat16 b) {
+ return __hip_bfloat162(a, b);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Returns high 16 bits of __hip_bfloat162
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 __high2bfloat16(const __hip_bfloat162 a) {
+ __hip_bfloat162_raw hr = a;
+ return __hip_bfloat16(__hip_bfloat16_raw{hr.y});
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Returns high 16 bits of __hip_bfloat162
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __high2bfloat162(const __hip_bfloat162 a) {
+ __hip_bfloat162_raw hr = a;
+ return __hip_bfloat162(__hip_bfloat16_raw{hr.y}, __hip_bfloat16_raw{hr.y});
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Converts high 16 bits of __hip_bfloat162 to float and returns the result
+ */
+__BF16_HOST_DEVICE_STATIC__ float __high2float(const __hip_bfloat162 a) {
+ __hip_bfloat162_raw hr = a;
+ return __bfloat162float(__hip_bfloat16(__hip_bfloat16_raw{hr.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Extracts high 16 bits from each and combines them
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __highs2bfloat162(const __hip_bfloat162 a,
+ const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hip_bfloat162(__hip_bfloat162_raw{hr_a.y, hr_b.y});
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Returns low 16 bits of __hip_bfloat162
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 __low2bfloat16(const __hip_bfloat162 a) {
+ __hip_bfloat162_raw hr = a;
+ return __hip_bfloat16(hr.x);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Returns low 16 bits of __hip_bfloat162
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __low2bfloat162(const __hip_bfloat162 a) {
+ __hip_bfloat162_raw hr = a;
+ return __hip_bfloat162(hr.x, hr.x);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Converts low 16 bits of __hip_bfloat162 to float and returns the result
+ */
+__BF16_HOST_DEVICE_STATIC__ float __low2float(const __hip_bfloat162 a) {
+ __hip_bfloat162_raw hr = a;
+ return __bfloat162float(__hip_bfloat16(__hip_bfloat16_raw{hr.x}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Swaps both halves
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __lowhigh2highlow(const __hip_bfloat162 a) {
+ __hip_bfloat162_raw hr = a;
+ return __hip_bfloat162(__hip_bfloat162_raw{hr.y, hr.x});
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Extracts low 16 bits from each and combines them
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __lows2bfloat162(const __hip_bfloat162 a,
+ const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hip_bfloat162(__hip_bfloat162_raw{hr_a.x, hr_b.x});
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Reinterprets short int into a bfloat16
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 __short_as_bfloat16(const short int a) {
+ return __hip_bfloat16(a);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_CONV
+ * \brief Reinterprets unsigned short int into a bfloat16
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 __ushort_as_bfloat16(const unsigned short int a) {
+ return __hip_bfloat16(a);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Adds two bfloat16 values
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 __hadd(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+ return __float2bfloat16(__bfloat162float(a) + __bfloat162float(b));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Subtracts two bfloat16 values
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 __hsub(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+ return __float2bfloat16(__bfloat162float(a) - __bfloat162float(b));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Divides two bfloat16 values
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 __hdiv(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+ return __float2bfloat16(__bfloat162float(a) / __bfloat162float(b));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Performs FMA of given bfloat16 values
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat16 __hfma(const __hip_bfloat16 a, const __hip_bfloat16 b,
+ const __hip_bfloat16 c) {
+ return __float2bfloat16(
+ __ocml_fma_f32(__bfloat162float(a), __bfloat162float(b), __bfloat162float(c)));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Multiplies two bfloat16 values
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 __hmul(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+ return __float2bfloat16(__bfloat162float(a) * __bfloat162float(b));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Negate a bfloat16 value
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 __hneg(const __hip_bfloat16 a) {
+ __hip_bfloat16_raw hr = a;
+ hr.x ^= 0x8000;
+ return __hip_bfloat16(hr);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Returns absolute of a bfloat16
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 __habs(const __hip_bfloat16 a) {
+ __hip_bfloat16_raw hr = a;
+ hr.x &= 0x7FFF;
+ return __hip_bfloat16(hr);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Divides bfloat162 values
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __h2div(const __hip_bfloat162 a,
+ const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hip_bfloat162(__float2bfloat16(__bfloat162float(__hip_bfloat16_raw{hr_a.x}) /
+ __bfloat162float(__hip_bfloat16_raw{hr_b.x})),
+ __float2bfloat16(__bfloat162float(__hip_bfloat16_raw{hr_a.y}) /
+ __bfloat162float(__hip_bfloat16_raw{hr_b.y})));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Returns absolute of a bfloat162
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __habs2(const __hip_bfloat162 a) {
+ __hip_bfloat162_raw hr_a = a;
+ return __hip_bfloat162(__habs(__hip_bfloat16_raw{hr_a.x}), __habs(__hip_bfloat16_raw{hr_a.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Adds two bfloat162 values
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __hadd2(const __hip_bfloat162 a,
+ const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hip_bfloat162(__hadd(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}),
+ __hadd(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Performs FMA of given bfloat162 values
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat162 __hfma2(const __hip_bfloat162 a, const __hip_bfloat162 b,
+ const __hip_bfloat162 c) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ __hip_bfloat162_raw hr_c = c;
+ return __hip_bfloat162(
+ __hfma(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}, __hip_bfloat16_raw{hr_c.x}),
+ __hfma(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y}, __hip_bfloat16_raw{hr_c.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Multiplies two bfloat162 values
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __hmul2(const __hip_bfloat162 a,
+ const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hip_bfloat162(__hmul(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}),
+ __hmul(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Converts a bfloat162 into negative
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __hneg2(const __hip_bfloat162 a) {
+ __hip_bfloat162_raw hr_a = a;
+ return __hip_bfloat162(__hneg(__hip_bfloat16_raw{hr_a.x}), __hneg(__hip_bfloat16_raw{hr_a.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Subtracts two bfloat162 values
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __hsub2(const __hip_bfloat162 a,
+ const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hip_bfloat162(__hsub(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}),
+ __hsub(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Operator to multiply two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 operator*(const __hip_bfloat16& l,
+ const __hip_bfloat16& r) {
+ return __hmul(l, r);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Operator to multiply-assign two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16& operator*=(__hip_bfloat16& l, const __hip_bfloat16& r) {
+ l = __hmul(l, r);
+ return l;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Operator to unary+ on a __hip_bfloat16 number
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 operator+(const __hip_bfloat16& l) { return l; }
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Operator to add two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 operator+(const __hip_bfloat16& l,
+ const __hip_bfloat16& r) {
+ return __hadd(l, r);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Operator to negate a __hip_bfloat16 number
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 operator-(const __hip_bfloat16& l) { return __hneg(l); }
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Operator to subtract two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 operator-(const __hip_bfloat16& l,
+ const __hip_bfloat16& r) {
+ return __hsub(l, r);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Operator to post increment a __hip_bfloat16 number
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 operator++(__hip_bfloat16& l, const int) {
+ auto ret = l;
+ l = __hadd(l, HIPRT_ONE_BF16);
+ return ret;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Operator to pre increment a __hip_bfloat16 number
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16& operator++(__hip_bfloat16& l) {
+ l = __hadd(l, HIPRT_ONE_BF16);
+ return l;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Operator to post decrement a __hip_bfloat16 number
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 operator--(__hip_bfloat16& l, const int) {
+ auto ret = l;
+ l = __hsub(l, HIPRT_ONE_BF16);
+ return ret;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Operator to pre decrement a __hip_bfloat16 number
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16& operator--(__hip_bfloat16& l) {
+ l = __hsub(l, HIPRT_ONE_BF16);
+ return l;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Operator to add-assign two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16& operator+=(__hip_bfloat16& l, const __hip_bfloat16& r) {
+ l = __hadd(l, r);
+ return l;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Operator to subtract-assign two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16& operator-=(__hip_bfloat16& l, const __hip_bfloat16& r) {
+ l = __hsub(l, r);
+ return l;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Operator to divide two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 operator/(const __hip_bfloat16& l,
+ const __hip_bfloat16& r) {
+ return __hdiv(l, r);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_ARITH
+ * \brief Operator to divide-assign two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16& operator/=(__hip_bfloat16& l, const __hip_bfloat16& r) {
+ l = __hdiv(l, r);
+ return l;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Operator to multiply two __hip_bfloat162 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 operator*(const __hip_bfloat162& l,
+ const __hip_bfloat162& r) {
+ return __hmul2(l, r);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Operator to multiply-assign two __hip_bfloat162 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162& operator*=(__hip_bfloat162& l,
+ const __hip_bfloat162& r) {
+ l = __hmul2(l, r);
+ return l;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Operator to unary+ on a __hip_bfloat162 number
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 operator+(const __hip_bfloat162& l) { return l; }
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Operator to add two __hip_bfloat162 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 operator+(const __hip_bfloat162& l,
+ const __hip_bfloat162& r) {
+ return __hadd2(l, r);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Operator to negate a __hip_bfloat162 number
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 operator-(const __hip_bfloat162& l) {
+ return __hneg2(l);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Operator to subtract two __hip_bfloat162 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 operator-(const __hip_bfloat162& l,
+ const __hip_bfloat162& r) {
+ return __hsub2(l, r);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Operator to post increment a __hip_bfloat162 number
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 operator++(__hip_bfloat162& l, const int) {
+ auto ret = l;
+ l = __hadd2(l, {HIPRT_ONE_BF16, HIPRT_ONE_BF16});
+ return ret;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Operator to pre increment a __hip_bfloat162 number
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162& operator++(__hip_bfloat162& l) {
+ l = __hadd2(l, {HIPRT_ONE_BF16, HIPRT_ONE_BF16});
+ return l;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Operator to post decrement a __hip_bfloat162 number
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 operator--(__hip_bfloat162& l, const int) {
+ auto ret = l;
+ l = __hsub2(l, {HIPRT_ONE_BF16, HIPRT_ONE_BF16});
+ return ret;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Operator to pre decrement a __hip_bfloat162 number
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162& operator--(__hip_bfloat162& l) {
+ l = __hsub2(l, {HIPRT_ONE_BF16, HIPRT_ONE_BF16});
+ return l;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Operator to add-assign two __hip_bfloat162 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162& operator+=(__hip_bfloat162& l,
+ const __hip_bfloat162& r) {
+ l = __hadd2(l, r);
+ return l;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Operator to subtract-assign two __hip_bfloat162 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162& operator-=(__hip_bfloat162& l,
+ const __hip_bfloat162& r) {
+ l = __hsub2(l, r);
+ return l;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Operator to divide two __hip_bfloat162 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 operator/(const __hip_bfloat162& l,
+ const __hip_bfloat162& r) {
+ return __h2div(l, r);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_ARITH
+ * \brief Operator to divide-assign two __hip_bfloat162 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162& operator/=(__hip_bfloat162& l,
+ const __hip_bfloat162& r) {
+ l = __h2div(l, r);
+ return l;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Compare two bfloat162 values
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __heq(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+ return __bfloat162float(a) == __bfloat162float(b);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Compare two bfloat162 values - unordered equal
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hequ(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+ return !(__bfloat162float(a) < __bfloat162float(b)) &&
+ !(__bfloat162float(a) > __bfloat162float(b));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Compare two bfloat162 values - greater than
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hgt(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+ return __bfloat162float(a) > __bfloat162float(b);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Compare two bfloat162 values - unordered greater than
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hgtu(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+ return !(__bfloat162float(a) <= __bfloat162float(b));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Compare two bfloat162 values - greater than equal
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hge(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+ return __bfloat162float(a) >= __bfloat162float(b);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Compare two bfloat162 values - unordered greater than equal
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hgeu(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+ return !(__bfloat162float(a) < __bfloat162float(b));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Compare two bfloat162 values - not equal
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hne(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+ return __bfloat162float(a) != __bfloat162float(b);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Compare two bfloat162 values - unordered not equal
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hneu(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+ return !(__bfloat162float(a) == __bfloat162float(b));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Compare two bfloat162 values - return max
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 __hmax(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+#if __HIP_DEVICE_COMPILE__
+ return __float2bfloat16(__ocml_fmax_f32(__bfloat162float(a), __bfloat162float(b)));
+#else
+ return __float2bfloat16(std::max(__bfloat162float(a), __bfloat162float(b)));
+#endif
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Compare two bfloat162 values - return min
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat16 __hmin(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+#if __HIP_DEVICE_COMPILE__
+ return __float2bfloat16(__ocml_fmin_f32(__bfloat162float(a), __bfloat162float(b)));
+#else
+ return __float2bfloat16(std::min(__bfloat162float(a), __bfloat162float(b)));
+#endif
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Compare two bfloat162 values - less than operator
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hlt(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+ return __bfloat162float(a) < __bfloat162float(b);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Compare two bfloat162 values - unordered less than
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hltu(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+ return !(__bfloat162float(a) >= __bfloat162float(b));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Compare two bfloat162 values - less than equal
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hle(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+ return __bfloat162float(a) <= __bfloat162float(b);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Compare two bfloat162 values - unordered less than equal
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hleu(const __hip_bfloat16 a, const __hip_bfloat16 b) {
+ return !(__bfloat162float(a) > __bfloat162float(b));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Checks if number is inf
+ */
+__BF16_HOST_DEVICE_STATIC__ int __hisinf(const __hip_bfloat16 a) {
+ __hip_bfloat16_raw hr = a;
+ return !(~hr.x & 0x7f80) && !(hr.x & 0x7f);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Checks if number is nan
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hisnan(const __hip_bfloat16 a) {
+ __hip_bfloat16_raw hr = a;
+ return !(~hr.x & 0x7f80) && +(hr.x & 0x7f);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Checks if two numbers are equal
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hbeq2(const __hip_bfloat162 a, const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __heq(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}) &&
+ __heq(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y});
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Checks if two numbers are equal - unordered
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hbequ2(const __hip_bfloat162 a, const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hequ(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}) &&
+ __hequ(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y});
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Check for a >= b
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hbge2(const __hip_bfloat162 a, const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hge(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}) &&
+ __hge(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y});
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Check for a >= b - unordered
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hbgeu2(const __hip_bfloat162 a, const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hgeu(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}) &&
+ __hgeu(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y});
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Check for a > b
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hbgt2(const __hip_bfloat162 a, const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hgt(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}) &&
+ __hgt(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y});
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Check for a > b - unordered
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hbgtu2(const __hip_bfloat162 a, const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hgtu(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}) &&
+ __hgtu(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y});
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Check for a <= b
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hble2(const __hip_bfloat162 a, const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hle(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}) &&
+ __hle(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y});
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Check for a <= b - unordered
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hbleu2(const __hip_bfloat162 a, const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hleu(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}) &&
+ __hleu(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y});
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Check for a < b
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hblt2(const __hip_bfloat162 a, const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hlt(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}) &&
+ __hlt(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y});
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Check for a < b - unordered
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hbltu2(const __hip_bfloat162 a, const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hltu(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}) &&
+ __hltu(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y});
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Check for a != b
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hbne2(const __hip_bfloat162 a, const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hne(__hip_bfloat16(__hip_bfloat16_raw{hr_a.x}),
+ __hip_bfloat16(__hip_bfloat16_raw{hr_b.x})) &&
+ __hne(__hip_bfloat16(__hip_bfloat16_raw{hr_a.y}), __hip_bfloat16(__hip_bfloat16_raw{hr_b.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Check for a != b
+ */
+__BF16_HOST_DEVICE_STATIC__ bool __hbneu2(const __hip_bfloat162 a, const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hneu(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}) ||
+ __hneu(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y});
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Check for a != b, returns 1.0 if equal, otherwise 0.0
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __heq2(const __hip_bfloat162 a,
+ const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hip_bfloat162{
+ {__heq(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}) ? HIPRT_ONE_BF16
+ : HIPRT_ZERO_BF16},
+ {__heq(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y}) ? HIPRT_ONE_BF16
+ : HIPRT_ZERO_BF16}};
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Check for a >= b, returns 1.0 if greater than equal, otherwise 0.0
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __hge2(const __hip_bfloat162 a,
+ const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hip_bfloat162{
+ {__hge(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}) ? HIPRT_ONE_BF16
+ : HIPRT_ZERO_BF16},
+ {__hge(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y}) ? HIPRT_ONE_BF16
+ : HIPRT_ZERO_BF16}};
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Check for a > b, returns 1.0 if greater than equal, otherwise 0.0
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __hgt2(const __hip_bfloat162 a,
+ const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hip_bfloat162{
+ {__hgt(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}) ? HIPRT_ONE_BF16
+ : HIPRT_ZERO_BF16},
+ {__hgt(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y}) ? HIPRT_ONE_BF16
+ : HIPRT_ONE_BF16}};
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Check for a is NaN, returns 1.0 if NaN, otherwise 0.0
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __hisnan2(const __hip_bfloat162 a) {
+ __hip_bfloat162_raw hr_a = a;
+ return __hip_bfloat162{{__hisnan(__hip_bfloat16_raw{hr_a.x}) ? HIPRT_ONE_BF16 : HIPRT_ZERO_BF16},
+ {__hisnan(__hip_bfloat16_raw{hr_a.y}) ? HIPRT_ONE_BF16 : HIPRT_ONE_BF16}};
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Check for a <= b, returns 1.0 if greater than equal, otherwise 0.0
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __hle2(const __hip_bfloat162 a,
+ const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hip_bfloat162{
+ {__hle(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}) ? HIPRT_ONE_BF16
+ : HIPRT_ZERO_BF16},
+ {__hle(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y}) ? HIPRT_ONE_BF16
+ : HIPRT_ZERO_BF16}};
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Check for a < b, returns 1.0 if greater than equal, otherwise 0.0
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __hlt2(const __hip_bfloat162 a,
+ const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hip_bfloat162{
+ {__hlt(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}) ? HIPRT_ONE_BF16
+ : HIPRT_ZERO_BF16},
+ {__hlt(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y}) ? HIPRT_ONE_BF16
+ : HIPRT_ZERO_BF16}};
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Returns max of two elements
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __hmax2(const __hip_bfloat162 a,
+ const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hip_bfloat162(__hmax(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}),
+ __hmax(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Returns min of two elements
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __hmin2(const __hip_bfloat162 a,
+ const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hip_bfloat162(__hmin(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}),
+ __hmin(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Checks for not equal to
+ */
+__BF16_HOST_DEVICE_STATIC__ __hip_bfloat162 __hne2(const __hip_bfloat162 a,
+ const __hip_bfloat162 b) {
+ __hip_bfloat162_raw hr_a = a;
+ __hip_bfloat162_raw hr_b = b;
+ return __hip_bfloat162{
+ {__hne(__hip_bfloat16_raw{hr_a.x}, __hip_bfloat16_raw{hr_b.x}) ? HIPRT_ONE_BF16
+ : HIPRT_ZERO_BF16},
+ {__hne(__hip_bfloat16_raw{hr_a.y}, __hip_bfloat16_raw{hr_b.y}) ? HIPRT_ONE_BF16
+ : HIPRT_ZERO_BF16}};
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Operator to perform an equal compare on two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ bool operator==(const __hip_bfloat16& l, const __hip_bfloat16& r) {
+ return __heq(l, r);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Operator to perform a not equal on two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ bool operator!=(const __hip_bfloat16& l, const __hip_bfloat16& r) {
+ return __hne(l, r);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Operator to perform a less than on two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ bool operator<(const __hip_bfloat16& l, const __hip_bfloat16& r) {
+ return __hlt(l, r);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Operator to perform a less than equal on two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ bool operator<=(const __hip_bfloat16& l, const __hip_bfloat16& r) {
+ return __hle(l, r);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Operator to perform a greater than on two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ bool operator>(const __hip_bfloat16& l, const __hip_bfloat16& r) {
+ return __hgt(l, r);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Operator to perform a greater than equal on two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ bool operator>=(const __hip_bfloat16& l, const __hip_bfloat16& r) {
+ return __hge(l, r);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Operator to perform an equal compare on two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ bool operator==(const __hip_bfloat162& l, const __hip_bfloat162& r) {
+ float2 ret = __heq2(l, r);
+ return ret.x != 0.0f && ret.y != 0.0f;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Operator to perform a not equal on two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ bool operator!=(const __hip_bfloat162& l, const __hip_bfloat162& r) {
+ return !(l == r);
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Operator to perform a less than on two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ bool operator<(const __hip_bfloat162& l, const __hip_bfloat162& r) {
+ float2 fl = l, fr = r;
+ return fl.x < fr.x && fl.x < fr.y;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Operator to perform a less than equal on two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ bool operator<=(const __hip_bfloat162& l, const __hip_bfloat162& r) {
+ float2 fl = l, fr = r;
+ return fl.x <= fr.x && fl.x <= fr.y;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_COMP
+ * \brief Operator to perform a greater than on two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ bool operator>(const __hip_bfloat162& l, const __hip_bfloat162& r) {
+ float2 fl = l, fr = r;
+ return fl.x > fr.x && fl.x > fr.y;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_COMP
+ * \brief Operator to perform a greater than equal on two __hip_bfloat16 numbers
+ */
+__BF16_HOST_DEVICE_STATIC__ bool operator>=(const __hip_bfloat162& l, const __hip_bfloat162& r) {
+ float2 fl = l, fr = r;
+ return fl.x >= fr.x && fl.x >= fr.y;
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_MATH
+ * \brief Calculate ceil of bfloat16
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat16 hceil(const __hip_bfloat16 h) {
+ return __float2bfloat16(__ocml_ceil_f32(__bfloat162float(h)));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_MATH
+ * \brief Calculate cosine of bfloat16
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat16 hcos(const __hip_bfloat16 h) {
+ return __float2bfloat16(__ocml_cos_f32(__bfloat162float(h)));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_MATH
+ * \brief Calculate exponential of bfloat16
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat16 hexp(const __hip_bfloat16 h) {
+ return __float2bfloat16(__ocml_exp_f32(__bfloat162float(h)));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_MATH
+ * \brief Calculate exponential 10 of bfloat16
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat16 hexp10(const __hip_bfloat16 h) {
+ return __float2bfloat16(__ocml_exp10_f32(__bfloat162float(h)));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_MATH
+ * \brief Calculate exponential 2 of bfloat16
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat16 hexp2(const __hip_bfloat16 h) {
+ return __float2bfloat16(__ocml_exp2_f32(__bfloat162float(h)));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_MATH
+ * \brief Calculate floor of bfloat16
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat16 hfloor(const __hip_bfloat16 h) {
+ return __float2bfloat16(__ocml_floor_f32(__bfloat162float(h)));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_MATH
+ * \brief Calculate natural log of bfloat16
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat16 hlog(const __hip_bfloat16 h) {
+ return __float2bfloat16(__ocml_log_f32(__bfloat162float(h)));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_MATH
+ * \brief Calculate log 10 of bfloat16
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat16 hlog10(const __hip_bfloat16 h) {
+ return __float2bfloat16(__ocml_log10_f32(__bfloat162float(h)));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_MATH
+ * \brief Calculate log 2 of bfloat16
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat16 hlog2(const __hip_bfloat16 h) {
+ return __float2bfloat16(__ocml_log2_f32(__bfloat162float(h)));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_MATH
+ * \brief Calculate reciprocal
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat16 hrcp(const __hip_bfloat16 h) {
+ return __float2bfloat16(1.0f / (__bfloat162float(h)));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_MATH
+ * \brief Round to nearest int
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat16 hrint(const __hip_bfloat16 h) {
+ return __float2bfloat16(__ocml_rint_f32(__bfloat162float(h)));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_MATH
+ * \brief Reciprocal square root
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat16 hrsqrt(const __hip_bfloat16 h) {
+ return __float2bfloat16(__ocml_rsqrt_f32(__bfloat162float(h)));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_MATH
+ * \brief Calculate sin of bfloat16
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat16 hsin(const __hip_bfloat16 h) {
+ return __float2bfloat16(__ocml_sin_f32(__bfloat162float(h)));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_MATH
+ * \brief Calculate sqrt of bfloat16
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat16 hsqrt(const __hip_bfloat16 h) {
+ return __float2bfloat16(__ocml_sqrt_f32(__bfloat162float(h)));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT16_MATH
+ * \brief Calculate truncate of bfloat16
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat16 htrunc(const __hip_bfloat16 h) {
+ return __float2bfloat16(__ocml_trunc_f32(__bfloat162float(h)));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_MATH
+ * \brief Calculate ceil of bfloat162
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat162 h2ceil(const __hip_bfloat162 h) {
+ __hip_bfloat162_raw hr = h;
+ return __hip_bfloat162(hceil(__hip_bfloat16_raw{hr.x}), hceil(__hip_bfloat16_raw{hr.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_MATH
+ * \brief Calculate cosine of bfloat162
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat162 h2cos(const __hip_bfloat162 h) {
+ __hip_bfloat162_raw hr = h;
+ return __hip_bfloat162(hcos(__hip_bfloat16_raw{hr.x}), hcos(__hip_bfloat16_raw{hr.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_MATH
+ * \brief Calculate exponential of bfloat162
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat162 h2exp(const __hip_bfloat162 h) {
+ __hip_bfloat162_raw hr = h;
+ return __hip_bfloat162(hexp(__hip_bfloat16_raw{hr.x}), hexp(__hip_bfloat16_raw{hr.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_MATH
+ * \brief Calculate exponential 10 of bfloat162
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat162 h2exp10(const __hip_bfloat162 h) {
+ __hip_bfloat162_raw hr = h;
+ return __hip_bfloat162(hexp10(__hip_bfloat16_raw{hr.x}), hexp10(__hip_bfloat16_raw{hr.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_MATH
+ * \brief Calculate exponential 2 of bfloat162
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat162 h2exp2(const __hip_bfloat162 h) {
+ __hip_bfloat162_raw hr = h;
+ return __hip_bfloat162(hexp2(__hip_bfloat16_raw{hr.x}), hexp2(__hip_bfloat16_raw{hr.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_MATH
+ * \brief Calculate floor of bfloat162
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat162 h2floor(const __hip_bfloat162 h) {
+ __hip_bfloat162_raw hr = h;
+ return __hip_bfloat162(hfloor(__hip_bfloat16_raw{hr.x}), hfloor(__hip_bfloat16_raw{hr.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_MATH
+ * \brief Calculate natural log of bfloat162
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat162 h2log(const __hip_bfloat162 h) {
+ __hip_bfloat162_raw hr = h;
+ return __hip_bfloat162(hlog(__hip_bfloat16_raw{hr.x}), hlog(__hip_bfloat16_raw{hr.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_MATH
+ * \brief Calculate log 10 of bfloat162
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat162 h2log10(const __hip_bfloat162 h) {
+ __hip_bfloat162_raw hr = h;
+ return __hip_bfloat162(hlog10(__hip_bfloat16_raw{hr.x}), hlog10(__hip_bfloat16_raw{hr.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_MATH
+ * \brief Calculate log 2 of bfloat162
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat162 h2log2(const __hip_bfloat162 h) {
+ __hip_bfloat162_raw hr = h;
+ return __hip_bfloat162(hlog2(__hip_bfloat16_raw{hr.x}), hlog2(__hip_bfloat16_raw{hr.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_MATH
+ * \brief Calculate vector reciprocal
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat162 h2rcp(const __hip_bfloat162 h) {
+ __hip_bfloat162_raw hr = h;
+ return __hip_bfloat162(hrcp(__hip_bfloat16_raw{hr.x}), hrcp(__hip_bfloat16_raw{hr.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_MATH
+ * \brief Calculate vector round to nearest int
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat162 h2rint(const __hip_bfloat162 h) {
+ __hip_bfloat162_raw hr = h;
+ return __hip_bfloat162(hrint(__hip_bfloat16_raw{hr.x}), hrint(__hip_bfloat16_raw{hr.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_MATH
+ * \brief Calculate vector reciprocal square root
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat162 h2rsqrt(const __hip_bfloat162 h) {
+ __hip_bfloat162_raw hr = h;
+ return __hip_bfloat162(hrsqrt(__hip_bfloat16_raw{hr.x}), hrsqrt(__hip_bfloat16_raw{hr.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_MATH
+ * \brief Calculate sin of bfloat162
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat162 h2sin(const __hip_bfloat162 h) {
+ __hip_bfloat162_raw hr = h;
+ return __hip_bfloat162(hsin(__hip_bfloat16_raw{hr.x}), hsin(__hip_bfloat16_raw{hr.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_MATH
+ * \brief Calculate sqrt of bfloat162
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat162 h2sqrt(const __hip_bfloat162 h) {
+ __hip_bfloat162_raw hr = h;
+ return __hip_bfloat162(hsqrt(__hip_bfloat16_raw{hr.x}), hsqrt(__hip_bfloat16_raw{hr.y}));
+}
+
+/**
+ * \ingroup HIP_INTRINSIC_BFLOAT162_MATH
+ * \brief Calculate truncate of bfloat162
+ */
+__BF16_DEVICE_STATIC__ __hip_bfloat162 h2trunc(const __hip_bfloat162 h) {
+ __hip_bfloat162_raw hr = h;
+ return __hip_bfloat162(htrunc(__hip_bfloat16_raw{hr.x}), htrunc(__hip_bfloat16_raw{hr.y}));
+}
+#endif
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_bfloat16.h b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_bfloat16.h
new file mode 100644
index 0000000000000000000000000000000000000000..deb3bfb7e24baad162e307044538b2ffa88e2c60
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_bfloat16.h
@@ -0,0 +1,293 @@
+/**
+ * MIT License
+ *
+ * Copyright (c) 2019 - 2022 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.
+ */
+
+/*!\file
+ * \brief hip_bfloat16.h provides struct for hip_bfloat16 typedef
+ */
+
+#ifndef _HIP_INCLUDE_HIP_AMD_DETAIL_HIP_BFLOAT16_H_
+#define _HIP_INCLUDE_HIP_AMD_DETAIL_HIP_BFLOAT16_H_
+
+#include "host_defines.h"
+#if defined(__HIPCC_RTC__)
+ #define __HOST_DEVICE__ __device__
+#else
+ #define __HOST_DEVICE__ __host__ __device__
+#endif
+
+#if __cplusplus < 201103L || !defined(__HIPCC__)
+
+// If this is a C compiler, C++ compiler below C++11, or a host-only compiler, we only
+// include a minimal definition of hip_bfloat16
+
+#include
+/*! \brief Struct to represent a 16 bit brain floating point number. */
+typedef struct
+{
+ uint16_t data;
+} hip_bfloat16;
+
+#else // __cplusplus < 201103L || !defined(__HIPCC__)
+
+#include
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wshadow"
+struct hip_bfloat16
+{
+ __hip_uint16_t data;
+
+ enum truncate_t
+ {
+ truncate
+ };
+
+ __HOST_DEVICE__ hip_bfloat16() = default;
+
+ // round upper 16 bits of IEEE float to convert to bfloat16
+ explicit __HOST_DEVICE__ hip_bfloat16(float f)
+ : data(float_to_bfloat16(f))
+ {
+ }
+
+ explicit __HOST_DEVICE__ hip_bfloat16(float f, truncate_t)
+ : data(truncate_float_to_bfloat16(f))
+ {
+ }
+
+ // zero extend lower 16 bits of bfloat16 to convert to IEEE float
+ __HOST_DEVICE__ operator float() const
+ {
+ union
+ {
+ uint32_t int32;
+ float fp32;
+ } u = {uint32_t(data) << 16};
+ return u.fp32;
+ }
+
+ __HOST_DEVICE__ hip_bfloat16 &operator=(const float& f)
+ {
+ data = float_to_bfloat16(f);
+ return *this;
+ }
+
+ static __HOST_DEVICE__ hip_bfloat16 round_to_bfloat16(float f)
+ {
+ hip_bfloat16 output;
+ output.data = float_to_bfloat16(f);
+ return output;
+ }
+
+ static __HOST_DEVICE__ hip_bfloat16 round_to_bfloat16(float f, truncate_t)
+ {
+ hip_bfloat16 output;
+ output.data = truncate_float_to_bfloat16(f);
+ return output;
+ }
+
+private:
+ static __HOST_DEVICE__ __hip_uint16_t float_to_bfloat16(float f)
+ {
+ union
+ {
+ float fp32;
+ uint32_t int32;
+ } u = {f};
+ if(~u.int32 & 0x7f800000)
+ {
+ // When the exponent bits are not all 1s, then the value is zero, normal,
+ // or subnormal. We round the bfloat16 mantissa up by adding 0x7FFF, plus
+ // 1 if the least significant bit of the bfloat16 mantissa is 1 (odd).
+ // This causes the bfloat16's mantissa to be incremented by 1 if the 16
+ // least significant bits of the float mantissa are greater than 0x8000,
+ // or if they are equal to 0x8000 and the least significant bit of the
+ // bfloat16 mantissa is 1 (odd). This causes it to be rounded to even when
+ // the lower 16 bits are exactly 0x8000. If the bfloat16 mantissa already
+ // has the value 0x7f, then incrementing it causes it to become 0x00 and
+ // the exponent is incremented by one, which is the next higher FP value
+ // to the unrounded bfloat16 value. When the bfloat16 value is subnormal
+ // with an exponent of 0x00 and a mantissa of 0x7F, it may be rounded up
+ // to a normal value with an exponent of 0x01 and a mantissa of 0x00.
+ // When the bfloat16 value has an exponent of 0xFE and a mantissa of 0x7F,
+ // incrementing it causes it to become an exponent of 0xFF and a mantissa
+ // of 0x00, which is Inf, the next higher value to the unrounded value.
+ u.int32 += 0x7fff + ((u.int32 >> 16) & 1); // Round to nearest, round to even
+ }
+ else if(u.int32 & 0xffff)
+ {
+ // When all of the exponent bits are 1, the value is Inf or NaN.
+ // Inf is indicated by a zero mantissa. NaN is indicated by any nonzero
+ // mantissa bit. Quiet NaN is indicated by the most significant mantissa
+ // bit being 1. Signaling NaN is indicated by the most significant
+ // mantissa bit being 0 but some other bit(s) being 1. If any of the
+ // lower 16 bits of the mantissa are 1, we set the least significant bit
+ // of the bfloat16 mantissa, in order to preserve signaling NaN in case
+ // the bloat16's mantissa bits are all 0.
+ u.int32 |= 0x10000; // Preserve signaling NaN
+ }
+ return __hip_uint16_t(u.int32 >> 16);
+ }
+
+ // Truncate instead of rounding, preserving SNaN
+ static __HOST_DEVICE__ __hip_uint16_t truncate_float_to_bfloat16(float f)
+ {
+ union
+ {
+ float fp32;
+ uint32_t int32;
+ } u = {f};
+ return __hip_uint16_t(u.int32 >> 16) | (!(~u.int32 & 0x7f800000) && (u.int32 & 0xffff));
+ }
+};
+#pragma clang diagnostic pop
+
+typedef struct
+{
+ __hip_uint16_t data;
+} hip_bfloat16_public;
+
+static_assert(__hip_internal::is_standard_layout{},
+ "hip_bfloat16 is not a standard layout type, and thus is "
+ "incompatible with C.");
+
+static_assert(__hip_internal::is_trivial{},
+ "hip_bfloat16 is not a trivial type, and thus is "
+ "incompatible with C.");
+#if !defined(__HIPCC_RTC__)
+static_assert(sizeof(hip_bfloat16) == sizeof(hip_bfloat16_public)
+ && offsetof(hip_bfloat16, data) == offsetof(hip_bfloat16_public, data),
+ "internal hip_bfloat16 does not match public hip_bfloat16");
+
+inline std::ostream& operator<<(std::ostream& os, const hip_bfloat16& bf16)
+{
+ return os << float(bf16);
+}
+#endif
+
+inline __HOST_DEVICE__ hip_bfloat16 operator+(hip_bfloat16 a)
+{
+ return a;
+}
+inline __HOST_DEVICE__ hip_bfloat16 operator-(hip_bfloat16 a)
+{
+ a.data ^= 0x8000;
+ return a;
+}
+inline __HOST_DEVICE__ hip_bfloat16 operator+(hip_bfloat16 a, hip_bfloat16 b)
+{
+ return hip_bfloat16(float(a) + float(b));
+}
+inline __HOST_DEVICE__ hip_bfloat16 operator-(hip_bfloat16 a, hip_bfloat16 b)
+{
+ return hip_bfloat16(float(a) - float(b));
+}
+inline __HOST_DEVICE__ hip_bfloat16 operator*(hip_bfloat16 a, hip_bfloat16 b)
+{
+ return hip_bfloat16(float(a) * float(b));
+}
+inline __HOST_DEVICE__ hip_bfloat16 operator/(hip_bfloat16 a, hip_bfloat16 b)
+{
+ return hip_bfloat16(float(a) / float(b));
+}
+inline __HOST_DEVICE__ bool operator<(hip_bfloat16 a, hip_bfloat16 b)
+{
+ return float(a) < float(b);
+}
+inline __HOST_DEVICE__ bool operator==(hip_bfloat16 a, hip_bfloat16 b)
+{
+ return float(a) == float(b);
+}
+inline __HOST_DEVICE__ bool operator>(hip_bfloat16 a, hip_bfloat16 b)
+{
+ return b < a;
+}
+inline __HOST_DEVICE__ bool operator<=(hip_bfloat16 a, hip_bfloat16 b)
+{
+ return !(a > b);
+}
+inline __HOST_DEVICE__ bool operator!=(hip_bfloat16 a, hip_bfloat16 b)
+{
+ return !(a == b);
+}
+inline __HOST_DEVICE__ bool operator>=(hip_bfloat16 a, hip_bfloat16 b)
+{
+ return !(a < b);
+}
+inline __HOST_DEVICE__ hip_bfloat16& operator+=(hip_bfloat16& a, hip_bfloat16 b)
+{
+ return a = a + b;
+}
+inline __HOST_DEVICE__ hip_bfloat16& operator-=(hip_bfloat16& a, hip_bfloat16 b)
+{
+ return a = a - b;
+}
+inline __HOST_DEVICE__ hip_bfloat16& operator*=(hip_bfloat16& a, hip_bfloat16 b)
+{
+ return a = a * b;
+}
+inline __HOST_DEVICE__ hip_bfloat16& operator/=(hip_bfloat16& a, hip_bfloat16 b)
+{
+ return a = a / b;
+}
+inline __HOST_DEVICE__ hip_bfloat16& operator++(hip_bfloat16& a)
+{
+ return a += hip_bfloat16(1.0f);
+}
+inline __HOST_DEVICE__ hip_bfloat16& operator--(hip_bfloat16& a)
+{
+ return a -= hip_bfloat16(1.0f);
+}
+inline __HOST_DEVICE__ hip_bfloat16 operator++(hip_bfloat16& a, int)
+{
+ hip_bfloat16 orig = a;
+ ++a;
+ return orig;
+}
+inline __HOST_DEVICE__ hip_bfloat16 operator--(hip_bfloat16& a, int)
+{
+ hip_bfloat16 orig = a;
+ --a;
+ return orig;
+}
+
+namespace std
+{
+ constexpr __HOST_DEVICE__ bool isinf(hip_bfloat16 a)
+ {
+ return !(~a.data & 0x7f80) && !(a.data & 0x7f);
+ }
+ constexpr __HOST_DEVICE__ bool isnan(hip_bfloat16 a)
+ {
+ return !(~a.data & 0x7f80) && +(a.data & 0x7f);
+ }
+ constexpr __HOST_DEVICE__ bool iszero(hip_bfloat16 a)
+ {
+ return !(a.data & 0x7fff);
+ }
+}
+
+#endif // __cplusplus < 201103L || !defined(__HIPCC__)
+
+#endif // _HIP_BFLOAT16_H_
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_common.h b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_common.h
new file mode 100644
index 0000000000000000000000000000000000000000..0c7dc51b503e5101abc365a2a62be471d00962e1
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_common.h
@@ -0,0 +1,32 @@
+/*
+Copyright (c) 2019 - 2021 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_HIP_COMMON_H
+#define HIP_INCLUDE_HIP_AMD_DETAIL_HIP_COMMON_H
+
+#if defined(__clang__) && defined(__HIP__)
+#define __HIP_CLANG_ONLY__ 1
+#else
+#define __HIP_CLANG_ONLY__ 0
+#endif
+
+#endif // HIP_INCLUDE_HIP_AMD_DETAIL_HIP_COMMON_H
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_complex.h b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_complex.h
new file mode 100644
index 0000000000000000000000000000000000000000..9ca29eafd206183a7de681aab31d033dea07f9f6
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_complex.h
@@ -0,0 +1,174 @@
+/*
+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.
+*/
+
+/* The header defines complex numbers and related functions*/
+
+#ifndef HIP_INCLUDE_HIP_AMD_DETAIL_HIP_COMPLEX_H
+#define HIP_INCLUDE_HIP_AMD_DETAIL_HIP_COMPLEX_H
+
+#if !defined(__HIPCC_RTC__)
+#include "hip/amd_detail/amd_hip_vector_types.h"
+#endif
+
+#if defined(__HIPCC_RTC__)
+#define __HOST_DEVICE__ __device__
+#else
+#define __HOST_DEVICE__ __host__ __device__
+// TODO: Clang has a bug which allows device functions to call std functions
+// when std functions are introduced into default namespace by using statement.
+// math.h may be included after this bug is fixed.
+#if __cplusplus
+#include
+#else
+#include "math.h"
+#endif
+#endif // !defined(__HIPCC_RTC__)
+
+typedef float2 hipFloatComplex;
+
+__HOST_DEVICE__ static inline float hipCrealf(hipFloatComplex z) { return z.x; }
+
+__HOST_DEVICE__ static inline float hipCimagf(hipFloatComplex z) { return z.y; }
+
+__HOST_DEVICE__ static inline hipFloatComplex make_hipFloatComplex(float a, float b) {
+ hipFloatComplex z;
+ z.x = a;
+ z.y = b;
+ return z;
+}
+
+__HOST_DEVICE__ static inline hipFloatComplex hipConjf(hipFloatComplex z) {
+ hipFloatComplex ret;
+ ret.x = z.x;
+ ret.y = -z.y;
+ return ret;
+}
+
+__HOST_DEVICE__ static inline float hipCsqabsf(hipFloatComplex z) {
+ return z.x * z.x + z.y * z.y;
+}
+
+__HOST_DEVICE__ static inline hipFloatComplex hipCaddf(hipFloatComplex p, hipFloatComplex q) {
+ return make_hipFloatComplex(p.x + q.x, p.y + q.y);
+}
+
+__HOST_DEVICE__ static inline hipFloatComplex hipCsubf(hipFloatComplex p, hipFloatComplex q) {
+ return make_hipFloatComplex(p.x - q.x, p.y - q.y);
+}
+
+__HOST_DEVICE__ static inline hipFloatComplex hipCmulf(hipFloatComplex p, hipFloatComplex q) {
+ return make_hipFloatComplex(p.x * q.x - p.y * q.y, p.y * q.x + p.x * q.y);
+}
+
+__HOST_DEVICE__ static inline hipFloatComplex hipCdivf(hipFloatComplex p, hipFloatComplex q) {
+ float sqabs = hipCsqabsf(q);
+ hipFloatComplex ret;
+ ret.x = (p.x * q.x + p.y * q.y) / sqabs;
+ ret.y = (p.y * q.x - p.x * q.y) / sqabs;
+ return ret;
+}
+
+__HOST_DEVICE__ static inline float hipCabsf(hipFloatComplex z) { return sqrtf(hipCsqabsf(z)); }
+
+
+typedef double2 hipDoubleComplex;
+
+__HOST_DEVICE__ static inline double hipCreal(hipDoubleComplex z) { return z.x; }
+
+__HOST_DEVICE__ static inline double hipCimag(hipDoubleComplex z) { return z.y; }
+
+__HOST_DEVICE__ static inline hipDoubleComplex make_hipDoubleComplex(double a, double b) {
+ hipDoubleComplex z;
+ z.x = a;
+ z.y = b;
+ return z;
+}
+
+__HOST_DEVICE__ static inline hipDoubleComplex hipConj(hipDoubleComplex z) {
+ hipDoubleComplex ret;
+ ret.x = z.x;
+ ret.y = -z.y;
+ return ret;
+}
+
+__HOST_DEVICE__ static inline double hipCsqabs(hipDoubleComplex z) {
+ return z.x * z.x + z.y * z.y;
+}
+
+__HOST_DEVICE__ static inline hipDoubleComplex hipCadd(hipDoubleComplex p, hipDoubleComplex q) {
+ return make_hipDoubleComplex(p.x + q.x, p.y + q.y);
+}
+
+__HOST_DEVICE__ static inline hipDoubleComplex hipCsub(hipDoubleComplex p, hipDoubleComplex q) {
+ return make_hipDoubleComplex(p.x - q.x, p.y - q.y);
+}
+
+__HOST_DEVICE__ static inline hipDoubleComplex hipCmul(hipDoubleComplex p, hipDoubleComplex q) {
+ return make_hipDoubleComplex(p.x * q.x - p.y * q.y, p.y * q.x + p.x * q.y);
+}
+
+__HOST_DEVICE__ static inline hipDoubleComplex hipCdiv(hipDoubleComplex p, hipDoubleComplex q) {
+ double sqabs = hipCsqabs(q);
+ hipDoubleComplex ret;
+ ret.x = (p.x * q.x + p.y * q.y) / sqabs;
+ ret.y = (p.y * q.x - p.x * q.y) / sqabs;
+ return ret;
+}
+
+__HOST_DEVICE__ static inline double hipCabs(hipDoubleComplex z) { return sqrt(hipCsqabs(z)); }
+
+typedef hipFloatComplex hipComplex;
+
+__HOST_DEVICE__ static inline hipComplex make_hipComplex(float x, float y) {
+ return make_hipFloatComplex(x, y);
+}
+
+__HOST_DEVICE__ static inline hipFloatComplex hipComplexDoubleToFloat(hipDoubleComplex z) {
+ return make_hipFloatComplex((float)z.x, (float)z.y);
+}
+
+__HOST_DEVICE__ static inline hipDoubleComplex hipComplexFloatToDouble(hipFloatComplex z) {
+ return make_hipDoubleComplex((double)z.x, (double)z.y);
+}
+
+__HOST_DEVICE__ static inline hipComplex hipCfmaf(hipComplex p, hipComplex q, hipComplex r) {
+ float real = (p.x * q.x) + r.x;
+ float imag = (q.x * p.y) + r.y;
+
+ real = -(p.y * q.y) + real;
+ imag = (p.x * q.y) + imag;
+
+ return make_hipComplex(real, imag);
+}
+
+__HOST_DEVICE__ static inline hipDoubleComplex hipCfma(hipDoubleComplex p, hipDoubleComplex q,
+ hipDoubleComplex r) {
+ double real = (p.x * q.x) + r.x;
+ double imag = (q.x * p.y) + r.y;
+
+ real = -(p.y * q.y) + real;
+ imag = (p.x * q.y) + imag;
+
+ return make_hipDoubleComplex(real, imag);
+}
+
+#endif //HIP_INCLUDE_HIP_AMD_DETAIL_HIP_COMPLEX_H
diff --git a/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_cooperative_groups.h b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_cooperative_groups.h
new file mode 100644
index 0000000000000000000000000000000000000000..c01039a7e1cca2d4210c9f9e00def882d721acf9
--- /dev/null
+++ b/code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib/python3.10/site-packages/triton/backends/amd/include/hip/amd_detail/amd_hip_cooperative_groups.h
@@ -0,0 +1,835 @@
+/*
+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.
+*/
+
+/**
+ * @file amd_detail/hip_cooperative_groups.h
+ *
+ * @brief Device side implementation of `Cooperative Group` feature.
+ *
+ * Defines new types and device API wrappers related to `Cooperative Group`
+ * feature, which the programmer can directly use in his kernel(s) in order to
+ * make use of this feature.
+ */
+#ifndef HIP_INCLUDE_HIP_AMD_DETAIL_HIP_COOPERATIVE_GROUPS_H
+#define HIP_INCLUDE_HIP_AMD_DETAIL_HIP_COOPERATIVE_GROUPS_H
+
+#if __cplusplus
+#if !defined(__HIPCC_RTC__)
+#include
+#endif
+
+namespace cooperative_groups {
+
+/** @brief The base type of all cooperative group types
+ *
+ * \details Holds the key properties of a constructed cooperative group types
+ * object, like the group type, its size, etc
+ *
+ * @note Cooperative groups feature is implemented on Linux, under developement
+ * on Windows.
+ */
+class thread_group {
+ protected:
+ uint32_t _type; // thread_group type
+ uint32_t _size; // total number of threads in the tread_group
+ uint64_t _mask; // Lanemask for coalesced and tiled partitioned group types,
+ // LSB represents lane 0, and MSB represents lane 63
+
+ // Construct a thread group, and set thread group type and other essential
+ // thread group properties. This generic thread group is directly constructed
+ // only when the group is supposed to contain only the calling the thread
+ // (throurh the API - `this_thread()`), and in all other cases, this thread
+ // group object is a sub-object of some other derived thread group object
+ __CG_QUALIFIER__ thread_group(internal::group_type type, uint32_t size = static_cast